blob: 6a6181cd37157bbc90dee852cf0ea00f417afa78 [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>
56#include <system/audio_effects/effect_virtualizer_stage.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>
Eric Laurent81784c32012-11-19 14:55:58 -080068
Mikhail Naganov2996f672019-04-18 12:29:59 -070069#include <audiomanager/AudioManager.h>
Eric Laurent81784c32012-11-19 14:55:58 -080070#include <powermanager/PowerManager.h>
71
Kevin Rocard7588ff42018-01-08 11:11:30 -080072#include <media/audiohal/EffectsFactoryHalInterface.h>
Kevin Rocard069c2712018-03-29 19:09:14 -070073#include <media/audiohal/StreamHalInterface.h>
Kevin Rocard7588ff42018-01-08 11:11:30 -080074
Eric Laurent81784c32012-11-19 14:55:58 -080075#include "AudioFlinger.h"
Eric Laurent81784c32012-11-19 14:55:58 -080076#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070077#include "FastCapture.h"
Andy Hungab7ef302018-05-15 19:35:29 -070078#include <mediautils/SchedulingPolicyService.h>
79#include <mediautils/ServiceUtilities.h>
Eric Laurent81784c32012-11-19 14:55:58 -080080
Eric Laurent81784c32012-11-19 14:55:58 -080081#ifdef ADD_BATTERY_DATA
82#include <media/IMediaPlayerService.h>
83#include <media/IMediaDeathNotifier.h>
84#endif
85
Eric Laurent81784c32012-11-19 14:55:58 -080086#ifdef DEBUG_CPU_USAGE
Eric Tan5b13ff82018-07-27 11:20:17 -070087#include <audio_utils/Statistics.h>
Eric Laurent81784c32012-11-19 14:55:58 -080088#include <cpustats/ThreadCpuUsage.h>
89#endif
90
Glenn Kastenc05b8d72016-03-24 09:48:17 -070091#include "AutoPark.h"
92
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080093#include <pthread.h>
94#include "TypedLogger.h"
95
Eric Laurent81784c32012-11-19 14:55:58 -080096// ----------------------------------------------------------------------------
97
98// Note: the following macro is used for extremely verbose logging message. In
99// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
100// 0; but one side effect of this is to turn all LOGV's as well. Some messages
101// are so verbose that we want to suppress them even when we have ALOG_ASSERT
102// turned on. Do not uncomment the #def below unless you really know what you
103// are doing and want to see all of the extremely verbose messages.
104//#define VERY_VERY_VERBOSE_LOGGING
105#ifdef VERY_VERY_VERBOSE_LOGGING
106#define ALOGVV ALOGV
107#else
108#define ALOGVV(a...) do { } while(0)
109#endif
110
Andy Hung6770c6f2015-04-07 13:43:36 -0700111// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700112#define max(a, b) ((a) > (b) ? (a) : (b))
Philip P. Moltmannbda45752020-07-17 16:41:18 -0700113
Andy Hung6770c6f2015-04-07 13:43:36 -0700114template <typename T>
115static inline T min(const T& a, const T& b)
116{
117 return a < b ? a : b;
118}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700119
Eric Laurent81784c32012-11-19 14:55:58 -0800120namespace android {
121
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700122using media::IEffectClient;
Svet Ganov33761132021-05-13 22:51:08 +0000123using content::AttributionSourceState;
Ytai Ben-Tsvi9cd89812020-07-01 17:12:06 -0700124
Eric Laurent81784c32012-11-19 14:55:58 -0800125// retry counts for buffer fill timeout
126// 50 * ~20msecs = 1 second
127static const int8_t kMaxTrackRetries = 50;
128static const int8_t kMaxTrackStartupRetries = 50;
Andy Hung455982f2021-04-27 17:46:12 -0700129
Eric Laurent81784c32012-11-19 14:55:58 -0800130// allow less retry attempts on direct output thread.
131// direct outputs can be a scarce resource in audio hardware and should
132// be released as quickly as possible.
Andy Hung455982f2021-04-27 17:46:12 -0700133// Notes:
134// 1) The retry duration kMaxTrackRetriesDirectMs may be increased
135// in case the data write is bursty for the AudioTrack. The application
136// should endeavor to write at least once every kMaxTrackRetriesDirectMs
137// to prevent an underrun situation. If the data is bursty, then
138// the application can also throttle the data sent to be even.
139// 2) For compressed audio data, any data present in the AudioTrack buffer
140// will be sent and reset the retry count. This delivers data as
141// it arrives, with approximately kDirectMinSleepTimeUs = 10ms checking interval.
142// 3) For linear PCM or proportional PCM, we wait one period for a period's worth
143// of data to be available, then any remaining data is delivered.
144// This is required to ensure the last bit of data is delivered before underrun.
145//
146// Sleep time per cycle is kDirectMinSleepTimeUs for compressed tracks
147// or the size of the HAL period for proportional / linear PCM tracks.
148static const int32_t kMaxTrackRetriesDirectMs = 200;
Eric Laurent81784c32012-11-19 14:55:58 -0800149
150// don't warn about blocked writes or record buffer overflows more often than this
151static const nsecs_t kWarningThrottleNs = seconds(5);
152
153// RecordThread loop sleep time upon application overrun or audio HAL read error
154static const int kRecordThreadSleepUs = 5000;
155
Eric Laurent10351942014-05-08 18:49:52 -0700156// maximum time to wait in sendConfigEvent_l() for a status to be received
157static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800158
159// minimum sleep time for the mixer thread loop when tracks are active but in underrun
160static const uint32_t kMinThreadSleepTimeUs = 5000;
161// maximum divider applied to the active sleep time in the mixer thread loop
162static const uint32_t kMaxThreadSleepTimeShift = 2;
163
Andy Hung09a50072014-02-27 14:30:47 -0800164// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700165// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800166static const uint32_t kMinNormalSinkBufferSizeMs = 20;
167// maximum normal sink buffer size
168static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800169
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700170// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
171// FIXME This should be based on experimentally observed scheduling jitter
172static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
173
Eric Laurent972a1732013-09-04 09:42:59 -0700174// Offloaded output thread standby delay: allows track transition without going to standby
175static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
176
Eric Laurent51716182016-02-29 18:00:56 -0800177// Direct output thread minimum sleep time in idle or active(underrun) state
178static const nsecs_t kDirectMinSleepTimeUs = 10000;
179
Glenn Kasten1b291842016-07-18 14:55:21 -0700180// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
181// balance between power consumption and latency, and allows threads to be scheduled reliably
182// by the CFS scheduler.
183// FIXME Express other hardcoded references to 20ms with references to this constant and move
184// it appropriately.
185#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800186
Eric Laurent81784c32012-11-19 14:55:58 -0800187// Whether to use fast mixer
188static const enum {
189 FastMixer_Never, // never initialize or use: for debugging only
190 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
191 // normal mixer multiplier is 1
192 FastMixer_Static, // initialize if needed, then use all the time if initialized,
193 // multiplier is calculated based on min & max normal mixer buffer size
194 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
195 // multiplier is calculated based on min & max normal mixer buffer size
196 // FIXME for FastMixer_Dynamic:
197 // Supporting this option will require fixing HALs that can't handle large writes.
198 // For example, one HAL implementation returns an error from a large write,
199 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
200 // We could either fix the HAL implementations, or provide a wrapper that breaks
201 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
202} kUseFastMixer = FastMixer_Static;
203
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700204// Whether to use fast capture
205static const enum {
206 FastCapture_Never, // never initialize or use: for debugging only
207 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
208 FastCapture_Static, // initialize if needed, then use all the time if initialized
209} kUseFastCapture = FastCapture_Static;
210
Eric Laurent81784c32012-11-19 14:55:58 -0800211// Priorities for requestPriority
212static const int kPriorityAudioApp = 2;
213static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700214static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800215
Glenn Kastenea38ee72016-04-18 11:08:01 -0700216// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
217// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
218// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700219
220// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800221static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800222
Glenn Kasten03490092014-05-27 12:30:54 -0700223// The minimum and maximum allowed values
224static const int kFastTrackMultiplierMin = 1;
225static const int kFastTrackMultiplierMax = 2;
226
227// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
228static int sFastTrackMultiplier = kFastTrackMultiplier;
229
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700230// See Thread::readOnlyHeap().
231// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
232// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
233// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700234static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700235
Eric Laurent81784c32012-11-19 14:55:58 -0800236// ----------------------------------------------------------------------------
237
Andy Hungb68f5eb2019-12-03 16:49:17 -0800238// TODO: move all toString helpers to audio.h
239// under #ifdef __cplusplus #endif
240static std::string patchSinksToString(const struct audio_patch *patch)
241{
242 std::stringstream ss;
243 for (size_t i = 0; i < patch->num_sinks; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700244 if (i > 0) {
245 ss << "|";
246 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800247 ss << "(" << toString(patch->sinks[i].ext.device.type)
248 << ", " << patch->sinks[i].ext.device.address << ")";
249 }
250 return ss.str();
251}
252
253static std::string patchSourcesToString(const struct audio_patch *patch)
254{
255 std::stringstream ss;
256 for (size_t i = 0; i < patch->num_sources; ++i) {
Andy Hungc2b11cb2020-04-22 09:04:01 -0700257 if (i > 0) {
258 ss << "|";
259 }
Andy Hungb68f5eb2019-12-03 16:49:17 -0800260 ss << "(" << toString(patch->sources[i].ext.device.type)
261 << ", " << patch->sources[i].ext.device.address << ")";
262 }
263 return ss.str();
264}
265
Glenn Kasten03490092014-05-27 12:30:54 -0700266static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
267
268static void sFastTrackMultiplierInit()
269{
270 char value[PROPERTY_VALUE_MAX];
271 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
272 char *endptr;
273 unsigned long ul = strtoul(value, &endptr, 0);
274 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
275 sFastTrackMultiplier = (int) ul;
276 }
277 }
278}
279
280// ----------------------------------------------------------------------------
281
Eric Laurent81784c32012-11-19 14:55:58 -0800282#ifdef ADD_BATTERY_DATA
283// To collect the amplifier usage
284static void addBatteryData(uint32_t params) {
285 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
286 if (service == NULL) {
287 // it already logged
288 return;
289 }
290
291 service->addBatteryData(params);
292}
293#endif
294
Andy Hung3f0c9022016-01-15 17:49:46 -0800295// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
296struct {
297 // call when you acquire a partial wakelock
298 void acquire(const sp<IBinder> &wakeLockToken) {
299 pthread_mutex_lock(&mLock);
300 if (wakeLockToken.get() == nullptr) {
301 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
302 } else {
303 if (mCount == 0) {
304 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
305 }
306 ++mCount;
307 }
308 pthread_mutex_unlock(&mLock);
309 }
310
311 // call when you release a partial wakelock.
312 void release(const sp<IBinder> &wakeLockToken) {
313 if (wakeLockToken.get() == nullptr) {
314 return;
315 }
316 pthread_mutex_lock(&mLock);
317 if (--mCount < 0) {
318 ALOGE("negative wakelock count");
319 mCount = 0;
320 }
321 pthread_mutex_unlock(&mLock);
322 }
323
324 // retrieves the boottime timebase offset from monotonic.
325 int64_t getBoottimeOffset() {
326 pthread_mutex_lock(&mLock);
327 int64_t boottimeOffset = mBoottimeOffset;
328 pthread_mutex_unlock(&mLock);
329 return boottimeOffset;
330 }
331
332 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
333 // and the selected timebase.
334 // Currently only TIMEBASE_BOOTTIME is allowed.
335 //
336 // This only needs to be called upon acquiring the first partial wakelock
337 // after all other partial wakelocks are released.
338 //
339 // We do an empirical measurement of the offset rather than parsing
340 // /proc/timer_list since the latter is not a formal kernel ABI.
341 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
342 int clockbase;
343 switch (timebase) {
344 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
345 clockbase = SYSTEM_TIME_BOOTTIME;
346 break;
347 default:
348 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
349 break;
350 }
351 // try three times to get the clock offset, choose the one
352 // with the minimum gap in measurements.
353 const int tries = 3;
354 nsecs_t bestGap, measured;
355 for (int i = 0; i < tries; ++i) {
356 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
357 const nsecs_t tbase = systemTime(clockbase);
358 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
359 const nsecs_t gap = tmono2 - tmono;
360 if (i == 0 || gap < bestGap) {
361 bestGap = gap;
362 measured = tbase - ((tmono + tmono2) >> 1);
363 }
364 }
365
366 // to avoid micro-adjusting, we don't change the timebase
367 // unless it is significantly different.
368 //
369 // Assumption: It probably takes more than toleranceNs to
370 // suspend and resume the device.
371 static int64_t toleranceNs = 10000; // 10 us
372 if (llabs(*offset - measured) > toleranceNs) {
373 ALOGV("Adjusting timebase offset old: %lld new: %lld",
374 (long long)*offset, (long long)measured);
375 *offset = measured;
376 }
377 }
378
379 pthread_mutex_t mLock;
380 int32_t mCount;
381 int64_t mBoottimeOffset;
382} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800383
384// ----------------------------------------------------------------------------
385// CPU Stats
386// ----------------------------------------------------------------------------
387
388class CpuStats {
389public:
390 CpuStats();
391 void sample(const String8 &title);
392#ifdef DEBUG_CPU_USAGE
393private:
394 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700395 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800396
Andy Hung16698b82018-08-01 10:48:38 -0700397 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800398
399 int mCpuNum; // thread's current CPU number
400 int mCpukHz; // frequency of thread's current CPU in kHz
401#endif
402};
403
404CpuStats::CpuStats()
405#ifdef DEBUG_CPU_USAGE
406 : mCpuNum(-1), mCpukHz(-1)
407#endif
408{
409}
410
Glenn Kasten0f11b512014-01-31 16:18:54 -0800411void CpuStats::sample(const String8 &title
412#ifndef DEBUG_CPU_USAGE
413 __unused
414#endif
415 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800416#ifdef DEBUG_CPU_USAGE
417 // get current thread's delta CPU time in wall clock ns
418 double wcNs;
419 bool valid = mCpuUsage.sampleAndEnable(wcNs);
420
421 // record sample for wall clock statistics
422 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700423 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800424 }
425
426 // get the current CPU number
427 int cpuNum = sched_getcpu();
428
429 // get the current CPU frequency in kHz
430 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
431
432 // check if either CPU number or frequency changed
433 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
434 mCpuNum = cpuNum;
435 mCpukHz = cpukHz;
436 // ignore sample for purposes of cycles
437 valid = false;
438 }
439
440 // if no change in CPU number or frequency, then record sample for cycle statistics
441 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700442 const double cycles = wcNs * cpukHz * 0.000001;
443 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800444 }
445
Eric Tan5b13ff82018-07-27 11:20:17 -0700446 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800447 // mCpuUsage.elapsed() is expensive, so don't call it every loop
448 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700449 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800450 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700451 const double perLoop = elapsed / (double) n;
452 const double perLoop100 = perLoop * 0.01;
453 const double perLoop1k = perLoop * 0.001;
454 const double mean = mWcStats.getMean();
455 const double stddev = mWcStats.getStdDev();
456 const double minimum = mWcStats.getMin();
457 const double maximum = mWcStats.getMax();
458 const double meanCycles = mHzStats.getMean();
459 const double stddevCycles = mHzStats.getStdDev();
460 const double minCycles = mHzStats.getMin();
461 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800462 mCpuUsage.resetElapsed();
463 mWcStats.reset();
464 mHzStats.reset();
465 ALOGD("CPU usage for %s over past %.1f secs\n"
466 " (%u mixer loops at %.1f mean ms per loop):\n"
467 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
468 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
469 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
470 title.string(),
471 elapsed * .000000001, n, perLoop * .000001,
472 mean * .001,
473 stddev * .001,
474 minimum * .001,
475 maximum * .001,
476 mean / perLoop100,
477 stddev / perLoop100,
478 minimum / perLoop100,
479 maximum / perLoop100,
480 meanCycles / perLoop1k,
481 stddevCycles / perLoop1k,
482 minCycles / perLoop1k,
483 maxCycles / perLoop1k);
484
485 }
486 }
487#endif
488};
489
490// ----------------------------------------------------------------------------
491// ThreadBase
492// ----------------------------------------------------------------------------
493
Glenn Kasten97b7b752014-09-28 13:04:24 -0700494// static
495const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
496{
497 switch (type) {
498 case MIXER:
499 return "MIXER";
500 case DIRECT:
501 return "DIRECT";
502 case DUPLICATING:
503 return "DUPLICATING";
504 case RECORD:
505 return "RECORD";
506 case OFFLOAD:
507 return "OFFLOAD";
Andy Hungea840382020-05-05 21:50:17 -0700508 case MMAP_PLAYBACK:
509 return "MMAP_PLAYBACK";
510 case MMAP_CAPTURE:
511 return "MMAP_CAPTURE";
Eric Laurentb3f315a2021-07-13 15:09:05 +0200512 case VIRTUALIZER_STAGE:
513 return "VIRTUALIZER_STAGE";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700514 default:
515 return "unknown";
516 }
517}
518
Eric Laurent81784c32012-11-19 14:55:58 -0800519AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -0700520 type_t type, bool systemReady, bool isOut)
Eric Laurent81784c32012-11-19 14:55:58 -0800521 : Thread(false /*canCallJava*/),
522 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700523 mAudioFlinger(audioFlinger),
Andy Hungcf10d742020-04-28 15:38:24 -0700524 mThreadMetrics(std::string(AMEDIAMETRICS_KEY_PREFIX_AUDIO_THREAD) + std::to_string(id),
525 isOut),
526 mIsOut(isOut),
Glenn Kasten70949c42013-08-06 07:40:12 -0700527 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800528 // are set by PlaybackThread::readOutputParameters_l() or
529 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700530 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabinc52b1ff2019-10-31 17:20:42 -0700531 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700532 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800533 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700534 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800535 mSystemReady(systemReady),
536 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800537{
Andy Hungcf10d742020-04-28 15:38:24 -0700538 mThreadMetrics.logConstructor(getpid(), threadTypeToString(type), id);
Eric Laurent296fb132015-05-01 11:38:42 -0700539 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800540}
541
542AudioFlinger::ThreadBase::~ThreadBase()
543{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700544 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700545 mConfigEvents.clear();
546
Eric Laurent81784c32012-11-19 14:55:58 -0800547 // do not lock the mutex in destructor
548 releaseWakeLock_l();
549 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800550 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800551 binder->unlinkToDeath(mDeathRecipient);
552 }
Andy Hungd0979812019-02-21 15:51:44 -0800553
554 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800555}
556
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700557status_t AudioFlinger::ThreadBase::readyToRun()
558{
559 status_t status = initCheck();
560 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800561 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700562 } else {
563 ALOGE("No working audio driver found.");
564 }
565 return status;
566}
567
Eric Laurent81784c32012-11-19 14:55:58 -0800568void AudioFlinger::ThreadBase::exit()
569{
570 ALOGV("ThreadBase::exit");
571 // do any cleanup required for exit to succeed
572 preExit();
573 {
574 // This lock prevents the following race in thread (uniprocessor for illustration):
575 // if (!exitPending()) {
576 // // context switch from here to exit()
577 // // exit() calls requestExit(), what exitPending() observes
578 // // exit() calls signal(), which is dropped since no waiters
579 // // context switch back from exit() to here
580 // mWaitWorkCV.wait(...);
581 // // now thread is hung
582 // }
583 AutoMutex lock(mLock);
584 requestExit();
585 mWaitWorkCV.broadcast();
586 }
587 // When Thread::requestExitAndWait is made virtual and this method is renamed to
588 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
589 requestExitAndWait();
590}
591
592status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
593{
Eric Laurent81784c32012-11-19 14:55:58 -0800594 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
595 Mutex::Autolock _l(mLock);
596
Eric Laurent10351942014-05-08 18:49:52 -0700597 return sendSetParameterConfigEvent_l(keyValuePairs);
598}
599
600// sendConfigEvent_l() must be called with ThreadBase::mLock held
601// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
602status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
603{
604 status_t status = NO_ERROR;
605
Eric Laurent72e3f392015-05-20 14:43:50 -0700606 if (event->mRequiresSystemReady && !mSystemReady) {
607 event->mWaitStatus = false;
608 mPendingConfigEvents.add(event);
609 return status;
610 }
Eric Laurent10351942014-05-08 18:49:52 -0700611 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700612 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800613 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700614 mLock.unlock();
615 {
616 Mutex::Autolock _l(event->mLock);
617 while (event->mWaitStatus) {
618 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
619 event->mStatus = TIMED_OUT;
620 event->mWaitStatus = false;
621 }
622 }
623 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800624 }
Eric Laurent10351942014-05-08 18:49:52 -0700625 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800626 return status;
627}
628
Mikhail Naganov88536df2021-07-26 17:30:29 -0700629void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700630 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800631{
632 Mutex::Autolock _l(mLock);
Eric Laurent09f1ed22019-04-24 17:45:17 -0700633 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800634}
635
636// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov88536df2021-07-26 17:30:29 -0700637void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -0700638 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800639{
Andy Hungd0979812019-02-21 15:51:44 -0800640 // The audio statistics history is exponentially weighted to forget events
641 // about five or more seconds in the past. In order to have
642 // crisper statistics for mediametrics, we reset the statistics on
643 // an IoConfigEvent, to reflect different properties for a new device.
644 mIoJitterMs.reset();
645 mLatencyMs.reset();
646 mProcessTimeMs.reset();
Robert Wu06db0a32021-08-10 19:05:34 +0000647 mMonopipePipeDepthStats.reset();
Dean Wheatley12473e92021-03-18 23:00:55 +1100648 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
Andy Hungd0979812019-02-21 15:51:44 -0800649
Eric Laurent09f1ed22019-04-24 17:45:17 -0700650 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700651 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800652}
653
Mikhail Naganov83f04272017-02-07 10:45:09 -0800654void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700655{
656 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800657 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700658}
659
Eric Laurent81784c32012-11-19 14:55:58 -0800660// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800661void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
662 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800663{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800664 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700665 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800666}
667
Eric Laurent10351942014-05-08 18:49:52 -0700668// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
669status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800670{
Andy Hung2ddee192015-12-18 17:34:44 -0800671 sp<ConfigEvent> configEvent;
672 AudioParameter param(keyValuePair);
673 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700674 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800675 setMasterMono_l(value != 0);
676 if (param.size() == 1) {
677 return NO_ERROR; // should be a solo parameter - we don't pass down
678 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700679 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800680 configEvent = new SetParameterConfigEvent(param.toString());
681 } else {
682 configEvent = new SetParameterConfigEvent(keyValuePair);
683 }
Eric Laurent10351942014-05-08 18:49:52 -0700684 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700685}
686
Eric Laurent1c333e22014-05-20 10:48:17 -0700687status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
688 const struct audio_patch *patch,
689 audio_patch_handle_t *handle)
690{
691 Mutex::Autolock _l(mLock);
692 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
693 status_t status = sendConfigEvent_l(configEvent);
694 if (status == NO_ERROR) {
695 CreateAudioPatchConfigEventData *data =
696 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
697 *handle = data->mHandle;
698 }
699 return status;
700}
701
702status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
703 const audio_patch_handle_t handle)
704{
705 Mutex::Autolock _l(mLock);
706 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
707 return sendConfigEvent_l(configEvent);
708}
709
jiabinc52b1ff2019-10-31 17:20:42 -0700710status_t AudioFlinger::ThreadBase::sendUpdateOutDeviceConfigEvent(
711 const DeviceDescriptorBaseVector& outDevices)
712{
713 if (type() != RECORD) {
714 // The update out device operation is only for record thread.
715 return INVALID_OPERATION;
716 }
717 Mutex::Autolock _l(mLock);
718 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
719 return sendConfigEvent_l(configEvent);
720}
721
Eric Laurentec376dc2021-04-08 20:41:22 +0200722void AudioFlinger::ThreadBase::sendResizeBufferConfigEvent_l(int32_t maxSharedAudioHistoryMs)
723{
724 ALOG_ASSERT(type() == RECORD, "sendResizeBufferConfigEvent_l() called on non record thread");
725 sp<ConfigEvent> configEvent =
726 (ConfigEvent *)new ResizeBufferConfigEvent(maxSharedAudioHistoryMs);
727 sendConfigEvent_l(configEvent);
728}
Eric Laurent1c333e22014-05-20 10:48:17 -0700729
Eric Laurentb3f315a2021-07-13 15:09:05 +0200730void AudioFlinger::ThreadBase::sendCheckOutputStageEffectsEvent()
731{
732 Mutex::Autolock _l(mLock);
733 sendCheckOutputStageEffectsEvent_l();
734}
735
736void AudioFlinger::ThreadBase::sendCheckOutputStageEffectsEvent_l()
737{
738 sp<ConfigEvent> configEvent =
739 (ConfigEvent *)new CheckOutputStageEffectsEvent();
740 sendConfigEvent_l(configEvent);
741}
742
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700743// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700744void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700745{
Eric Laurent10351942014-05-08 18:49:52 -0700746 bool configChanged = false;
747
Eric Laurent81784c32012-11-19 14:55:58 -0800748 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700749 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700750 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800751 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700752 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700753 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700754 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
755 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800756 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700757 true /*asynchronous*/);
758 if (err != 0) {
759 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700760 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700761 }
762 } break;
763 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700764 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent09f1ed22019-04-24 17:45:17 -0700765 ioConfigChanged(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700766 } break;
767 case CFG_EVENT_SET_PARAMETER: {
768 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
769 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
770 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700771 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
772 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700773 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700774 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700775 case CFG_EVENT_CREATE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700776 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700777 CreateAudioPatchConfigEventData *data =
778 (CreateAudioPatchConfigEventData *)event->mData.get();
779 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700780 const DeviceTypeSet newDevices = getDeviceTypes();
781 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
782 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
783 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700784 } break;
785 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
jiabinc52b1ff2019-10-31 17:20:42 -0700786 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700787 ReleaseAudioPatchConfigEventData *data =
788 (ReleaseAudioPatchConfigEventData *)event->mData.get();
789 event->mStatus = releaseAudioPatch_l(data->mHandle);
jiabinc52b1ff2019-10-31 17:20:42 -0700790 const DeviceTypeSet newDevices = getDeviceTypes();
791 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
792 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
793 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
794 } break;
795 case CFG_EVENT_UPDATE_OUT_DEVICE: {
796 UpdateOutDevicesConfigEventData *data =
797 (UpdateOutDevicesConfigEventData *)event->mData.get();
798 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700799 } break;
Eric Laurentec376dc2021-04-08 20:41:22 +0200800 case CFG_EVENT_RESIZE_BUFFER: {
801 ResizeBufferConfigEventData *data =
802 (ResizeBufferConfigEventData *)event->mData.get();
803 resizeInputBuffer_l(data->mMaxSharedAudioHistoryMs);
804 } break;
Eric Laurentb3f315a2021-07-13 15:09:05 +0200805
806 case CFG_EVENT_CHECK_OUTPUT_STAGE_EFFECTS: {
807 setCheckOutputStageEffects();
808 } break;
809
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700810 default:
Eric Laurent10351942014-05-08 18:49:52 -0700811 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700812 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800813 }
Eric Laurent10351942014-05-08 18:49:52 -0700814 {
815 Mutex::Autolock _l(event->mLock);
816 if (event->mWaitStatus) {
817 event->mWaitStatus = false;
818 event->mCond.signal();
819 }
820 }
821 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
822 }
823
824 if (configChanged) {
825 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800826 }
Eric Laurent81784c32012-11-19 14:55:58 -0800827}
828
Marco Nelissenb2208842014-02-07 14:00:50 -0800829String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
830 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700831 const audio_channel_representation_t representation =
832 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700833
834 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800835 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700836 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
837 if (output) {
838 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
839 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
840 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700841 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700842 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
843 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
844 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
845 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
846 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
847 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
848 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
849 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
850 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
851 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
852 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
853 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700854 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, ");
855 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, ");
856 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, ");
857 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, ");
858 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_LEFT) s.append("bottom-front-left, ");
859 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_CENTER) s.append("bottom-front-center, ");
860 if (mask & AUDIO_CHANNEL_OUT_BOTTOM_FRONT_RIGHT) s.append("bottom-front-right, ");
Andy Hungfba71252021-05-07 11:58:32 -0700861 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY_2) s.append("low-frequency-2, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700862 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, ");
863 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700864 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
865 } else {
866 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
867 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
868 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
869 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
870 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
871 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
872 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
873 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
874 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
875 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
876 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
877 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700878 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
879 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
880 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
Andy Hungfba71252021-05-07 11:58:32 -0700881 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low-frequency, ");
Andy Hungae81b4c2021-05-07 08:54:28 -0700882 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, ");
883 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, ");
Andy Hungf98ec8d2015-05-19 12:53:24 -0700884 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
885 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
886 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
887 }
888 const int len = s.length();
889 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700890 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700891 s.unlockBuffer(len - 2); // remove trailing ", "
892 }
893 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800894 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700895 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
896 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
897 return s;
898 default:
899 s.appendFormat("unknown mask, representation:%d bits:%#x",
900 representation, audio_channel_mask_get_bits(mask));
901 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800902 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800903}
904
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700905void AudioFlinger::ThreadBase::dump(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800906{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800907 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
908 this, mThreadName, getTid(), type(), threadTypeToString(type()));
909
Eric Laurent81784c32012-11-19 14:55:58 -0800910 bool locked = AudioFlinger::dumpTryLock(mLock);
911 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800912 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800913 }
914
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700915 dumpBase_l(fd, args);
916 dumpInternals_l(fd, args);
917 dumpTracks_l(fd, args);
918 dumpEffectChains_l(fd, args);
919
920 if (locked) {
921 mLock.unlock();
922 }
923
924 dprintf(fd, " Local log:\n");
925 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
926}
927
928void AudioFlinger::ThreadBase::dumpBase_l(int fd, const Vector<String16>& args __unused)
929{
Elliott Hughes87cebad2014-05-22 10:14:43 -0700930 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700931 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700932 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700933 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700934 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700935 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700936 dprintf(fd, " Channel count: %u\n", mChannelCount);
937 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800938 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700939 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700940 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700941 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800942 size_t numConfig = mConfigEvents.size();
943 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700944 const size_t SIZE = 256;
945 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -0800946 for (size_t i = 0; i < numConfig; i++) {
947 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700948 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800949 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700950 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800951 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700952 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800953 }
Andy Hung293558a2017-03-21 12:19:20 -0700954 // Note: output device may be used by capture threads for effects such as AEC.
jiabinc52b1ff2019-10-31 17:20:42 -0700955 dprintf(fd, " Output devices: %s (%s)\n",
956 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
957 dprintf(fd, " Input device: %#x (%s)\n",
958 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -0800959 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -0800960
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700961 // Dump timestamp statistics for the Thread types that support it.
962 if (mType == RECORD
963 || mType == MIXER
964 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -0700965 || mType == DIRECT
966 || mType == OFFLOAD) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700967 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -0700968 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700969 }
970
Andy Hung446f4df2019-02-21 12:26:41 -0800971 if (mLastIoBeginNs > 0) { // MMAP may not set this
972 dprintf(fd, " Last %s occurred (msecs): %lld\n",
973 isOutput() ? "write" : "read",
974 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
975 }
976
977 if (mProcessTimeMs.getN() > 0) {
978 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
979 }
980
981 if (mIoJitterMs.getN() > 0) {
982 dprintf(fd, " Hal %s jitter ms stats: %s\n",
983 isOutput() ? "write" : "read",
984 mIoJitterMs.toString().c_str());
985 }
986
Andy Hunge6c37112019-02-26 17:38:10 -0800987 if (mLatencyMs.getN() > 0) {
988 dprintf(fd, " Threadloop %s latency stats: %s\n",
989 isOutput() ? "write" : "read",
990 mLatencyMs.toString().c_str());
991 }
Robert Wu06db0a32021-08-10 19:05:34 +0000992
993 if (mMonopipePipeDepthStats.getN() > 0) {
994 dprintf(fd, " Monopipe %s pipe depth stats: %s\n",
995 isOutput() ? "write" : "read",
996 mMonopipePipeDepthStats.toString().c_str());
997 }
Eric Laurent81784c32012-11-19 14:55:58 -0800998}
999
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001000void AudioFlinger::ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08001001{
1002 const size_t SIZE = 256;
1003 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -08001004
Marco Nelissenb2208842014-02-07 14:00:50 -08001005 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +00001006 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -08001007 write(fd, buffer, strlen(buffer));
1008
Marco Nelissenb2208842014-02-07 14:00:50 -08001009 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -08001010 sp<EffectChain> chain = mEffectChains[i];
1011 if (chain != 0) {
1012 chain->dump(fd, args);
1013 }
1014 }
1015}
1016
Andy Hungdae27702016-10-31 14:01:16 -07001017void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -08001018{
1019 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07001020 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001021}
1022
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001023String16 AudioFlinger::ThreadBase::getWakeLockTag()
1024{
1025 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -08001026 case MIXER:
1027 return String16("AudioMix");
1028 case DIRECT:
1029 return String16("AudioDirectOut");
1030 case DUPLICATING:
1031 return String16("AudioDup");
1032 case RECORD:
1033 return String16("AudioIn");
1034 case OFFLOAD:
1035 return String16("AudioOffload");
Andy Hungea840382020-05-05 21:50:17 -07001036 case MMAP_PLAYBACK:
1037 return String16("MmapPlayback");
1038 case MMAP_CAPTURE:
1039 return String16("MmapCapture");
Eric Laurentb3f315a2021-07-13 15:09:05 +02001040 case VIRTUALIZER_STAGE:
1041 return String16("AudioVirt");
Glenn Kastenbcb14862015-03-05 17:11:21 -08001042 default:
1043 ALOG_ASSERT(false);
1044 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001045 }
1046}
1047
Andy Hungdae27702016-10-31 14:01:16 -07001048void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -08001049{
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001050 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001051 if (mPowerManager != 0) {
1052 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -07001053 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
Chris Ye6597d732020-02-28 22:38:25 -08001054 binder::Status status = mPowerManager->acquireWakeLockAsync(binder,
1055 POWERMANAGER_PARTIAL_WAKE_LOCK,
Narayan Kamath014e7fa2013-10-14 15:03:38 +01001056 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -07001057 String16("audioserver"),
Chris Ye6597d732020-02-28 22:38:25 -08001058 {} /* workSource */,
1059 {} /* historyTag */);
1060 if (status.isOk()) {
Eric Laurent81784c32012-11-19 14:55:58 -08001061 mWakeLockToken = binder;
1062 }
Chris Ye6597d732020-02-28 22:38:25 -08001063 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status.exceptionCode());
Eric Laurent81784c32012-11-19 14:55:58 -08001064 }
Wei Jia3f273d12015-11-24 09:06:49 -08001065
Andy Hung3f0c9022016-01-15 17:49:46 -08001066 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -08001067 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
1068 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -08001069}
1070
1071void AudioFlinger::ThreadBase::releaseWakeLock()
1072{
1073 Mutex::Autolock _l(mLock);
1074 releaseWakeLock_l();
1075}
1076
1077void AudioFlinger::ThreadBase::releaseWakeLock_l()
1078{
Andy Hung3f0c9022016-01-15 17:49:46 -08001079 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -08001080 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001081 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001082 if (mPowerManager != 0) {
Chris Ye6597d732020-02-28 22:38:25 -08001083 mPowerManager->releaseWakeLockAsync(mWakeLockToken, 0);
Eric Laurent81784c32012-11-19 14:55:58 -08001084 }
1085 mWakeLockToken.clear();
1086 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001087}
1088
1089void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -07001090 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001091 // use checkService() to avoid blocking if power service is not up yet
1092 sp<IBinder> binder =
1093 defaultServiceManager()->checkService(String16("power"));
1094 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -08001095 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001096 } else {
Chris Ye6597d732020-02-28 22:38:25 -08001097 mPowerManager = interface_cast<os::IPowerManager>(binder);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001098 binder->linkToDeath(mDeathRecipient);
1099 }
1100 }
1101}
1102
Andy Hungd01b0f12016-11-07 16:10:30 -08001103void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001104 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001105
1106#if !LOG_NDEBUG
1107 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001108 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001109 s << uid << " ";
1110 }
1111 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1112#endif
1113
Andy Hung438e7572015-12-14 15:51:17 -08001114 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1115 if (mSystemReady) {
1116 ALOGE("no wake lock to update, but system ready!");
1117 } else {
1118 ALOGW("no wake lock to update, system not ready yet");
1119 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001120 return;
1121 }
1122 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001123 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
Chris Ye6597d732020-02-28 22:38:25 -08001124 binder::Status status = mPowerManager->updateWakeLockUidsAsync(
1125 mWakeLockToken, uidsAsInt);
1126 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status.exceptionCode());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001127 }
1128}
1129
Eric Laurent81784c32012-11-19 14:55:58 -08001130void AudioFlinger::ThreadBase::clearPowerManager()
1131{
1132 Mutex::Autolock _l(mLock);
1133 releaseWakeLock_l();
1134 mPowerManager.clear();
1135}
1136
jiabinc52b1ff2019-10-31 17:20:42 -07001137void AudioFlinger::ThreadBase::updateOutDevices(
1138 const DeviceDescriptorBaseVector& outDevices __unused)
1139{
1140 ALOGE("%s should only be called in RecordThread", __func__);
1141}
1142
Eric Laurentec376dc2021-04-08 20:41:22 +02001143void AudioFlinger::ThreadBase::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs __unused)
1144{
1145 ALOGE("%s should only be called in RecordThread", __func__);
1146}
1147
Glenn Kasten0f11b512014-01-31 16:18:54 -08001148void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001149{
1150 sp<ThreadBase> thread = mThread.promote();
1151 if (thread != 0) {
1152 thread->clearPowerManager();
1153 }
1154 ALOGW("power manager service died !!!");
1155}
1156
Eric Laurent81784c32012-11-19 14:55:58 -08001157void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001158 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001159{
1160 sp<EffectChain> chain = getEffectChain_l(sessionId);
1161 if (chain != 0) {
1162 if (type != NULL) {
1163 chain->setEffectSuspended_l(type, suspend);
1164 } else {
1165 chain->setEffectSuspendedAll_l(suspend);
1166 }
1167 }
1168
1169 updateSuspendedSessions_l(type, suspend, sessionId);
1170}
1171
1172void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1173{
1174 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1175 if (index < 0) {
1176 return;
1177 }
1178
1179 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1180 mSuspendedSessions.valueAt(index);
1181
1182 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001183 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001184 for (int j = 0; j < desc->mRefCount; j++) {
1185 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1186 chain->setEffectSuspendedAll_l(true);
1187 } else {
1188 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1189 desc->mType.timeLow);
1190 chain->setEffectSuspended_l(&desc->mType, true);
1191 }
1192 }
1193 }
1194}
1195
1196void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1197 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001198 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001199{
1200 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1201
1202 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1203
1204 if (suspend) {
1205 if (index >= 0) {
1206 sessionEffects = mSuspendedSessions.valueAt(index);
1207 } else {
1208 mSuspendedSessions.add(sessionId, sessionEffects);
1209 }
1210 } else {
1211 if (index < 0) {
1212 return;
1213 }
1214 sessionEffects = mSuspendedSessions.valueAt(index);
1215 }
1216
1217
1218 int key = EffectChain::kKeyForSuspendAll;
1219 if (type != NULL) {
1220 key = type->timeLow;
1221 }
1222 index = sessionEffects.indexOfKey(key);
1223
1224 sp<SuspendedSessionDesc> desc;
1225 if (suspend) {
1226 if (index >= 0) {
1227 desc = sessionEffects.valueAt(index);
1228 } else {
1229 desc = new SuspendedSessionDesc();
1230 if (type != NULL) {
1231 desc->mType = *type;
1232 }
1233 sessionEffects.add(key, desc);
1234 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1235 }
1236 desc->mRefCount++;
1237 } else {
1238 if (index < 0) {
1239 return;
1240 }
1241 desc = sessionEffects.valueAt(index);
1242 if (--desc->mRefCount == 0) {
1243 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1244 sessionEffects.removeItemsAt(index);
1245 if (sessionEffects.isEmpty()) {
1246 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1247 sessionId);
1248 mSuspendedSessions.removeItem(sessionId);
1249 }
1250 }
1251 }
1252 if (!sessionEffects.isEmpty()) {
1253 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1254 }
1255}
1256
Eric Laurent6b446ce2019-12-13 10:56:31 -08001257void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(bool enabled,
1258 audio_session_t sessionId,
1259 bool threadLocked) {
1260 if (!threadLocked) {
1261 mLock.lock();
1262 }
Eric Laurent81784c32012-11-19 14:55:58 -08001263
Eric Laurent81784c32012-11-19 14:55:58 -08001264 if (mType != RECORD) {
1265 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1266 // another session. This gives the priority to well behaved effect control panels
1267 // and applications not using global effects.
1268 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1269 // global effects
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001270 if (!audio_is_global_session(sessionId)) {
Eric Laurent81784c32012-11-19 14:55:58 -08001271 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1272 }
1273 }
1274
Eric Laurent6b446ce2019-12-13 10:56:31 -08001275 if (!threadLocked) {
1276 mLock.unlock();
Eric Laurent81784c32012-11-19 14:55:58 -08001277 }
1278}
1279
Eric Laurent4c415062016-06-17 16:14:16 -07001280// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1281status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1282 const effect_descriptor_t *desc, audio_session_t sessionId)
1283{
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001284 // No global output effect sessions on record threads
1285 if (sessionId == AUDIO_SESSION_OUTPUT_MIX
1286 || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
Eric Laurent4c415062016-06-17 16:14:16 -07001287 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1288 desc->name, mThreadName);
1289 return BAD_VALUE;
1290 }
1291 // only pre processing effects on record thread
1292 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1293 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1294 desc->name, mThreadName);
1295 return BAD_VALUE;
1296 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001297
1298 // always allow effects without processing load or latency
1299 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1300 return NO_ERROR;
1301 }
1302
Eric Laurent4c415062016-06-17 16:14:16 -07001303 audio_input_flags_t flags = mInput->flags;
1304 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1305 if (flags & AUDIO_INPUT_FLAG_RAW) {
1306 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1307 desc->name, mThreadName);
1308 return BAD_VALUE;
1309 }
1310 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1311 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1312 desc->name, mThreadName);
1313 return BAD_VALUE;
1314 }
1315 }
jiabineb3bda02020-06-30 14:07:03 -07001316
1317 if (EffectModule::isHapticGenerator(&desc->type)) {
1318 ALOGE("%s(): HapticGenerator is not supported in RecordThread", __func__);
1319 return BAD_VALUE;
1320 }
Eric Laurent4c415062016-06-17 16:14:16 -07001321 return NO_ERROR;
1322}
1323
1324// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1325status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1326 const effect_descriptor_t *desc, audio_session_t sessionId)
1327{
1328 // no preprocessing on playback threads
1329 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1330 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1331 " thread %s", desc->name, mThreadName);
1332 return BAD_VALUE;
1333 }
1334
Eric Laurent3e4de772017-07-16 16:55:08 -07001335 // always allow effects without processing load or latency
1336 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1337 return NO_ERROR;
1338 }
1339
jiabineb3bda02020-06-30 14:07:03 -07001340 if (EffectModule::isHapticGenerator(&desc->type) && mHapticChannelCount == 0) {
1341 ALOGW("%s: thread doesn't support haptic playback while the effect is HapticGenerator",
1342 __func__);
1343 return BAD_VALUE;
1344 }
1345
Eric Laurent4c415062016-06-17 16:14:16 -07001346 switch (mType) {
1347 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001348#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001349 // Reject any effect on mixer multichannel sinks.
1350 // TODO: fix both format and multichannel issues with effects.
1351 if (mChannelCount != FCC_2) {
1352 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1353 " thread %s", desc->name, mChannelCount, mThreadName);
1354 return BAD_VALUE;
1355 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001356#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001357 audio_output_flags_t flags = mOutput->flags;
1358 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1359 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1360 // global effects are applied only to non fast tracks if they are SW
1361 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1362 break;
1363 }
1364 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1365 // only post processing on output stage session
1366 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1367 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1368 " on output stage session", desc->name);
1369 return BAD_VALUE;
1370 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001371 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1372 // only post processing on output stage session
1373 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1374 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1375 " on device session", desc->name);
1376 return BAD_VALUE;
1377 }
Eric Laurent4c415062016-06-17 16:14:16 -07001378 } else {
1379 // no restriction on effects applied on non fast tracks
1380 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1381 break;
1382 }
1383 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001384
Eric Laurent4c415062016-06-17 16:14:16 -07001385 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1386 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1387 desc->name);
1388 return BAD_VALUE;
1389 }
1390 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1391 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1392 " in fast mode", desc->name);
1393 return BAD_VALUE;
1394 }
1395 }
1396 } break;
1397 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001398 // nothing actionable on offload threads, if the effect:
1399 // - is offloadable: the effect can be created
1400 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1401 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001402 break;
1403 case DIRECT:
1404 // Reject any effect on Direct output threads for now, since the format of
1405 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1406 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1407 desc->name, mThreadName);
1408 return BAD_VALUE;
1409 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001410#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001411 // Reject any effect on mixer multichannel sinks.
1412 // TODO: fix both format and multichannel issues with effects.
1413 if (mChannelCount != FCC_2) {
1414 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1415 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1416 return BAD_VALUE;
1417 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001418#endif
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001419 if (audio_is_global_session(sessionId)) {
Eric Laurent4c415062016-06-17 16:14:16 -07001420 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1421 " thread %s", desc->name, mThreadName);
1422 return BAD_VALUE;
1423 }
1424 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1425 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1426 " DUPLICATING thread %s", desc->name, mThreadName);
1427 return BAD_VALUE;
1428 }
1429 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1430 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1431 " DUPLICATING thread %s", desc->name, mThreadName);
1432 return BAD_VALUE;
1433 }
1434 break;
Eric Laurentb3f315a2021-07-13 15:09:05 +02001435 case VIRTUALIZER_STAGE:
1436 if (!audio_is_global_session(sessionId)) {
1437 ALOGW("checkEffectCompatibility_l(): non global effect %s on VIRTUALIZER_STAGE"
1438 " thread %s", desc->name, mThreadName);
1439 return BAD_VALUE;
1440 }
1441 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001442 default:
1443 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1444 }
1445
1446 return NO_ERROR;
1447}
1448
Eric Laurent81784c32012-11-19 14:55:58 -08001449// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1450sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1451 const sp<AudioFlinger::Client>& client,
1452 const sp<IEffectClient>& effectClient,
1453 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001454 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001455 effect_descriptor_t *desc,
1456 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001457 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001458 bool pinned,
1459 bool probe)
Eric Laurent81784c32012-11-19 14:55:58 -08001460{
1461 sp<EffectModule> effect;
1462 sp<EffectHandle> handle;
1463 status_t lStatus;
1464 sp<EffectChain> chain;
1465 bool chainCreated = false;
1466 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001467 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001468
1469 lStatus = initCheck();
1470 if (lStatus != NO_ERROR) {
1471 ALOGW("createEffect_l() Audio driver not initialized.");
1472 goto Exit;
1473 }
1474
Eric Laurent81784c32012-11-19 14:55:58 -08001475 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1476
1477 { // scope for mLock
1478 Mutex::Autolock _l(mLock);
1479
Eric Laurent4c415062016-06-17 16:14:16 -07001480 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001481 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001482 goto Exit;
1483 }
1484
Eric Laurent81784c32012-11-19 14:55:58 -08001485 // check for existing effect chain with the requested audio session
1486 chain = getEffectChain_l(sessionId);
1487 if (chain == 0) {
1488 // create a new chain for this session
1489 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1490 chain = new EffectChain(this, sessionId);
1491 addEffectChain_l(chain);
1492 chain->setStrategy(getStrategyForSession_l(sessionId));
1493 chainCreated = true;
1494 } else {
1495 effect = chain->getEffectFromDesc_l(desc);
1496 }
1497
1498 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1499
1500 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001501 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001502 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001503 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001504 if (lStatus != NO_ERROR) {
1505 goto Exit;
1506 }
1507 effectCreated = true;
1508
jiabinc52b1ff2019-10-31 17:20:42 -07001509 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001510 effect->setDevices(outDeviceTypeAddrs());
1511 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001512 effect->setMode(mAudioFlinger->getMode());
1513 effect->setAudioSource(mAudioSource);
1514 }
jiabin1319f5a2021-03-30 22:21:24 +00001515 if (effect->isHapticGenerator()) {
1516 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1517 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001518 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
1519 std::move(mAudioFlinger->getDefaultVibratorInfo_l());
1520 if (defaultVibratorInfo) {
jiabin1319f5a2021-03-30 22:21:24 +00001521 // Only set the vibrator info when it is a valid one.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001522 effect->setVibratorInfo(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001523 }
1524 }
Eric Laurent81784c32012-11-19 14:55:58 -08001525 // create effect handle and connect it to effect module
1526 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001527 lStatus = handle->initCheck();
1528 if (lStatus == OK) {
1529 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001530 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001531 }
Eric Laurent81784c32012-11-19 14:55:58 -08001532 if (enabled != NULL) {
1533 *enabled = (int)effect->isEnabled();
1534 }
1535 }
1536
1537Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001538 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent81784c32012-11-19 14:55:58 -08001539 Mutex::Autolock _l(mLock);
1540 if (effectCreated) {
1541 chain->removeEffect_l(effect);
1542 }
Eric Laurent81784c32012-11-19 14:55:58 -08001543 if (chainCreated) {
1544 removeEffectChain_l(chain);
1545 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001546 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001547 }
1548
Glenn Kasten9156ef32013-08-06 15:39:08 -07001549 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001550 return handle;
1551}
1552
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001553void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1554 bool unpinIfLast)
1555{
1556 bool remove = false;
1557 sp<EffectModule> effect;
1558 {
1559 Mutex::Autolock _l(mLock);
Eric Laurent41709552019-12-16 19:34:05 -08001560 sp<EffectBase> effectBase = handle->effect().promote();
1561 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001562 return;
1563 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001564 effect = effectBase->asEffectModule();
1565 if (effect == nullptr) {
1566 return;
1567 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001568 // restore suspended effects if the disconnected handle was enabled and the last one.
1569 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1570 if (remove) {
1571 removeEffect_l(effect, true);
1572 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001573 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001574 }
1575 if (remove) {
1576 mAudioFlinger->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001577 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001578 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001579 }
1580 }
1581}
1582
Eric Laurent6b446ce2019-12-13 10:56:31 -08001583void AudioFlinger::ThreadBase::onEffectEnable(const sp<EffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001584 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001585 Mutex::Autolock _l(mLock);
1586 broadcast_l();
1587 }
1588 if (!effect->isOffloadable()) {
1589 if (mType == ThreadBase::OFFLOAD) {
1590 PlaybackThread *t = (PlaybackThread *)this;
1591 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1592 }
1593 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
1594 mAudioFlinger->onNonOffloadableGlobalEffectEnable();
1595 }
1596 }
1597}
1598
1599void AudioFlinger::ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001600 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001601 Mutex::Autolock _l(mLock);
1602 broadcast_l();
1603 }
1604}
1605
Glenn Kastend848eb42016-03-08 13:42:11 -08001606sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1607 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001608{
1609 Mutex::Autolock _l(mLock);
1610 return getEffect_l(sessionId, effectId);
1611}
1612
Glenn Kastend848eb42016-03-08 13:42:11 -08001613sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1614 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001615{
1616 sp<EffectChain> chain = getEffectChain_l(sessionId);
1617 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1618}
1619
Eric Laurent6c796322019-04-09 14:13:17 -07001620std::vector<int> AudioFlinger::ThreadBase::getEffectIds_l(audio_session_t sessionId)
1621{
1622 sp<EffectChain> chain = getEffectChain_l(sessionId);
1623 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1624}
1625
Eric Laurent81784c32012-11-19 14:55:58 -08001626// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1627// PlaybackThread::mLock held
1628status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1629{
1630 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001631 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001632 sp<EffectChain> chain = getEffectChain_l(sessionId);
1633 bool chainCreated = false;
1634
Eric Laurent5baf2af2013-09-12 17:37:00 -07001635 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001636 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001637 this, effect->desc().name, effect->desc().flags);
1638
Eric Laurent81784c32012-11-19 14:55:58 -08001639 if (chain == 0) {
1640 // create a new chain for this session
1641 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1642 chain = new EffectChain(this, sessionId);
1643 addEffectChain_l(chain);
1644 chain->setStrategy(getStrategyForSession_l(sessionId));
1645 chainCreated = true;
1646 }
1647 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1648
1649 if (chain->getEffectFromId_l(effect->id()) != 0) {
1650 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1651 this, effect->desc().name, chain.get());
1652 return BAD_VALUE;
1653 }
1654
Eric Laurent5baf2af2013-09-12 17:37:00 -07001655 effect->setOffloaded(mType == OFFLOAD, mId);
1656
Eric Laurent81784c32012-11-19 14:55:58 -08001657 status_t status = chain->addEffect_l(effect);
1658 if (status != NO_ERROR) {
1659 if (chainCreated) {
1660 removeEffectChain_l(chain);
1661 }
1662 return status;
1663 }
1664
jiabin8f278ee2019-11-11 12:16:27 -08001665 effect->setDevices(outDeviceTypeAddrs());
1666 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001667 effect->setMode(mAudioFlinger->getMode());
1668 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001669
Eric Laurent81784c32012-11-19 14:55:58 -08001670 return NO_ERROR;
1671}
1672
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001673void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001674
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001675 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001676 effect_descriptor_t desc = effect->desc();
1677 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1678 detachAuxEffect_l(effect->id());
1679 }
1680
Andy Hungfda44002021-06-03 17:23:16 -07001681 sp<EffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001682 if (chain != 0) {
1683 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001684 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001685 removeEffectChain_l(chain);
1686 }
1687 } else {
1688 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1689 }
1690}
1691
1692void AudioFlinger::ThreadBase::lockEffectChains_l(
1693 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1694{
1695 effectChains = mEffectChains;
1696 for (size_t i = 0; i < mEffectChains.size(); i++) {
1697 mEffectChains[i]->lock();
1698 }
1699}
1700
1701void AudioFlinger::ThreadBase::unlockEffectChains(
1702 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1703{
1704 for (size_t i = 0; i < effectChains.size(); i++) {
1705 effectChains[i]->unlock();
1706 }
1707}
1708
Glenn Kastend848eb42016-03-08 13:42:11 -08001709sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001710{
1711 Mutex::Autolock _l(mLock);
1712 return getEffectChain_l(sessionId);
1713}
1714
Glenn Kastend848eb42016-03-08 13:42:11 -08001715sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1716 const
Eric Laurent81784c32012-11-19 14:55:58 -08001717{
1718 size_t size = mEffectChains.size();
1719 for (size_t i = 0; i < size; i++) {
1720 if (mEffectChains[i]->sessionId() == sessionId) {
1721 return mEffectChains[i];
1722 }
1723 }
1724 return 0;
1725}
1726
1727void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1728{
1729 Mutex::Autolock _l(mLock);
1730 size_t size = mEffectChains.size();
1731 for (size_t i = 0; i < size; i++) {
1732 mEffectChains[i]->setMode_l(mode);
1733 }
1734}
1735
Mikhail Naganovdc769682018-05-04 15:34:08 -07001736void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001737{
1738 config->type = AUDIO_PORT_TYPE_MIX;
1739 config->ext.mix.handle = mId;
1740 config->sample_rate = mSampleRate;
1741 config->format = mFormat;
1742 config->channel_mask = mChannelMask;
1743 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1744 AUDIO_PORT_CONFIG_FORMAT;
1745}
1746
Eric Laurent72e3f392015-05-20 14:43:50 -07001747void AudioFlinger::ThreadBase::systemReady()
1748{
1749 Mutex::Autolock _l(mLock);
1750 if (mSystemReady) {
1751 return;
1752 }
1753 mSystemReady = true;
1754
1755 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1756 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1757 }
1758 mPendingConfigEvents.clear();
1759}
1760
Andy Hungdae27702016-10-31 14:01:16 -07001761template <typename T>
1762ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1763 ssize_t index = mActiveTracks.indexOf(track);
1764 if (index >= 0) {
1765 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1766 return index;
1767 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001768 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001769 mActiveTracksGeneration++;
1770 mLatestActiveTrack = track;
1771 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001772 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001773 return mActiveTracks.add(track);
1774}
1775
1776template <typename T>
1777ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1778 ssize_t index = mActiveTracks.remove(track);
1779 if (index < 0) {
1780 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1781 return index;
1782 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001783 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001784 mActiveTracksGeneration++;
1785 --mBatteryCounter[track->uid()].second;
1786 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001787 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001788#ifdef TEE_SINK
1789 track->dumpTee(-1 /* fd */, "_REMOVE");
1790#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001791 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001792 return index;
1793}
1794
1795template <typename T>
1796void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1797 for (const sp<T> &track : mActiveTracks) {
1798 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001799 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001800 }
1801 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001802 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001803 mActiveTracks.clear();
1804 mLatestActiveTrack.clear();
1805 mBatteryCounter.clear();
1806}
1807
1808template <typename T>
1809void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1810 sp<ThreadBase> thread, bool force) {
1811 // Updates ActiveTracks client uids to the thread wakelock.
1812 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1813 thread->updateWakeLockUids_l(getWakeLockUids());
1814 mLastActiveTracksGeneration = mActiveTracksGeneration;
1815 }
1816
1817 // Updates BatteryNotifier uids
1818 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1819 const uid_t uid = it->first;
1820 ssize_t &previous = it->second.first;
1821 ssize_t &current = it->second.second;
1822 if (current > 0) {
1823 if (previous == 0) {
1824 BatteryNotifier::getInstance().noteStartAudio(uid);
1825 }
1826 previous = current;
1827 ++it;
1828 } else if (current == 0) {
1829 if (previous > 0) {
1830 BatteryNotifier::getInstance().noteStopAudio(uid);
1831 }
1832 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1833 } else /* (current < 0) */ {
1834 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1835 }
1836 }
1837}
Eric Laurent83b88082014-06-20 18:31:16 -07001838
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001839template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001840bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001841 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001842 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001843
1844 for (const sp<T> &track : mActiveTracks) {
1845 // Do not short-circuit as all hasChanged states must be reset
1846 // as all the metadata are going to be sent
1847 hasChanged |= track->readAndClearHasChanged();
1848 }
Kevin Rocard069c2712018-03-29 19:09:14 -07001849 return hasChanged;
1850}
1851
1852template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001853void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1854 const char *funcName, const sp<T> &track) const {
1855 if (mLocalLog != nullptr) {
1856 String8 result;
1857 track->appendDump(result, false /* active */);
1858 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1859 }
1860}
1861
Eric Laurent6acd1d42017-01-04 14:23:29 -08001862void AudioFlinger::ThreadBase::broadcast_l()
1863{
1864 // Thread could be blocked waiting for async
1865 // so signal it to handle state changes immediately
1866 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1867 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1868 mSignalPending = true;
1869 mWaitWorkCV.broadcast();
1870}
1871
Andy Hungd0979812019-02-21 15:51:44 -08001872// Call only from threadLoop() or when it is idle.
1873// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
1874void AudioFlinger::ThreadBase::sendStatistics(bool force)
1875{
1876 // Do not log if we have no stats.
1877 // We choose the timestamp verifier because it is the most likely item to be present.
1878 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1879 if (nstats == 0) {
1880 return;
1881 }
1882
1883 // Don't log more frequently than once per 12 hours.
1884 // We use BOOTTIME to include suspend time.
1885 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1886 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1887 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1888 return;
1889 }
1890
1891 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1892 mLastRecordedTimeNs = timeNs;
1893
Ray Essickf27e9872019-12-07 06:28:46 -08001894 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08001895
1896#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1897
1898 // thread configuration
1899 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1900 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1901 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1902 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1903 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1904 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1905 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07001906 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
1907 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08001908
1909 // thread statistics
1910 if (mIoJitterMs.getN() > 0) {
1911 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1912 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1913 }
1914 if (mProcessTimeMs.getN() > 0) {
1915 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
1916 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
1917 }
1918 const auto tsjitter = mTimestampVerifier.getJitterMs();
1919 if (tsjitter.getN() > 0) {
1920 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
1921 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
1922 }
1923 if (mLatencyMs.getN() > 0) {
1924 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
1925 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
1926 }
Robert Wu06db0a32021-08-10 19:05:34 +00001927 if (mMonopipePipeDepthStats.getN() > 0) {
1928 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
1929 mMonopipePipeDepthStats.getMean());
1930 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
1931 mMonopipePipeDepthStats.getStdDev());
1932 }
Andy Hungd0979812019-02-21 15:51:44 -08001933
1934 item->selfrecord();
1935}
1936
Eric Laurentd66d7a12021-07-13 13:35:32 +02001937product_strategy_t AudioFlinger::ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
1938{
1939 if (!mAudioFlinger->isAudioPolicyReady()) {
1940 return PRODUCT_STRATEGY_NONE;
1941 }
1942 return AudioSystem::getStrategyForStream(stream);
1943}
1944
Eric Laurent81784c32012-11-19 14:55:58 -08001945// ----------------------------------------------------------------------------
1946// Playback
1947// ----------------------------------------------------------------------------
1948
1949AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1950 AudioStreamOut* output,
1951 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07001952 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02001953 bool systemReady,
1954 audio_config_base_t *mixerConfig)
Andy Hungcf10d742020-04-28 15:38:24 -07001955 : ThreadBase(audioFlinger, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08001956 mNormalFrameCount(0), mSinkBuffer(NULL),
Eric Laurentb3f315a2021-07-13 15:09:05 +02001957 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == VIRTUALIZER_STAGE),
Andy Hung69aed5f2014-02-25 17:24:40 -08001958 mMixerBuffer(NULL),
1959 mMixerBufferSize(0),
1960 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1961 mMixerBufferValid(false),
Eric Laurentb3f315a2021-07-13 15:09:05 +02001962 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == VIRTUALIZER_STAGE),
Andy Hung98ef9782014-03-04 14:46:50 -08001963 mEffectBuffer(NULL),
1964 mEffectBufferSize(0),
1965 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1966 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001967 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001968 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001969 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001970 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001971 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001972 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001973 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08001974 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001975 mMixerStatus(MIXER_IDLE),
1976 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001977 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001978 mBytesRemaining(0),
1979 mCurrentWriteLength(0),
1980 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001981 mWriteAckSequence(0),
1982 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001983 mScreenState(AudioFlinger::mScreenState),
1984 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001985 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001986 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01001987 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
1988 mDownStreamPatch{}
Eric Laurent81784c32012-11-19 14:55:58 -08001989{
Glenn Kastend7dca052015-03-05 16:05:54 -08001990 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1991 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001992
1993 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1994 // it would be safer to explicitly pass initial masterVolume/masterMute as
1995 // parameter.
1996 //
1997 // If the HAL we are using has support for master volume or master mute,
1998 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1999 // and the mute set to false).
2000 mMasterVolume = audioFlinger->masterVolume_l();
2001 mMasterMute = audioFlinger->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002002 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002003 if (mOutput->audioHwDev->canSetMasterVolume()) {
2004 mMasterVolume = 1.0;
2005 }
2006
2007 if (mOutput->audioHwDev->canSetMasterMute()) {
2008 mMasterMute = false;
2009 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002010 mIsMsdDevice = strcmp(
2011 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002012 }
2013
Eric Laurentf1f22e72021-07-13 14:04:14 +02002014 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2015 mMixerChannelMask = mixerConfig->channel_mask;
2016 }
2017
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002018 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002019
Eric Laurentb3f315a2021-07-13 15:09:05 +02002020 if (mType != VIRTUALIZER_STAGE
2021 && mMixerChannelMask != mChannelMask) {
2022 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2023 mChannelMask, mMixerChannelMask);
2024 }
2025
Andy Hungc8fddf32018-08-08 18:32:37 -07002026 // TODO: We may also match on address as well as device type for
2027 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002028 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002029 // TODO: This property should be ensure that only contains one single device type.
2030 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2031 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002032 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2033 : AUDIO_DEVICE_NONE));
2034 }
2035
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002036 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2037 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002038 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08002039 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
2040 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002041 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002042 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2043 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002044 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2045 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002046}
2047
2048AudioFlinger::PlaybackThread::~PlaybackThread()
2049{
Glenn Kasten9e58b552013-01-18 15:09:48 -08002050 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002051 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002052 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002053 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002054}
2055
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002056// Thread virtuals
2057
2058void AudioFlinger::PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002059{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002060 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002061 ALOGE("The stream is not open yet"); // This should not happen.
2062 } else {
2063 // setEventCallback will need a strong pointer as a parameter. Calling it
2064 // here instead of constructor of PlaybackThread so that the onFirstRef
2065 // callback would not be made on an incompletely constructed object.
2066 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002067 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002068 }
2069 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002070 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08002071}
2072
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002073// ThreadBase virtuals
2074void AudioFlinger::PlaybackThread::preExit()
2075{
2076 ALOGV(" preExit()");
2077 // FIXME this is using hard-coded strings but in the future, this functionality will be
2078 // converted to use audio HAL extensions required to support tunneling
2079 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
2080 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
2081}
2082
2083void AudioFlinger::PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002084{
Eric Laurent81784c32012-11-19 14:55:58 -08002085 String8 result;
2086
Marco Nelissenb2208842014-02-07 14:00:50 -08002087 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002088 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2089 const stream_type_t *st = &mStreamTypes[i];
2090 if (i > 0) {
2091 result.appendFormat(", ");
2092 }
2093 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2094 if (st->mute) {
2095 result.append("M");
2096 }
2097 }
2098 result.append("\n");
2099 write(fd, result.string(), result.length());
2100 result.clear();
2101
Eric Laurent81784c32012-11-19 14:55:58 -08002102 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2103 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002104 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002105 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002106
2107 size_t numtracks = mTracks.size();
2108 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002109 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002110 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002111 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002112 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002113 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002114 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002115 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002116 for (size_t i = 0; i < numtracks; ++i) {
2117 sp<Track> track = mTracks[i];
2118 if (track != 0) {
2119 bool active = mActiveTracks.indexOf(track) >= 0;
2120 if (active) {
2121 numactiveseen++;
2122 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002123 result.append(prefix);
2124 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002125 }
2126 }
2127 } else {
2128 result.append("\n");
2129 }
2130 if (numactiveseen != numactive) {
2131 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002132 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002133 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002134 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002135 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002136 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07002137 sp<Track> track = mActiveTracks[i];
2138 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002139 result.append(prefix);
2140 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002141 }
2142 }
2143 }
2144
2145 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002146}
2147
Andy Hung61589a42021-06-16 09:37:53 -07002148void AudioFlinger::PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002149{
Andy Hung04cb8f72020-03-20 13:44:33 -07002150 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002151 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002152 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2153 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002154 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2155 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2156 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2157 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002158 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002159 dprintf(fd, " Total writes: %d\n", mNumWrites);
2160 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2161 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2162 dprintf(fd, " Suspend count: %d\n", mSuspended);
2163 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2164 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2165 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2166 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002167 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002168 AudioStreamOut *output = mOutput;
2169 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002170 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002171 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002172 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2173 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2174 if (mPipeSink.get() != nullptr) {
2175 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2176 }
2177 if (output != nullptr) {
2178 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002179 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002180 }
Eric Laurent81784c32012-11-19 14:55:58 -08002181}
2182
Eric Laurent81784c32012-11-19 14:55:58 -08002183// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
2184sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
2185 const sp<AudioFlinger::Client>& client,
2186 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002187 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002188 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002189 audio_format_t format,
2190 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002191 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002192 size_t *pNotificationFrameCount,
2193 uint32_t notificationsPerBuffer,
2194 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002195 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002196 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002197 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002198 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002199 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002200 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002201 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002202 audio_port_handle_t portId,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002203 const sp<media::IAudioTrackCallback>& callback)
Eric Laurent81784c32012-11-19 14:55:58 -08002204{
Glenn Kasten74935e42013-12-19 08:56:45 -08002205 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002206 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002207 sp<Track> track;
2208 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002209 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002210 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002211 uint32_t sampleRate;
2212
2213 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2214 lStatus = BAD_VALUE;
2215 goto Exit;
2216 }
Eric Laurent21da6472017-11-09 16:29:26 -08002217
2218 if (*pSampleRate == 0) {
2219 *pSampleRate = mSampleRate;
2220 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002221 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002222
2223 // special case for FAST flag considered OK if fast mixer is present
2224 if (hasFastMixer()) {
2225 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2226 }
2227
2228 // Check if requested flags are compatible with output stream flags
2229 if ((*flags & outputFlags) != *flags) {
2230 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2231 *flags, outputFlags);
2232 *flags = (audio_output_flags_t)(*flags & outputFlags);
2233 }
Eric Laurent81784c32012-11-19 14:55:58 -08002234
Eric Laurent81784c32012-11-19 14:55:58 -08002235 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002236 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002237 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002238 // PCM data
2239 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002240 // TODO: extract as a data library function that checks that a computationally
2241 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002242 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002243 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2244 (channelMask == AUDIO_CHANNEL_OUT_MONO
2245 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002246 // hardware sample rate
2247 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002248 // normal mixer has an associated fast mixer
2249 hasFastMixer() &&
2250 // there are sufficient fast track slots available
2251 (mFastTrackAvailMask != 0)
2252 // FIXME test that MixerThread for this fast track has a capable output HAL
2253 // FIXME add a permission test also?
2254 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002255 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2256 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002257 // read the fast track multiplier property the first time it is needed
2258 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2259 if (ok != 0) {
2260 ALOGE("%s pthread_once failed: %d", __func__, ok);
2261 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002262 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002263 }
Eric Laurent4c415062016-06-17 16:14:16 -07002264
2265 // check compatibility with audio effects.
2266 { // scope for mLock
2267 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002268 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002269 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002270 AUDIO_SESSION_OUTPUT_STAGE,
2271 AUDIO_SESSION_OUTPUT_MIX,
2272 sessionId,
2273 }) {
2274 sp<EffectChain> chain = getEffectChain_l(session);
2275 if (chain.get() != nullptr) {
2276 audio_output_flags_t old = *flags;
2277 chain->checkOutputFlagCompatibility(flags);
2278 if (old != *flags) {
2279 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2280 (int)session, (int)old, (int)*flags);
2281 }
Eric Laurent4c415062016-06-17 16:14:16 -07002282 }
2283 }
2284 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002285 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002286 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2287 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002288 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002289 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
2290 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002291 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002292 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002293 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002294 audio_is_linear_pcm(format), channelMask, sampleRate,
2295 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002296 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002297 }
2298 }
Eric Laurent21da6472017-11-09 16:29:26 -08002299
2300 if (!audio_has_proportional_frames(format)) {
2301 if (sharedBuffer != 0) {
2302 // Same comment as below about ignoring frameCount parameter for set()
2303 frameCount = sharedBuffer->size();
2304 } else if (frameCount == 0) {
2305 frameCount = mNormalFrameCount;
2306 }
2307 if (notificationFrameCount != frameCount) {
2308 notificationFrameCount = frameCount;
2309 }
2310 } else if (sharedBuffer != 0) {
2311 // FIXME: Ensure client side memory buffers need
2312 // not have additional alignment beyond sample
2313 // (e.g. 16 bit stereo accessed as 32 bit frame).
2314 size_t alignment = audio_bytes_per_sample(format);
2315 if (alignment & 1) {
2316 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2317 alignment = 1;
2318 }
2319 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2320 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2321 if (channelCount > 1) {
2322 // More than 2 channels does not require stronger alignment than stereo
2323 alignment <<= 1;
2324 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002325 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002326 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002327 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002328 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002329 goto Exit;
2330 }
Eric Laurent21da6472017-11-09 16:29:26 -08002331
2332 // When initializing a shared buffer AudioTrack via constructors,
2333 // there's no frameCount parameter.
2334 // But when initializing a shared buffer AudioTrack via set(),
2335 // there _is_ a frameCount parameter. We silently ignore it.
2336 frameCount = sharedBuffer->size() / frameSize;
2337 } else {
2338 size_t minFrameCount = 0;
2339 // For fast tracks we try to respect the application's request for notifications per buffer.
2340 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2341 if (notificationsPerBuffer > 0) {
2342 // Avoid possible arithmetic overflow during multiplication.
2343 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2344 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2345 notificationsPerBuffer, mFrameCount);
2346 } else {
2347 minFrameCount = mFrameCount * notificationsPerBuffer;
2348 }
2349 }
2350 } else {
2351 // For normal PCM streaming tracks, update minimum frame count.
2352 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2353 // cover audio hardware latency.
2354 // This is probably too conservative, but legacy application code may depend on it.
2355 // If you change this calculation, also review the start threshold which is related.
2356 uint32_t latencyMs = latency_l();
2357 if (latencyMs == 0) {
2358 ALOGE("Error when retrieving output stream latency");
2359 lStatus = UNKNOWN_ERROR;
2360 goto Exit;
2361 }
2362
2363 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2364 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2365
Eric Laurent81784c32012-11-19 14:55:58 -08002366 }
Eric Laurent21da6472017-11-09 16:29:26 -08002367 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002368 frameCount = minFrameCount;
2369 }
Eric Laurent81784c32012-11-19 14:55:58 -08002370 }
Eric Laurent21da6472017-11-09 16:29:26 -08002371
2372 // Make sure that application is notified with sufficient margin before underrun.
2373 // The client can divide the AudioTrack buffer into sub-buffers,
2374 // and expresses its desire to server as the notification frame count.
2375 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2376 size_t maxNotificationFrames;
2377 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2378 // notify every HAL buffer, regardless of the size of the track buffer
2379 maxNotificationFrames = mFrameCount;
2380 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002381 // Triple buffer the notification period for a triple buffered mixer period;
2382 // otherwise, double buffering for the notification period is fine.
2383 //
2384 // TODO: This should be moved to AudioTrack to modify the notification period
2385 // on AudioTrack::setBufferSizeInFrames() changes.
2386 const int nBuffering =
2387 (uint64_t{frameCount} * mSampleRate)
2388 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2389
Eric Laurent21da6472017-11-09 16:29:26 -08002390 maxNotificationFrames = frameCount / nBuffering;
2391 // If client requested a fast track but this was denied, then use the smaller maximum.
2392 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2393 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2394 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2395 maxNotificationFrames = maxNotificationFramesFastDenied;
2396 }
2397 }
2398 }
2399 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2400 if (notificationFrameCount == 0) {
2401 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2402 maxNotificationFrames, frameCount);
2403 } else {
2404 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2405 notificationFrameCount, maxNotificationFrames, frameCount);
2406 }
2407 notificationFrameCount = maxNotificationFrames;
2408 }
2409 }
2410
Glenn Kasten74935e42013-12-19 08:56:45 -08002411 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002412 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002413
Glenn Kastenc3df8382014-03-13 15:05:25 -07002414 switch (mType) {
2415
2416 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002417 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002418 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002419 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2420 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002421 sampleRate, format, channelMask, mOutput, mFormat);
2422 lStatus = BAD_VALUE;
2423 goto Exit;
2424 }
2425 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002426 break;
2427
2428 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002429 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002430 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2431 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002432 sampleRate, format, channelMask, mOutput, mFormat);
2433 lStatus = BAD_VALUE;
2434 goto Exit;
2435 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002436 break;
2437
2438 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002439 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002440 ALOGE("createTrack_l() Bad parameter: format %#x \""
2441 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002442 format, mOutput, mFormat);
2443 lStatus = BAD_VALUE;
2444 goto Exit;
2445 }
Andy Hungcd044842014-08-07 11:04:34 -07002446 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002447 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2448 lStatus = BAD_VALUE;
2449 goto Exit;
2450 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002451 break;
2452
Eric Laurent81784c32012-11-19 14:55:58 -08002453 }
2454
2455 lStatus = initCheck();
2456 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002457 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002458 goto Exit;
2459 }
2460
2461 { // scope for mLock
2462 Mutex::Autolock _l(mLock);
2463
2464 // all tracks in same audio session must share the same routing strategy otherwise
2465 // conflicts will happen when tracks are moved from one output to another by audio policy
2466 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002467 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002468 for (size_t i = 0; i < mTracks.size(); ++i) {
2469 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002470 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002471 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002472 if (sessionId == t->sessionId() && strategy != actual) {
2473 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2474 strategy, actual);
2475 lStatus = BAD_VALUE;
2476 goto Exit;
2477 }
2478 }
2479 }
2480
yucliuc9c49cd2020-07-13 16:25:21 -07002481 // Set DIRECT flag if current thread is DirectOutputThread. This can
2482 // happen when the playback is rerouted to direct output thread by
2483 // dynamic audio policy.
2484 // Do NOT report the flag changes back to client, since the client
2485 // doesn't explicitly request a direct flag.
2486 audio_output_flags_t trackFlags = *flags;
2487 if (mType == DIRECT) {
2488 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2489 }
2490
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002491 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002492 channelMask, frameCount,
2493 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002494 sessionId, creatorPid, attributionSource, trackFlags,
2495 TrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/, speed);
Glenn Kasten03003332013-08-06 15:40:54 -07002496
Glenn Kasten03003332013-08-06 15:40:54 -07002497 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2498 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002499 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002500 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002501 goto Exit;
2502 }
2503 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002504 {
2505 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2506 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002507 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002508 }
2509 }
Eric Laurent81784c32012-11-19 14:55:58 -08002510
2511 sp<EffectChain> chain = getEffectChain_l(sessionId);
2512 if (chain != 0) {
2513 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2514 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002515 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002516 chain->incTrackCnt();
2517 }
2518
Eric Laurent05067782016-06-01 18:27:28 -07002519 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002520 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2521 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2522 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002523 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002524 }
2525 }
2526
2527 lStatus = NO_ERROR;
2528
2529Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002530 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002531 return track;
2532}
2533
Andy Hung1bc088a2018-02-09 15:57:31 -08002534template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002535ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2536{
Andy Hungc0691382018-09-12 18:01:57 -07002537 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002538 const ssize_t index = mTracks.remove(track);
2539 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002540 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002541 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002542 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002543 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002544 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002545 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002546 }
2547 return index;
2548}
2549
Eric Laurent81784c32012-11-19 14:55:58 -08002550uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2551{
2552 return latency;
2553}
2554
2555uint32_t AudioFlinger::PlaybackThread::latency() const
2556{
2557 Mutex::Autolock _l(mLock);
2558 return latency_l();
2559}
2560uint32_t AudioFlinger::PlaybackThread::latency_l() const
2561{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002562 uint32_t latency;
2563 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2564 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002565 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002566 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002567}
2568
2569void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2570{
2571 Mutex::Autolock _l(mLock);
2572 // Don't apply master volume in SW if our HAL can do it for us.
2573 if (mOutput && mOutput->audioHwDev &&
2574 mOutput->audioHwDev->canSetMasterVolume()) {
2575 mMasterVolume = 1.0;
2576 } else {
2577 mMasterVolume = value;
2578 }
2579}
2580
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002581void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2582{
2583 mMasterBalance.store(balance);
2584}
2585
Eric Laurent81784c32012-11-19 14:55:58 -08002586void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2587{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002588 if (isDuplicating()) {
2589 return;
2590 }
Eric Laurent81784c32012-11-19 14:55:58 -08002591 Mutex::Autolock _l(mLock);
2592 // Don't apply master mute in SW if our HAL can do it for us.
2593 if (mOutput && mOutput->audioHwDev &&
2594 mOutput->audioHwDev->canSetMasterMute()) {
2595 mMasterMute = false;
2596 } else {
2597 mMasterMute = muted;
2598 }
2599}
2600
2601void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2602{
2603 Mutex::Autolock _l(mLock);
2604 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002605 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002606}
2607
2608void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2609{
2610 Mutex::Autolock _l(mLock);
2611 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002612 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002613}
2614
2615float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2616{
2617 Mutex::Autolock _l(mLock);
2618 return mStreamTypes[stream].volume;
2619}
2620
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002621void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2622{
2623 mOutput->stream->setVolume(left, right);
2624}
2625
Eric Laurent81784c32012-11-19 14:55:58 -08002626// addTrack_l() must be called with ThreadBase::mLock held
2627status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2628{
2629 status_t status = ALREADY_EXISTS;
2630
Eric Laurent81784c32012-11-19 14:55:58 -08002631 if (mActiveTracks.indexOf(track) < 0) {
2632 // the track is newly added, make sure it fills up all its
2633 // buffers before playing. This is to ensure the client will
2634 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002635 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002636 TrackBase::track_state state = track->mState;
2637 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002638 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002639 mLock.lock();
2640 // abort track was stopped/paused while we released the lock
2641 if (state != track->mState) {
2642 if (status == NO_ERROR) {
2643 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002644 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002645 mLock.lock();
2646 }
2647 return INVALID_OPERATION;
2648 }
2649 // abort if start is rejected by audio policy manager
2650 if (status != NO_ERROR) {
2651 return PERMISSION_DENIED;
2652 }
2653#ifdef ADD_BATTERY_DATA
2654 // to track the speaker usage
2655 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2656#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002657 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002658 }
2659
Eric Laurent51716182016-02-29 18:00:56 -08002660 // set retry count for buffer fill
2661 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002662 if (track->isStopping_1()) {
2663 track->mRetryCount = kMaxTrackStopRetriesOffload;
2664 } else {
2665 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2666 }
2667 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002668 } else {
2669 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002670 track->mFillingUpStatus =
2671 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002672 }
2673
jiabineb3bda02020-06-30 14:07:03 -07002674 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2675 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2676 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2677 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002678 // Unlock due to VibratorService will lock for this call and will
2679 // call Tracks.mute/unmute which also require thread's lock.
2680 mLock.unlock();
2681 const int intensity = AudioFlinger::onExternalVibrationStart(
2682 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002683 std::optional<media::AudioVibratorInfo> vibratorInfo;
2684 {
2685 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2686 // used to play this track.
2687 Mutex::Autolock _l(mAudioFlinger->mLock);
2688 vibratorInfo = std::move(mAudioFlinger->getDefaultVibratorInfo_l());
2689 }
jiabin57303cc2018-12-18 15:45:57 -08002690 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07002691 track->setHapticIntensity(static_cast<os::HapticScale>(intensity));
Lais Andradebc3f37a2021-07-02 00:13:19 +01002692 if (vibratorInfo) {
2693 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2694 }
2695
jiabin57303cc2018-12-18 15:45:57 -08002696 // Haptic playback should be enabled by vibrator service.
2697 if (track->getHapticPlaybackEnabled()) {
2698 // Disable haptic playback of all active track to ensure only
2699 // one track playing haptic if current track should play haptic.
2700 for (const auto &t : mActiveTracks) {
2701 t->setHapticPlaybackEnabled(false);
2702 }
jiabin245cdd92018-12-07 17:55:15 -08002703 }
jiabine70bc7f2020-06-30 22:07:55 -07002704
2705 // Set haptic intensity for effect
2706 if (chain != nullptr) {
2707 chain->setHapticIntensity_l(track->id(), intensity);
2708 }
jiabin245cdd92018-12-07 17:55:15 -08002709 }
2710
Eric Laurent81784c32012-11-19 14:55:58 -08002711 track->mResetDone = false;
Andy Hung59de4262021-06-14 10:53:54 -07002712 track->resetPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08002713 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002714 if (chain != 0) {
2715 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2716 track->sessionId());
2717 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002718 }
2719
Andy Hungc2b11cb2020-04-22 09:04:01 -07002720 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002721 status = NO_ERROR;
2722 }
2723
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002724 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002725 return status;
2726}
2727
Eric Laurentbfb1b832013-01-07 09:53:42 -08002728bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002729{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002730 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002731 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002732 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2733 track->mState = TrackBase::STOPPED;
2734 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002735 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002736 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002737 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002738 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002739
2740 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002741}
2742
2743void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2744{
2745 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002746
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002747 String8 result;
2748 track->appendDump(result, false /* active */);
2749 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002750
Eric Laurent81784c32012-11-19 14:55:58 -08002751 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002752 {
2753 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2754 mAudioTrackCallbacks.erase(track);
2755 }
Eric Laurent81784c32012-11-19 14:55:58 -08002756 if (track->isFastTrack()) {
2757 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002758 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002759 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2760 mFastTrackAvailMask |= 1 << index;
2761 // redundant as track is about to be destroyed, for dumpsys only
2762 track->mFastIndex = -1;
2763 }
2764 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2765 if (chain != 0) {
2766 chain->decTrackCnt();
2767 }
2768}
2769
2770String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2771{
Eric Laurent81784c32012-11-19 14:55:58 -08002772 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002773 String8 out_s8;
2774 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2775 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002776 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002777 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002778}
2779
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002780status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2781 Mutex::Autolock _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002782 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002783 return NO_INIT;
2784 }
2785 return mOutput->stream->selectPresentation(presentationId, programId);
2786}
2787
Mikhail Naganov88536df2021-07-26 17:30:29 -07002788void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002789 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002790 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07002791 sp<AudioIoDescriptor> desc;
2792 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002793 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002794 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002795 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002796 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002797 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
2798 mSampleRate, mFormat, mChannelMask,
2799 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
2800 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08002801 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002802 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002803 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07002804 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002805 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002806 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002807 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08002808 break;
2809 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002810 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002811}
2812
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002813void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002814{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002815 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002816}
2817
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002818void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002819{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002820 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002821}
2822
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002823void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002824{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002825 mCallbackThread->setAsyncError();
2826}
2827
jiabinf6eb4c32020-02-25 14:06:25 -08002828void AudioFlinger::PlaybackThread::onCodecFormatChanged(
2829 const std::basic_string<uint8_t>& metadataBs)
2830{
2831 std::thread([this, metadataBs]() {
2832 audio_utils::metadata::Data metadata =
2833 audio_utils::metadata::dataFromByteString(metadataBs);
2834 if (metadata.empty()) {
2835 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
2836 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
2837 (int)metadataBs.size());
2838 return;
2839 }
2840
2841 audio_utils::metadata::ByteString metaDataStr =
2842 audio_utils::metadata::byteStringFromData(metadata);
2843 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
2844 Mutex::Autolock _l(mAudioTrackCbLock);
jiabin18a4b1c2020-09-17 11:40:42 -07002845 for (const auto& callbackPair : mAudioTrackCallbacks) {
2846 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08002847 }
2848 }).detach();
2849}
2850
Eric Laurent3b4529e2013-09-05 18:09:19 -07002851void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002852{
2853 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002854 // reject out of sequence requests
2855 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2856 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002857 mWaitWorkCV.signal();
2858 }
2859}
2860
Eric Laurent3b4529e2013-09-05 18:09:19 -07002861void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002862{
2863 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002864 // reject out of sequence requests
2865 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002866 // Register discontinuity when HW drain is completed because that can cause
2867 // the timestamp frame position to reset to 0 for direct and offload threads.
2868 // (Out of sequence requests are ignored, since the discontinuity would be handled
2869 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11002870 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002871 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002872 mWaitWorkCV.signal();
2873 }
2874}
2875
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002876void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002877{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002878 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00002879 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
2880 mSampleRate = audioConfig.sample_rate;
2881 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002882 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002883 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002884 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02002885 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07002886 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2887 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002888 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02002889
2890 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
2891 mMixerChannelMask = mChannelMask;
2892 }
2893
Andy Hunge5412692014-05-16 11:25:07 -07002894 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002895 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002896
Eric Laurentf1f22e72021-07-13 14:04:14 +02002897 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
2898
Phil Burkca5e6142015-07-14 09:42:29 -07002899 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002900 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002901 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002902 // Get format from the shim, which will be different than the HAL format
2903 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002904 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002905 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002906 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002907 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02002908 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07002909 LOG_FATAL("HAL format %#x not supported for mixed output",
2910 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002911 }
Phil Burk062e67a2015-02-11 13:40:50 -08002912 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002913 result = mOutput->stream->getBufferSize(&mBufferSize);
2914 LOG_ALWAYS_FATAL_IF(result != OK,
2915 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002916 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02002917 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002918 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002919 mFrameCount);
2920 }
2921
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002922 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2923 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002924 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002925 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002926 }
2927 }
2928
Eric Laurentd1f69b02014-12-15 14:33:13 -08002929 mHwSupportsPause = false;
2930 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002931 bool supportsPause = false, supportsResume = false;
2932 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2933 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002934 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002935 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002936 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002937 } else if (supportsResume) {
2938 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002939 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002940 }
2941 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002942 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2943 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2944 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002945
Andy Hungfbfc3952015-01-15 13:33:51 -08002946 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2947 // For best precision, we use float instead of the associated output
2948 // device format (typically PCM 16 bit).
2949
2950 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2951 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2952 mBufferSize = mFrameSize * mFrameCount;
2953
2954 // TODO: We currently use the associated output device channel mask and sample rate.
2955 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2956 // (if a valid mask) to avoid premature downmix.
2957 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2958 // instead of the output device sample rate to avoid loss of high frequency information.
2959 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2960 }
2961
Andy Hung09a50072014-02-27 14:30:47 -08002962 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002963 double multiplier = 1.0;
2964 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2965 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002966 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2967 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002968
Eric Laurent81784c32012-11-19 14:55:58 -08002969 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2970 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2971 maxNormalFrameCount = maxNormalFrameCount & ~15;
2972 if (maxNormalFrameCount < minNormalFrameCount) {
2973 maxNormalFrameCount = minNormalFrameCount;
2974 }
2975 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2976 if (multiplier <= 1.0) {
2977 multiplier = 1.0;
2978 } else if (multiplier <= 2.0) {
2979 if (2 * mFrameCount <= maxNormalFrameCount) {
2980 multiplier = 2.0;
2981 } else {
2982 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2983 }
2984 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002985 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002986 }
2987 }
2988 mNormalFrameCount = multiplier * mFrameCount;
2989 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02002990 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07002991 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2992 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002993 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002994 mNormalFrameCount);
2995
Andy Hung08fb1742015-05-31 23:22:10 -07002996 // Check if we want to throttle the processing to no more than 2x normal rate
2997 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002998 mThreadThrottleTimeMs = 0;
2999 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003000 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3001
Andy Hung010a1a12014-03-13 13:57:33 -07003002 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3003 // Originally this was int16_t[] array, need to remove legacy implications.
3004 free(mSinkBuffer);
3005 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07003006 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3007 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3008 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003009 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003010
Andy Hung69aed5f2014-02-25 17:24:40 -08003011 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3012 // drives the output.
3013 free(mMixerBuffer);
3014 mMixerBuffer = NULL;
3015 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003016 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003017 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003018 * audio_bytes_per_sample(mMixerBufferFormat);
3019 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3020 }
Andy Hung98ef9782014-03-04 14:46:50 -08003021 free(mEffectBuffer);
3022 mEffectBuffer = NULL;
3023 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07003024 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003025 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003026 * audio_bytes_per_sample(mEffectBufferFormat);
3027 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3028 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003029
Mikhail Naganov55773032020-10-01 15:08:13 -07003030 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3031 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003032 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3033 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003034 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003035
Eric Laurent81784c32012-11-19 14:55:58 -08003036 // force reconfiguration of effect chains and engines to take new buffer size and audio
3037 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08003038 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003039 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3040 // matter.
3041 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
3042 Vector< sp<EffectChain> > effectChains = mEffectChains;
3043 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent6c796322019-04-09 14:13:17 -07003044 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(),
3045 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003046 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003047
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003048 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003049 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003050 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
3051 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
3052 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3053 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3054 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3055 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3056 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3057 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3058 (int32_t)mHapticChannelMask)
3059 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3060 (int32_t)mHapticChannelCount)
3061 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
3062 formatToString(mHALFormat).c_str())
3063 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3064 (int32_t)mFrameCount) // sic - added HAL
3065 ;
3066 uint32_t latencyMs;
3067 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3068 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3069 }
3070 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003071}
3072
Kevin Rocard069c2712018-03-29 19:09:14 -07003073void AudioFlinger::PlaybackThread::updateMetadata_l()
3074{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003075 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Kevin Rocard12381092018-04-11 09:19:59 -07003076 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003077 }
3078 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003079 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07003080 for (const sp<Track> &track : mActiveTracks) {
3081 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurentb9cc0ab2021-01-29 11:46:52 +01003082 // Do not forward metadata for PatchTrack with unspecified stream type
3083 if (track->streamType() != AUDIO_STREAM_PATCH) {
3084 track->copyMetadataTo(backInserter);
3085 }
Kevin Rocard069c2712018-03-29 19:09:14 -07003086 }
Kevin Rocard12381092018-04-11 09:19:59 -07003087 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00003088}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003089
Kevin Rocard12381092018-04-11 09:19:59 -07003090void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
3091 const StreamOutHalInterface::SourceMetadata& metadata)
3092{
3093 mOutput->stream->updateSourceMetadata(metadata);
3094};
3095
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003096status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08003097{
3098 if (halFrames == NULL || dspFrames == NULL) {
3099 return BAD_VALUE;
3100 }
3101 Mutex::Autolock _l(mLock);
3102 if (initCheck() != NO_ERROR) {
3103 return INVALID_OPERATION;
3104 }
Andy Hung818e7a32016-02-16 18:08:07 -08003105 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003106 *halFrames = framesWritten;
3107
3108 if (isSuspended()) {
3109 // return an estimation of rendered frames when the output is suspended
3110 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003111 *dspFrames = (uint32_t)
3112 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003113 return NO_ERROR;
3114 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003115 status_t status;
3116 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003117 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003118 *dspFrames = (size_t)frames;
3119 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003120 }
3121}
3122
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003123product_strategy_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003124{
3125 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3126 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3127 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003128 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003129 }
3130 for (size_t i = 0; i < mTracks.size(); i++) {
3131 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003132 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003133 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003134 }
3135 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003136 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003137}
3138
3139
Phil Burk062e67a2015-02-11 13:40:50 -08003140AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003141{
3142 Mutex::Autolock _l(mLock);
3143 return mOutput;
3144}
3145
Phil Burk062e67a2015-02-11 13:40:50 -08003146AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003147{
3148 Mutex::Autolock _l(mLock);
3149 AudioStreamOut *output = mOutput;
3150 mOutput = NULL;
3151 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3152 // must push a NULL and wait for ack
3153 mOutputSink.clear();
3154 mPipeSink.clear();
3155 mNormalSink.clear();
3156 return output;
3157}
3158
3159// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003160sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003161{
3162 if (mOutput == NULL) {
3163 return NULL;
3164 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003165 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003166}
3167
3168uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
3169{
3170 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3171}
3172
3173status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
3174{
3175 if (!isValidSyncEvent(event)) {
3176 return BAD_VALUE;
3177 }
3178
3179 Mutex::Autolock _l(mLock);
3180
3181 for (size_t i = 0; i < mTracks.size(); ++i) {
3182 sp<Track> track = mTracks[i];
3183 if (event->triggerSession() == track->sessionId()) {
3184 (void) track->setSyncEvent(event);
3185 return NO_ERROR;
3186 }
3187 }
3188
3189 return NAME_NOT_FOUND;
3190}
3191
3192bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
3193{
3194 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3195}
3196
3197void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
3198 const Vector< sp<Track> >& tracksToRemove)
3199{
Andy Hungfe726a62018-09-27 15:17:25 -07003200 // Miscellaneous track cleanup when removed from the active list,
3201 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003202#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003203 for (const auto& track : tracksToRemove) {
3204 if (track->isExternalTrack()) {
3205 // to track the speaker usage
3206 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003207 }
3208 }
Andy Hungfe726a62018-09-27 15:17:25 -07003209#else
3210 (void)tracksToRemove; // suppress unused warning
3211#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003212}
3213
3214void AudioFlinger::PlaybackThread::checkSilentMode_l()
3215{
3216 if (!mMasterMute) {
3217 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003218 if (mOutDeviceTypeAddrs.empty()) {
3219 ALOGD("ro.audio.silent is ignored since no output device is set");
3220 return;
3221 }
jiabinc52b1ff2019-10-31 17:20:42 -07003222 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003223 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3224 return;
3225 }
Eric Laurent81784c32012-11-19 14:55:58 -08003226 if (property_get("ro.audio.silent", value, "0") > 0) {
3227 char *endptr;
3228 unsigned long ul = strtoul(value, &endptr, 0);
3229 if (*endptr == '\0' && ul != 0) {
3230 ALOGD("Silence is golden");
3231 // The setprop command will not allow a property to be changed after
3232 // the first time it is set, so we don't have to worry about un-muting.
3233 setMasterMute_l(true);
3234 }
3235 }
3236 }
3237}
3238
3239// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08003240ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003241{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003242 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003243 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003244 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003245 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003246
3247 // If an NBAIO sink is present, use it to write the normal mixer's submix
3248 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003249
Andy Hung010a1a12014-03-13 13:57:33 -07003250 const size_t count = mBytesRemaining / mFrameSize;
3251
Simon Wilson2d590962012-11-29 15:18:50 -08003252 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003253 // update the setpoint when AudioFlinger::mScreenState changes
3254 uint32_t screenState = AudioFlinger::mScreenState;
3255 if (screenState != mScreenState) {
3256 mScreenState = screenState;
3257 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3258 if (pipe != NULL) {
3259 pipe->setAvgFrames((mScreenState & 1) ?
3260 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3261 }
3262 }
Andy Hung010a1a12014-03-13 13:57:33 -07003263 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003264 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08003265 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003266 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07003267#ifdef TEE_SINK
3268 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3269#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003270 } else {
3271 bytesWritten = framesWritten;
3272 }
3273 // otherwise use the HAL / AudioStreamOut directly
3274 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003275 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003276
Eric Laurentbfb1b832013-01-07 09:53:42 -08003277 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003278 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3279 mWriteAckSequence += 2;
3280 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003281 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003282 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003283 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003284 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003285 // FIXME We should have an implementation of timestamps for direct output threads.
3286 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003287 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003288 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003289
Eric Laurentbfb1b832013-01-07 09:53:42 -08003290 if (mUseAsyncWrite &&
3291 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3292 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003293 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003294 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003295 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003296 }
Eric Laurent81784c32012-11-19 14:55:58 -08003297 }
3298
Eric Laurent81784c32012-11-19 14:55:58 -08003299 mNumWrites++;
3300 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003301 if (mStandby) {
3302 mThreadMetrics.logBeginInterval();
3303 mStandby = false;
3304 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003305 return bytesWritten;
3306}
3307
3308void AudioFlinger::PlaybackThread::threadLoop_drain()
3309{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003310 bool supportsDrain = false;
3311 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003312 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3313 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003314 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3315 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003316 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003317 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003318 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003319 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003320 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003321 }
3322}
3323
3324void AudioFlinger::PlaybackThread::threadLoop_exit()
3325{
Eric Laurent275e8e92014-11-30 15:14:47 -08003326 {
3327 Mutex::Autolock _l(mLock);
3328 for (size_t i = 0; i < mTracks.size(); i++) {
3329 sp<Track> track = mTracks[i];
3330 track->invalidate();
3331 }
Andy Hungdae27702016-10-31 14:01:16 -07003332 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3333 // After we exit there are no more track changes sent to BatteryNotifier
3334 // because that requires an active threadLoop.
3335 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3336 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003337 }
Eric Laurent81784c32012-11-19 14:55:58 -08003338}
3339
3340/*
3341The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003342 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003343 - mActiveSleepTimeUs from activeSleepTimeUs()
3344 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003345 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3346 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003347 - maxPeriod from frame count and sample rate (MIXER only)
3348
3349The parameters that affect these derived values are:
3350 - frame count
3351 - frame size
3352 - sample rate
3353 - device type: A2DP or not
3354 - device latency
3355 - format: PCM or not
3356 - active sleep time
3357 - idle sleep time
3358*/
3359
3360void AudioFlinger::PlaybackThread::cacheParameters_l()
3361{
Andy Hung25c2dac2014-02-27 14:56:00 -08003362 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003363 mActiveSleepTimeUs = activeSleepTimeUs();
3364 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003365
3366 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3367 // truncating audio when going to standby.
3368 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
jiabinc52b1ff2019-10-31 17:20:42 -07003369 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003370 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3371 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3372 }
3373 }
Eric Laurent81784c32012-11-19 14:55:58 -08003374}
3375
Eric Laurent13084622016-05-17 10:51:49 -07003376bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003377{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003378 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003379 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003380 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003381 size_t size = mTracks.size();
3382 for (size_t i = 0; i < size; i++) {
3383 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003384 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003385 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003386 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003387 }
3388 }
Eric Laurent13084622016-05-17 10:51:49 -07003389 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003390}
3391
Haynes Mathew George05317d22016-05-03 16:34:26 -07003392void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3393{
3394 Mutex::Autolock _l(mLock);
3395 invalidateTracks_l(streamType);
3396}
3397
jiabinf042b9b2021-05-07 23:46:28 +00003398// getTrackById_l must be called with holding thread lock
3399AudioFlinger::PlaybackThread::Track* AudioFlinger::PlaybackThread::getTrackById_l(
3400 audio_port_handle_t trackPortId) {
3401 for (size_t i = 0; i < mTracks.size(); i++) {
3402 if (mTracks[i]->portId() == trackPortId) {
3403 return mTracks[i].get();
3404 }
3405 }
3406 return nullptr;
3407}
3408
Eric Laurent81784c32012-11-19 14:55:58 -08003409status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3410{
Glenn Kastend848eb42016-03-08 13:42:11 -08003411 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003412 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003413 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08003414 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3415 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3416 &halInBuffer);
3417 if (result != OK) return result;
3418 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003419 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003420 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003421 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003422 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003423 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003424 if (mType != DIRECT) {
Eric Laurentf1f22e72021-07-13 14:04:14 +02003425 size_t numSamples = mNormalFrameCount
3426 * (audio_channel_count_from_out_mask(mMixerChannelMask) + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003427 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003428 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003429 &halInBuffer);
3430 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003431#ifdef FLOAT_EFFECT_CHAIN
3432 buffer = halInBuffer->audioBuffer()->f32;
3433#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003434 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003435#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003436 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3437 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003438 }
3439
3440 // Attach all tracks with same session ID to this chain.
3441 for (size_t i = 0; i < mTracks.size(); ++i) {
3442 sp<Track> track = mTracks[i];
3443 if (session == track->sessionId()) {
3444 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3445 buffer);
3446 track->setMainBuffer(buffer);
3447 chain->incTrackCnt();
3448 }
3449 }
3450
3451 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003452 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003453 if (session == track->sessionId()) {
3454 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3455 chain->incActiveTrackCnt();
3456 }
3457 }
3458 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003459 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003460 chain->setInBuffer(halInBuffer);
3461 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003462 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3463 // chains list in order to be processed last as it contains output device effects.
3464 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3465 // processing effects specific to an output stream before effects applied to all streams
3466 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003467 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3468 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003469 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003470 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003471 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003472 // Effect chain for other sessions are inserted at beginning of effect
3473 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003474 // sessions is not important.
3475 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003476 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3477 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003478 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003479 size_t size = mEffectChains.size();
3480 size_t i = 0;
3481 for (i = 0; i < size; i++) {
3482 if (mEffectChains[i]->sessionId() < session) {
3483 break;
3484 }
3485 }
3486 mEffectChains.insertAt(chain, i);
3487 checkSuspendOnAddEffectChain_l(chain);
3488
3489 return NO_ERROR;
3490}
3491
3492size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3493{
Glenn Kastend848eb42016-03-08 13:42:11 -08003494 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003495
3496 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3497
3498 for (size_t i = 0; i < mEffectChains.size(); i++) {
3499 if (chain == mEffectChains[i]) {
3500 mEffectChains.removeAt(i);
3501 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003502 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003503 if (session == track->sessionId()) {
3504 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3505 chain.get(), session);
3506 chain->decActiveTrackCnt();
3507 }
3508 }
3509
3510 // detach all tracks with same session ID from this chain
3511 for (size_t i = 0; i < mTracks.size(); ++i) {
3512 sp<Track> track = mTracks[i];
3513 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003514 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003515 chain->decTrackCnt();
3516 }
3517 }
3518 break;
3519 }
3520 }
3521 return mEffectChains.size();
3522}
3523
3524status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003525 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003526{
3527 Mutex::Autolock _l(mLock);
3528 return attachAuxEffect_l(track, EffectId);
3529}
3530
3531status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003532 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003533{
3534 status_t status = NO_ERROR;
3535
3536 if (EffectId == 0) {
3537 track->setAuxBuffer(0, NULL);
3538 } else {
3539 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3540 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3541 if (effect != 0) {
3542 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3543 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3544 } else {
3545 status = INVALID_OPERATION;
3546 }
3547 } else {
3548 status = BAD_VALUE;
3549 }
3550 }
3551 return status;
3552}
3553
3554void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3555{
3556 for (size_t i = 0; i < mTracks.size(); ++i) {
3557 sp<Track> track = mTracks[i];
3558 if (track->auxEffectId() == effectId) {
3559 attachAuxEffect_l(track, 0);
3560 }
3561 }
3562}
3563
3564bool AudioFlinger::PlaybackThread::threadLoop()
3565{
Glenn Kasten388d5712017-04-07 14:38:41 -07003566 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003567
Eric Laurent81784c32012-11-19 14:55:58 -08003568 Vector< sp<Track> > tracksToRemove;
3569
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003570 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003571 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003572
3573 // MIXER
3574 nsecs_t lastWarning = 0;
3575
3576 // DUPLICATING
3577 // FIXME could this be made local to while loop?
3578 writeFrames = 0;
3579
3580 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003581 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003582
3583 if (mType == MIXER) {
3584 sleepTimeShift = 0;
3585 }
3586
3587 CpuStats cpuStats;
3588 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3589
3590 acquireWakeLock();
3591
Glenn Kasteneef598c2017-04-03 14:41:13 -07003592 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3593 // thread associated with this PlaybackThread.
3594 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3595 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003596 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3597 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003598 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003599 const char *logString = NULL;
3600
rago1bb90822017-05-02 18:31:48 -07003601 // Estimated time for next buffer to be written to hal. This is used only on
3602 // suspended mode (for now) to help schedule the wait time until next iteration.
3603 nsecs_t timeLoopNextNs = 0;
3604
Eric Laurent664539d2013-09-23 18:24:31 -07003605 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003606
Andy Hung2dbffc22018-08-08 18:50:41 -07003607 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003608
Eric Laurentb3f315a2021-07-13 15:09:05 +02003609 sendCheckOutputStageEffectsEvent();
3610
Andy Hung446f4df2019-02-21 12:26:41 -08003611 // loopCount is used for statistics and diagnostics.
3612 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003613 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003614 // Log merge requests are performed during AudioFlinger binder transactions, but
3615 // that does not cover audio playback. It's requested here for that reason.
3616 mAudioFlinger->requestLogMerge();
3617
Eric Laurent81784c32012-11-19 14:55:58 -08003618 cpuStats.sample(myName);
3619
3620 Vector< sp<EffectChain> > effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003621 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Andy Hungc1646382019-04-30 16:12:10 -07003622 std::vector<sp<Track>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003623
Andy Hung2dbffc22018-08-08 18:50:41 -07003624 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3625 //
jiabinc52b1ff2019-10-31 17:20:42 -07003626 // Note: we access outDeviceTypes() outside of mLock.
3627 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003628 // Here, we try for the AF lock, but do not block on it as the latency
3629 // is more informational.
3630 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3631 std::vector<PatchPanel::SoftwarePatch> swPatches;
3632 double latencyMs;
3633 status_t status = INVALID_OPERATION;
3634 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3635 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3636 && swPatches.size() > 0) {
3637 status = swPatches[0].getLatencyMs_l(&latencyMs);
3638 downstreamPatchHandle = swPatches[0].getPatchHandle();
3639 }
3640 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003641 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003642 lastDownstreamPatchHandle = downstreamPatchHandle;
3643 }
3644 if (status == OK) {
3645 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003646 // latency of 5 seconds).
3647 const double minLatency = 0., maxLatency = 5000.;
3648 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003649 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003650 } else {
3651 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003652 if (latencyMs < minLatency) latencyMs = minLatency;
3653 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003654 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003655 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003656 }
3657 mAudioFlinger->mLock.unlock();
3658 }
3659 } else {
3660 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3661 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003662 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003663 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3664 }
3665 }
3666
Eric Laurentb3f315a2021-07-13 15:09:05 +02003667 if (mCheckOutputStageEffects.exchange(false)) {
3668 checkOutputStageEffects();
3669 }
3670
Eric Laurent81784c32012-11-19 14:55:58 -08003671 { // scope for mLock
3672
3673 Mutex::Autolock _l(mLock);
3674
Eric Laurent021cf962014-05-13 10:18:14 -07003675 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02003676 if (mCheckOutputStageEffects.load()) {
3677 continue;
3678 }
Eric Laurent10351942014-05-08 18:49:52 -07003679
Glenn Kasteneef598c2017-04-03 14:41:13 -07003680 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003681 if (logString != NULL) {
3682 mNBLogWriter->logTimestamp();
3683 mNBLogWriter->log(logString);
3684 logString = NULL;
3685 }
3686
Dean Wheatley12473e92021-03-18 23:00:55 +11003687 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07003688
Eric Laurent81784c32012-11-19 14:55:58 -08003689 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003690 if (mSignalPending) {
3691 // A signal was raised while we were unlocked
3692 mSignalPending = false;
3693 } else if (waitingAsyncCallback_l()) {
3694 if (exitPending()) {
3695 break;
3696 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003697 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003698 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003699 releaseWakeLock_l();
3700 released = true;
3701 }
Andy Hung10cbff12017-02-21 17:30:14 -08003702
3703 const int64_t waitNs = computeWaitTimeNs_l();
3704 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3705 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3706 if (status == TIMED_OUT) {
3707 mSignalPending = true; // if timeout recheck everything
3708 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003709 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003710 if (released) {
3711 acquireWakeLock_l();
3712 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003713 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3714 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003715
3716 continue;
3717 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003718 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003719 isSuspended()) {
3720 // put audio hardware into standby after short delay
3721 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003722
3723 threadLoop_standby();
3724
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003725 // This is where we go into standby
3726 if (!mStandby) {
3727 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07003728 mThreadMetrics.logEndInterval();
3729 mStandby = true;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003730 }
Andy Hungd0979812019-02-21 15:51:44 -08003731 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003732 }
3733
Eric Tan39ec8d62018-07-24 09:49:29 -07003734 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003735 // we're about to wait, flush the binder command buffer
3736 IPCThreadState::self()->flushCommands();
3737
3738 clearOutputTracks();
3739
3740 if (exitPending()) {
3741 break;
3742 }
3743
3744 releaseWakeLock_l();
3745 // wait until we have something to do...
3746 ALOGV("%s going to sleep", myName.string());
3747 mWaitWorkCV.wait(mLock);
3748 ALOGV("%s waking up", myName.string());
3749 acquireWakeLock_l();
3750
3751 mMixerStatus = MIXER_IDLE;
3752 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3753 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003754 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003755 checkSilentMode_l();
3756
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003757 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3758 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003759 if (mType == MIXER) {
3760 sleepTimeShift = 0;
3761 }
3762
3763 continue;
3764 }
3765 }
Eric Laurent81784c32012-11-19 14:55:58 -08003766 // mMixerStatusIgnoringFastTracks is also updated internally
3767 mMixerStatus = prepareTracks_l(&tracksToRemove);
3768
Andy Hungdae27702016-10-31 14:01:16 -07003769 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003770
Kevin Rocard069c2712018-03-29 19:09:14 -07003771 updateMetadata_l();
3772
Eric Laurent81784c32012-11-19 14:55:58 -08003773 // prevent any changes in effect chain list and in each effect chain
3774 // during mixing and effect process as the audio buffers could be deleted
3775 // or modified if an effect is created or deleted
3776 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07003777
3778 // Determine which session to pick up haptic data.
3779 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07003780 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003781 // TODO: Write haptic data directly to sink buffer when mixing.
3782 if (mHapticChannelCount > 0 && effectChains.size() > 0) {
3783 for (const auto& track : mActiveTracks) {
jiabineb3bda02020-06-30 14:07:03 -07003784 sp<EffectChain> effectChain = getEffectChain_l(track->sessionId());
3785 if (effectChain != nullptr && effectChain->containsHapticGeneratingEffect_l()) {
3786 activeHapticSessionId = track->sessionId();
3787 break;
3788 }
Andy Hung6e6a2e62019-04-30 16:38:41 -07003789 if (track->getHapticPlaybackEnabled()) {
3790 activeHapticSessionId = track->sessionId();
3791 break;
3792 }
3793 }
3794 }
3795
Andy Hungc1646382019-04-30 16:12:10 -07003796 // Acquire a local copy of active tracks with lock (release w/o lock).
3797 //
3798 // Control methods on the track acquire the ThreadBase lock (e.g. start()
3799 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
3800 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
3801 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003802 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003803
Eric Laurentbfb1b832013-01-07 09:53:42 -08003804 if (mBytesRemaining == 0) {
3805 mCurrentWriteLength = 0;
3806 if (mMixerStatus == MIXER_TRACKS_READY) {
3807 // threadLoop_mix() sets mCurrentWriteLength
3808 threadLoop_mix();
3809 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3810 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003811 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003812 // must be written to HAL
3813 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003814 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003815 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07003816
3817 // Tally underrun frames as we are inserting 0s here.
3818 for (const auto& track : activeTracks) {
Andy Hunge2e830f2019-12-03 12:54:46 -08003819 if (track->mFillingUpStatus == Track::FS_ACTIVE
3820 && !track->isStopped()
3821 && !track->isPaused()
3822 && !track->isTerminated()) {
3823 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
3824 __func__, track->id(), track->getTrackStateAsString(),
3825 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07003826 track->mAudioTrackServerProxy->tallyUnderrunFrames(mNormalFrameCount);
3827 }
3828 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003829 }
3830 }
Andy Hung98ef9782014-03-04 14:46:50 -08003831 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003832 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003833 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3834 // or mSinkBuffer (if there are no effects).
3835 //
3836 // This is done pre-effects computation; if effects change to
3837 // support higher precision, this needs to move.
3838 //
3839 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003840 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003841 if (mMixerBufferValid) {
3842 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3843 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003844 uint32_t channelCount = mEffectBufferValid ?
3845 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
Andy Hung98ef9782014-03-04 14:46:50 -08003846
Andy Hung2ddee192015-12-18 17:34:44 -08003847 // mono blend occurs for mixer threads only (not direct or offloaded)
3848 // and is handled here if we're going directly to the sink.
3849 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003850 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3851 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003852 }
3853
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003854 if (!hasFastMixer()) {
3855 // Balance must take effect after mono conversion.
3856 // We do it here if there is no FastMixer.
3857 // mBalance detects zero balance within the class for speed (not needed here).
3858 mBalance.setBalance(mMasterBalance.load());
3859 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
3860 }
3861
Andy Hung98ef9782014-03-04 14:46:50 -08003862 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurentf1f22e72021-07-13 14:04:14 +02003863 mNormalFrameCount * (channelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08003864
3865 // If we're going directly to the sink and there are haptic channels,
3866 // we should adjust channels as the sample data is partially interleaved
3867 // in this case.
3868 if (!mEffectBufferValid && mHapticChannelCount > 0) {
3869 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
3870 mChannelCount + mHapticChannelCount,
3871 audio_bytes_per_sample(format),
3872 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
3873 }
Andy Hung98ef9782014-03-04 14:46:50 -08003874 }
3875
Eric Laurentbfb1b832013-01-07 09:53:42 -08003876 mBytesRemaining = mCurrentWriteLength;
3877 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003878 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3879 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3880 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3881 mBytesWritten += mBytesRemaining;
3882 mFramesWritten += framesRemaining;
3883 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003884 mBytesRemaining = 0;
3885 }
Eric Laurent81784c32012-11-19 14:55:58 -08003886
Eric Laurentbfb1b832013-01-07 09:53:42 -08003887 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003888 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003889 for (size_t i = 0; i < effectChains.size(); i ++) {
3890 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07003891 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003892 if (activeHapticSessionId != AUDIO_SESSION_NONE
3893 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07003894 // Haptic data is active in this case, copy it directly from
3895 // in buffer to out buffer.
3896 const size_t audioBufferSize = mNormalFrameCount
3897 * audio_bytes_per_frame(mChannelCount, EFFECT_BUFFER_FORMAT);
3898 memcpy_by_audio_format(
3899 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
3900 EFFECT_BUFFER_FORMAT,
3901 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
3902 EFFECT_BUFFER_FORMAT, mNormalFrameCount * mHapticChannelCount);
3903 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003904 }
Eric Laurent81784c32012-11-19 14:55:58 -08003905 }
3906 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003907 // Process effect chains for offloaded thread even if no audio
3908 // was read from audio track: process only updates effect state
3909 // and thus does have to be synchronized with audio writes but may have
3910 // to be called while waiting for async write callback
3911 if (mType == OFFLOAD) {
3912 for (size_t i = 0; i < effectChains.size(); i ++) {
3913 effectChains[i]->process_l();
3914 }
3915 }
Eric Laurent81784c32012-11-19 14:55:58 -08003916
Andy Hung98ef9782014-03-04 14:46:50 -08003917 // Only if the Effects buffer is enabled and there is data in the
3918 // Effects buffer (buffer valid), we need to
3919 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003920 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003921 if (mEffectBufferValid) {
3922 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003923
3924 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003925 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3926 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003927 }
3928
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003929 if (!hasFastMixer()) {
3930 // Balance must take effect after mono conversion.
3931 // We do it here if there is no FastMixer.
3932 // mBalance detects zero balance within the class for speed (not needed here).
3933 mBalance.setBalance(mMasterBalance.load());
3934 mBalance.process((float *)mEffectBuffer, mNormalFrameCount);
3935 }
3936
Andy Hung98ef9782014-03-04 14:46:50 -08003937 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003938 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3939 // The sample data is partially interleaved when haptic channels exist,
3940 // we need to adjust channels here.
3941 if (mHapticChannelCount > 0) {
3942 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
3943 mChannelCount + mHapticChannelCount,
3944 audio_bytes_per_sample(mFormat),
3945 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
3946 }
Andy Hung98ef9782014-03-04 14:46:50 -08003947 }
3948
Eric Laurent81784c32012-11-19 14:55:58 -08003949 // enable changes in effect chain
3950 unlockEffectChains(effectChains);
3951
Eric Laurentbfb1b832013-01-07 09:53:42 -08003952 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003953 // mSleepTimeUs == 0 means we must write to audio hardware
3954 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003955 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003956 // writePeriodNs is updated >= 0 when ret > 0.
3957 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003958 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003959 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08003960 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07003961 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08003962 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003963 if (ret < 0) {
3964 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003965 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003966 mBytesWritten += ret;
3967 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08003968 const int64_t frames = ret / mFrameSize;
3969 mFramesWritten += frames;
3970
3971 writePeriodNs = lastIoEndNs - mLastIoEndNs;
3972 // process information relating to write time.
3973 if (audio_has_proportional_frames(mFormat)) {
3974 // we are in a continuous mixing cycle
3975 if (mMixerStatus == MIXER_TRACKS_READY &&
3976 loopCount == lastLoopCountWritten + 1) {
3977
3978 const double jitterMs =
3979 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
3980 {frames, writePeriodNs},
3981 {0, 0} /* lastTimestamp */, mSampleRate);
3982 const double processMs =
3983 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
3984
3985 Mutex::Autolock _l(mLock);
3986 mIoJitterMs.add(jitterMs);
3987 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00003988
3989 if (mPipeSink.get() != nullptr) {
3990 // Using the Monopipe availableToWrite, we estimate the current
3991 // buffer size.
3992 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
3993 const ssize_t
3994 availableToWrite = mPipeSink->availableToWrite();
3995 const size_t pipeFrames = monoPipe->maxFrames();
3996 const size_t
3997 remainingFrames = pipeFrames - max(availableToWrite, 0);
3998 mMonopipePipeDepthStats.add(remainingFrames);
3999 }
Andy Hung446f4df2019-02-21 12:26:41 -08004000 }
4001
4002 // write blocked detection
4003 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
4004 if (mType == MIXER && deltaWriteNs > maxPeriod) {
4005 mNumDelayedWrites++;
4006 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4007 ATRACE_NAME("underrun");
4008 ALOGW("write blocked for %lld msecs, "
4009 "%d delayed writes, thread %d",
4010 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4011 mNumDelayedWrites, mId);
4012 lastWarning = lastIoEndNs;
4013 }
4014 }
4015 }
4016 // update timing info.
4017 mLastIoBeginNs = lastIoBeginNs;
4018 mLastIoEndNs = lastIoEndNs;
4019 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004020 }
4021 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4022 (mMixerStatus == MIXER_DRAIN_ALL)) {
4023 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004024 }
Andy Hung08fb1742015-05-31 23:22:10 -07004025 if (mType == MIXER && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004026
4027 if (mThreadThrottle
4028 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004029 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004030 // Limit MixerThread data processing to no more than twice the
4031 // expected processing rate.
4032 //
4033 // This helps prevent underruns with NuPlayer and other applications
4034 // which may set up buffers that are close to the minimum size, or use
4035 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4036 //
4037 // The throttle smooths out sudden large data drains from the device,
4038 // e.g. when it comes out of standby, which often causes problems with
4039 // (1) mixer threads without a fast mixer (which has its own warm-up)
4040 // (2) minimum buffer sized tracks (even if the track is full,
4041 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004042 //
4043 // Total time spent in last processing cycle equals time spent in
4044 // 1. threadLoop_write, as well as time spent in
4045 // 2. threadLoop_mix (significant for heavy mixing, especially
4046 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004047
Andy Hung446f4df2019-02-21 12:26:41 -08004048 // it's OK if deltaMs is an overestimate.
4049
4050 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004051
Ivan Lozanoea04d392017-11-07 14:37:07 -08004052 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004053 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004054 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004055
Andy Hung08fb1742015-05-31 23:22:10 -07004056 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004057 // notify of throttle start on verbose log
4058 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4059 "mixer(%p) throttle begin:"
4060 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004061 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004062 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004063 // Throttle must be attributed to the previous mixer loop's write time
4064 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004065 // This also ensures proper timing statistics.
4066 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004067 } else {
4068 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4069 if (diff > 0) {
4070 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004071 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004072 ALOGD_IF(!isSingleDeviceType(
4073 outDeviceTypes(), audio_is_a2dp_out_device) &&
4074 !isSingleDeviceType(
4075 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004076 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004077 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4078 }
Andy Hung08fb1742015-05-31 23:22:10 -07004079 }
4080 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004081 }
Eric Laurent81784c32012-11-19 14:55:58 -08004082
Eric Laurentbfb1b832013-01-07 09:53:42 -08004083 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004084 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07004085 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07004086 // suspended requires accurate metering of sleep time.
4087 if (isSuspended()) {
4088 // advance by expected sleepTime
4089 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4090 const nsecs_t nowNs = systemTime();
4091
4092 // compute expected next time vs current time.
4093 // (negative deltas are treated as delays).
4094 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4095 if (deltaNs < -kMaxNextBufferDelayNs) {
4096 // Delays longer than the max allowed trigger a reset.
4097 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4098 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4099 timeLoopNextNs = nowNs + deltaNs;
4100 } else if (deltaNs < 0) {
4101 // Delays within the max delay allowed: zero the delta/sleepTime
4102 // to help the system catch up in the next iteration(s)
4103 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4104 deltaNs = 0;
4105 }
4106 // update sleep time (which is >= 0)
4107 mSleepTimeUs = deltaNs / 1000;
4108 }
Eric Laurente93cc032016-05-05 10:15:10 -07004109 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4110 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004111 }
Glenn Kastene7754022014-10-31 12:11:26 -07004112 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004113 }
Eric Laurent81784c32012-11-19 14:55:58 -08004114 }
4115
4116 // Finally let go of removed track(s), without the lock held
4117 // since we can't guarantee the destructors won't acquire that
4118 // same lock. This will also mutate and push a new fast mixer state.
4119 threadLoop_removeTracks(tracksToRemove);
4120 tracksToRemove.clear();
4121
4122 // FIXME I don't understand the need for this here;
4123 // it was in the original code but maybe the
4124 // assignment in saveOutputTracks() makes this unnecessary?
4125 clearOutputTracks();
4126
4127 // Effect chains will be actually deleted here if they were removed from
4128 // mEffectChains list during mixing or effects processing
4129 effectChains.clear();
4130
4131 // FIXME Note that the above .clear() is no longer necessary since effectChains
4132 // is now local to this block, but will keep it for now (at least until merge done).
4133 }
4134
Eric Laurentbfb1b832013-01-07 09:53:42 -08004135 threadLoop_exit();
4136
Eric Laurentcf817a22014-08-04 20:36:31 -07004137 if (!mStandby) {
4138 threadLoop_standby();
4139 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004140 }
4141
4142 releaseWakeLock();
4143
4144 ALOGV("Thread %p type %d exiting", this, mType);
4145 return false;
4146}
4147
Dean Wheatley12473e92021-03-18 23:00:55 +11004148void AudioFlinger::PlaybackThread::collectTimestamps_l()
4149{
4150 // Collect timestamp statistics for the Playback Thread types that support it.
4151 if (mType != MIXER
4152 && mType != DUPLICATING
4153 && mType != DIRECT
4154 && mType != OFFLOAD) {
4155 return;
4156 }
4157 if (mStandby) {
4158 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4159 return;
4160 } else if (mHwPaused) {
4161 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4162 return;
4163 }
4164
4165 // Gather the framesReleased counters for all active tracks,
4166 // and associate with the sink frames written out. We need
4167 // this to convert the sink timestamp to the track timestamp.
4168 bool kernelLocationUpdate = false;
4169 ExtendedTimestamp timestamp; // use private copy to fetch
4170
4171 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4172 // HAL may be draining some small duration buffered data for fade out.
4173 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4174 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4175 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4176 mSampleRate);
4177
4178 if (isTimestampCorrectionEnabled()) {
4179 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4180 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4181 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4182 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4183 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4184 = correctedTimestamp.mFrames;
4185 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4186 = correctedTimestamp.mTimeNs;
4187 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4188 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4189 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4190
4191 // Note: Downstream latency only added if timestamp correction enabled.
4192 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4193 const int64_t newPosition =
4194 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4195 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4196 // prevent retrograde
4197 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4198 newPosition,
4199 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4200 - mSuspendedFrames));
4201 }
4202 }
4203
4204 // We always fetch the timestamp here because often the downstream
4205 // sink will block while writing.
4206
4207 // We keep track of the last valid kernel position in case we are in underrun
4208 // and the normal mixer period is the same as the fast mixer period, or there
4209 // is some error from the HAL.
4210 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4211 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4212 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4213 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4214 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4215
4216 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4217 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4218 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4219 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4220 }
4221
4222 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4223 kernelLocationUpdate = true;
4224 } else {
4225 ALOGVV("getTimestamp error - no valid kernel position");
4226 }
4227
4228 // copy over kernel info
4229 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4230 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4231 + mSuspendedFrames; // add frames discarded when suspended
4232 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4233 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4234 } else {
4235 mTimestampVerifier.error();
4236 }
4237
4238 // mFramesWritten for non-offloaded tracks are contiguous
4239 // even after standby() is called. This is useful for the track frame
4240 // to sink frame mapping.
4241 bool serverLocationUpdate = false;
4242 if (mFramesWritten != mLastFramesWritten) {
4243 serverLocationUpdate = true;
4244 mLastFramesWritten = mFramesWritten;
4245 }
4246 // Only update timestamps if there is a meaningful change.
4247 // Either the kernel timestamp must be valid or we have written something.
4248 if (kernelLocationUpdate || serverLocationUpdate) {
4249 if (serverLocationUpdate) {
4250 // use the time before we called the HAL write - it is a bit more accurate
4251 // to when the server last read data than the current time here.
4252 //
4253 // If we haven't written anything, mLastIoBeginNs will be -1
4254 // and we use systemTime().
4255 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4256 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4257 ? systemTime() : mLastIoBeginNs;
4258 }
4259
4260 for (const sp<Track> &t : mActiveTracks) {
4261 if (!t->isFastTrack()) {
4262 t->updateTrackFrameInfo(
4263 t->mAudioTrackServerProxy->framesReleased(),
4264 mFramesWritten,
4265 mSampleRate,
4266 mTimestamp);
4267 }
4268 }
4269 }
4270
4271 if (audio_has_proportional_frames(mFormat)) {
4272 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4273 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4274 mLatencyMs.add(latencyMs);
4275 }
4276 }
4277#if 0
4278 // logFormat example
4279 if (z % 100 == 0) {
4280 timespec ts;
4281 clock_gettime(CLOCK_MONOTONIC, &ts);
4282 LOGT("This is an integer %d, this is a float %f, this is my "
4283 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4284 LOGT("A deceptive null-terminated string %\0");
4285 }
4286 ++z;
4287#endif
4288}
4289
Eric Laurentbfb1b832013-01-07 09:53:42 -08004290// removeTracks_l() must be called with ThreadBase::mLock held
4291void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
4292{
Andy Hungfe726a62018-09-27 15:17:25 -07004293 for (const auto& track : tracksToRemove) {
4294 mActiveTracks.remove(track);
4295 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
4296 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
4297 if (chain != 0) {
4298 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4299 __func__, track->id(), chain.get(), track->sessionId());
4300 chain->decActiveTrackCnt();
4301 }
4302 // If an external client track, inform APM we're no longer active, and remove if needed.
4303 // We do this under lock so that the state is consistent if the Track is destroyed.
4304 if (track->isExternalTrack()) {
4305 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004306 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004307 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004308 }
4309 }
Andy Hungfe726a62018-09-27 15:17:25 -07004310 if (track->isTerminated()) {
4311 // remove from our tracks vector
4312 removeTrack_l(track);
4313 }
jiabineb3bda02020-06-30 14:07:03 -07004314 if (mHapticChannelCount > 0 &&
4315 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4316 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004317 mLock.unlock();
4318 // Unlock due to VibratorService will lock for this call and will
4319 // call Tracks.mute/unmute which also require thread's lock.
4320 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
4321 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004322
4323 // When the track is stop, set the haptic intensity as MUTE
4324 // for the HapticGenerator effect.
4325 if (chain != nullptr) {
4326 chain->setHapticIntensity_l(track->id(), static_cast<int>(os::HapticScale::MUTE));
4327 }
jiabin245cdd92018-12-07 17:55:15 -08004328 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004329 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004330}
Eric Laurent81784c32012-11-19 14:55:58 -08004331
Eric Laurentaccc1472013-09-20 09:36:34 -07004332status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
4333{
4334 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004335 ExtendedTimestamp ets;
4336 status_t status = mNormalSink->getTimestamp(ets);
4337 if (status == NO_ERROR) {
4338 status = ets.getBestTimestamp(&timestamp);
4339 }
4340 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004341 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004342 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004343 collectTimestamps_l();
4344 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4345 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004346 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004347 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4348 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4349 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4350 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4351 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004352 }
4353 return INVALID_OPERATION;
4354}
Eric Laurent1c333e22014-05-20 10:48:17 -07004355
Eric Laurenteab90452019-06-24 15:17:46 -07004356// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4357// still applied by the mixer.
4358// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4359// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4360// if more than one track are active
4361status_t AudioFlinger::PlaybackThread::handleVoipVolume_l(float *volume)
4362{
4363 status_t result = NO_ERROR;
4364 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4365 if (*volume != mLeftVolFloat) {
4366 result = mOutput->stream->setVolume(*volume, *volume);
4367 ALOGE_IF(result != OK,
4368 "Error when setting output stream volume: %d", result);
4369 if (result == NO_ERROR) {
4370 mLeftVolFloat = *volume;
4371 }
4372 }
4373 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4374 // remove stream volume contribution from software volume.
4375 if (mLeftVolFloat == *volume) {
4376 *volume = 1.0f;
4377 }
4378 }
4379 return result;
4380}
4381
Eric Laurent054d9d32015-04-24 08:48:48 -07004382status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
4383 audio_patch_handle_t *handle)
4384{
Andy Hungf60abce2016-08-26 11:37:54 -07004385 status_t status;
4386 if (property_get_bool("af.patch_park", false /* default_value */)) {
4387 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4388 // or if HAL does not properly lock against access.
4389 AutoPark<FastMixer> park(mFastMixer);
4390 status = PlaybackThread::createAudioPatch_l(patch, handle);
4391 } else {
4392 status = PlaybackThread::createAudioPatch_l(patch, handle);
4393 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004394 return status;
4395}
4396
Eric Laurent1c333e22014-05-20 10:48:17 -07004397status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
4398 audio_patch_handle_t *handle)
4399{
4400 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004401
4402 // store new device and send to effects
4403 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004404 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004405 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004406 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4407 && !mOutput->audioHwDev->supportsAudioPatches(),
4408 "Enumerated device type(%#x) must not be used "
4409 "as it does not support audio patches",
4410 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004411 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07004412 deviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
4413 patch->sinks[i].ext.device.address));
Eric Laurent054d9d32015-04-24 08:48:48 -07004414 }
4415
François Gaffie0c280aa2018-07-25 10:02:15 +02004416 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004417#ifdef ADD_BATTERY_DATA
4418 // when changing the audio output device, call addBatteryData to notify
4419 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004420 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004421 uint32_t params = 0;
4422 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004423 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004424 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004425 }
4426
Eric Laurent054d9d32015-04-24 08:48:48 -07004427 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004428 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004429 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4430 }
4431
4432 if (params != 0) {
4433 addBatteryData(params);
4434 }
4435 }
4436#endif
4437
4438 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004439 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004440 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004441
jiabinc52b1ff2019-10-31 17:20:42 -07004442 // mPatch.num_sinks is not set when the thread is created so that
4443 // the first patch creation triggers an ioConfigChanged callback
4444 bool configChanged = (mPatch.num_sinks == 0) ||
4445 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004446 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004447 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004448 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004449
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004450 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004451 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4452 status = hwDevice->createAudioPatch(patch->num_sources,
4453 patch->sources,
4454 patch->num_sinks,
4455 patch->sinks,
4456 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004457 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004458 char *address;
4459 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
4460 //FIXME: we only support address on first sink with HAL version < 3.0
4461 address = audio_device_address_to_parameter(
4462 patch->sinks[0].ext.device.type,
4463 patch->sinks[0].ext.device.address);
4464 } else {
4465 address = (char *)calloc(1, 1);
4466 }
4467 AudioParameter param = AudioParameter(String8(address));
4468 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07004469 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004470 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07004471 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004472 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004473 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004474
4475 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004476 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004477 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004478 // also dispatch to active AudioTracks for MediaMetrics
4479 for (const auto &track : mActiveTracks) {
4480 track->logEndInterval();
4481 track->logBeginInterval(patchSinksAsString);
4482 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004483
Eric Laurente8726fe2015-06-26 09:39:24 -07004484 if (configChanged) {
4485 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4486 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004487 return status;
4488}
4489
Eric Laurent054d9d32015-04-24 08:48:48 -07004490status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4491{
Andy Hungf60abce2016-08-26 11:37:54 -07004492 status_t status;
4493 if (property_get_bool("af.patch_park", false /* default_value */)) {
4494 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4495 // or if HAL does not properly lock against access.
4496 AutoPark<FastMixer> park(mFastMixer);
4497 status = PlaybackThread::releaseAudioPatch_l(handle);
4498 } else {
4499 status = PlaybackThread::releaseAudioPatch_l(handle);
4500 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004501 return status;
4502}
4503
Eric Laurent1c333e22014-05-20 10:48:17 -07004504status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4505{
4506 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004507
jiabinc52b1ff2019-10-31 17:20:42 -07004508 mPatch = audio_patch{};
4509 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004510
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004511 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004512 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4513 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004514 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004515 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07004516 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004517 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07004518 }
4519 return status;
4520}
4521
Eric Laurent83b88082014-06-20 18:31:16 -07004522void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
4523{
4524 Mutex::Autolock _l(mLock);
4525 mTracks.add(track);
4526}
4527
4528void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
4529{
4530 Mutex::Autolock _l(mLock);
4531 destroyTrack_l(track);
4532}
4533
Mikhail Naganovdc769682018-05-04 15:34:08 -07004534void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07004535{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004536 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004537 config->role = AUDIO_PORT_ROLE_SOURCE;
4538 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4539 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004540 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4541 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4542 config->flags.output = mOutput->flags;
4543 }
Eric Laurent83b88082014-06-20 18:31:16 -07004544}
4545
Eric Laurent81784c32012-11-19 14:55:58 -08004546// ----------------------------------------------------------------------------
4547
4548AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02004549 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
4550 : PlaybackThread(audioFlinger, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08004551 // mAudioMixer below
4552 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004553 mFastMixerFutex(0),
4554 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004555 // mOutputSink below
4556 // mPipeSink below
4557 // mNormalSink below
4558{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004559 setMasterBalance(audioFlinger->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004560 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004561 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004562 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004563 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4564 mNormalFrameCount);
4565 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4566
Andy Hungfbfc3952015-01-15 13:33:51 -08004567 if (type == DUPLICATING) {
4568 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4569 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4570 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4571 return;
4572 }
Eric Laurent81784c32012-11-19 14:55:58 -08004573 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004574 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004575 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004576 const NBAIO_Format offers[1] = {Format_from_SR_C(
4577 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004578#if !LOG_NDEBUG
4579 ssize_t index =
4580#else
4581 (void)
4582#endif
4583 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004584 ALOG_ASSERT(index == 0);
4585
4586 // initialize fast mixer depending on configuration
4587 bool initFastMixer;
4588 switch (kUseFastMixer) {
4589 case FastMixer_Never:
4590 initFastMixer = false;
4591 break;
4592 case FastMixer_Always:
4593 initFastMixer = true;
4594 break;
4595 case FastMixer_Static:
4596 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08004597 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
4598 // where the period is less than an experimentally determined threshold that can be
4599 // scheduled reliably with CFS. However, the BT A2DP HAL is
4600 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
4601 initFastMixer = mFrameCount < mNormalFrameCount
jiabinc52b1ff2019-10-31 17:20:42 -07004602 && Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty();
Eric Laurent81784c32012-11-19 14:55:58 -08004603 break;
4604 }
Andy Hungfda69402017-02-15 14:33:12 -08004605 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4606 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4607 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004608 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004609 audio_format_t fastMixerFormat;
4610 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4611 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4612 } else {
4613 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4614 }
4615 if (mFormat != fastMixerFormat) {
4616 // change our Sink format to accept our intermediate precision
4617 mFormat = fastMixerFormat;
4618 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004619 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004620 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4621 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4622 }
Eric Laurent81784c32012-11-19 14:55:58 -08004623
4624 // create a MonoPipe to connect our submix to FastMixer
4625 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004626
Andy Hung1258c1a2014-05-23 21:22:17 -07004627 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004628 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004629 format.mFormat = fastMixerFormat;
4630 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4631
Eric Laurent81784c32012-11-19 14:55:58 -08004632 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4633 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4634 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4635 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4636 const NBAIO_Format offers[1] = {format};
4637 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004638#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004639 ssize_t index =
4640#else
4641 (void)
4642#endif
4643 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004644 ALOG_ASSERT(index == 0);
4645 monoPipe->setAvgFrames((mScreenState & 1) ?
4646 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4647 mPipeSink = monoPipe;
4648
Eric Laurent81784c32012-11-19 14:55:58 -08004649 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004650 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004651 FastMixerStateQueue *sq = mFastMixer->sq();
4652#ifdef STATE_QUEUE_DUMP
4653 sq->setObserverDump(&mStateQueueObserverDump);
4654 sq->setMutatorDump(&mStateQueueMutatorDump);
4655#endif
4656 FastMixerState *state = sq->begin();
4657 FastTrack *fastTrack = &state->mFastTracks[0];
4658 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4659 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4660 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07004661 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
4662 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
4663 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004664 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004665 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07004666 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01004667 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08004668 fastTrack->mGeneration++;
4669 state->mFastTracksGen++;
4670 state->mTrackMask = 1;
4671 // fast mixer will use the HAL output sink
4672 state->mOutputSink = mOutputSink.get();
4673 state->mOutputSinkGen++;
4674 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004675 // specify sink channel mask when haptic channel mask present as it can not
4676 // be calculated directly from channel count
4677 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07004678 ? AUDIO_CHANNEL_NONE
4679 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08004680 state->mCommand = FastMixerState::COLD_IDLE;
4681 // already done in constructor initialization list
4682 //mFastMixerFutex = 0;
4683 state->mColdFutexAddr = &mFastMixerFutex;
4684 state->mColdGen++;
4685 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004686 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4687 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004688 sq->end();
4689 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4690
Eric Tan0513b5d2018-09-17 10:32:48 -07004691 NBLog::thread_info_t info;
4692 info.id = mId;
4693 info.type = NBLog::FASTMIXER;
4694 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4695
Eric Laurent81784c32012-11-19 14:55:58 -08004696 // start the fast mixer
4697 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4698 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004699 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004700 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004701
4702#ifdef AUDIO_WATCHDOG
4703 // create and start the watchdog
4704 mAudioWatchdog = new AudioWatchdog();
4705 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4706 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4707 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004708 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004709#endif
Andy Hung8946a282018-04-19 20:04:56 -07004710 } else {
4711#ifdef TEE_SINK
4712 // Only use the MixerThread tee if there is no FastMixer.
4713 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4714 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4715#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004716 }
4717
4718 switch (kUseFastMixer) {
4719 case FastMixer_Never:
4720 case FastMixer_Dynamic:
4721 mNormalSink = mOutputSink;
4722 break;
4723 case FastMixer_Always:
4724 mNormalSink = mPipeSink;
4725 break;
4726 case FastMixer_Static:
4727 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4728 break;
4729 }
4730}
4731
4732AudioFlinger::MixerThread::~MixerThread()
4733{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004734 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004735 FastMixerStateQueue *sq = mFastMixer->sq();
4736 FastMixerState *state = sq->begin();
4737 if (state->mCommand == FastMixerState::COLD_IDLE) {
4738 int32_t old = android_atomic_inc(&mFastMixerFutex);
4739 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004740 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004741 }
4742 }
4743 state->mCommand = FastMixerState::EXIT;
4744 sq->end();
4745 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4746 mFastMixer->join();
4747 // Though the fast mixer thread has exited, it's state queue is still valid.
4748 // We'll use that extract the final state which contains one remaining fast track
4749 // corresponding to our sub-mix.
4750 state = sq->begin();
4751 ALOG_ASSERT(state->mTrackMask == 1);
4752 FastTrack *fastTrack = &state->mFastTracks[0];
4753 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4754 delete fastTrack->mBufferProvider;
4755 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004756 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004757#ifdef AUDIO_WATCHDOG
4758 if (mAudioWatchdog != 0) {
4759 mAudioWatchdog->requestExit();
4760 mAudioWatchdog->requestExitAndWait();
4761 mAudioWatchdog.clear();
4762 }
4763#endif
4764 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004765 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004766 delete mAudioMixer;
4767}
4768
4769
4770uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4771{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004772 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004773 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4774 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4775 }
4776 return latency;
4777}
4778
Eric Laurentbfb1b832013-01-07 09:53:42 -08004779ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004780{
4781 // FIXME we should only do one push per cycle; confirm this is true
4782 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004783 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004784 FastMixerStateQueue *sq = mFastMixer->sq();
4785 FastMixerState *state = sq->begin();
4786 if (state->mCommand != FastMixerState::MIX_WRITE &&
4787 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4788 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004789
4790 // FIXME workaround for first HAL write being CPU bound on some devices
4791 ATRACE_BEGIN("write");
4792 mOutput->write((char *)mSinkBuffer, 0);
4793 ATRACE_END();
4794
Eric Laurent81784c32012-11-19 14:55:58 -08004795 int32_t old = android_atomic_inc(&mFastMixerFutex);
4796 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004797 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004798 }
4799#ifdef AUDIO_WATCHDOG
4800 if (mAudioWatchdog != 0) {
4801 mAudioWatchdog->resume();
4802 }
4803#endif
4804 }
4805 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004806#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004807 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004808 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004809#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004810 sq->end();
4811 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4812 if (kUseFastMixer == FastMixer_Dynamic) {
4813 mNormalSink = mPipeSink;
4814 }
4815 } else {
4816 sq->end(false /*didModify*/);
4817 }
4818 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004819 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004820}
4821
4822void AudioFlinger::MixerThread::threadLoop_standby()
4823{
4824 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004825 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004826 FastMixerStateQueue *sq = mFastMixer->sq();
4827 FastMixerState *state = sq->begin();
4828 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004829 // Report any frames trapped in the Monopipe
4830 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4831 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4832 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4833 "monoPipeWritten:%lld monoPipeLeft:%lld",
4834 (long long)mFramesWritten, (long long)mSuspendedFrames,
4835 (long long)mPipeSink->framesWritten(), pipeFrames);
4836 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4837
Eric Laurent81784c32012-11-19 14:55:58 -08004838 state->mCommand = FastMixerState::COLD_IDLE;
4839 state->mColdFutexAddr = &mFastMixerFutex;
4840 state->mColdGen++;
4841 mFastMixerFutex = 0;
4842 sq->end();
4843 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4844 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4845 if (kUseFastMixer == FastMixer_Dynamic) {
4846 mNormalSink = mOutputSink;
4847 }
4848#ifdef AUDIO_WATCHDOG
4849 if (mAudioWatchdog != 0) {
4850 mAudioWatchdog->pause();
4851 }
4852#endif
4853 } else {
4854 sq->end(false /*didModify*/);
4855 }
4856 }
4857 PlaybackThread::threadLoop_standby();
4858}
4859
Eric Laurentbfb1b832013-01-07 09:53:42 -08004860bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4861{
4862 return false;
4863}
4864
4865bool AudioFlinger::PlaybackThread::shouldStandby_l()
4866{
4867 return !mStandby;
4868}
4869
4870bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4871{
4872 Mutex::Autolock _l(mLock);
4873 return waitingAsyncCallback_l();
4874}
4875
Eric Laurent81784c32012-11-19 14:55:58 -08004876// shared by MIXER and DIRECT, overridden by DUPLICATING
4877void AudioFlinger::PlaybackThread::threadLoop_standby()
4878{
4879 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004880 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004881 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004882 // discard any pending drain or write ack by incrementing sequence
4883 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4884 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004885 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004886 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4887 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004888 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004889 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004890}
4891
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004892void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4893{
4894 ALOGV("signal playback thread");
4895 broadcast_l();
4896}
4897
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004898void AudioFlinger::PlaybackThread::onAsyncError()
4899{
4900 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4901 invalidateTracks((audio_stream_type_t)i);
4902 }
4903}
4904
Eric Laurent81784c32012-11-19 14:55:58 -08004905void AudioFlinger::MixerThread::threadLoop_mix()
4906{
Eric Laurent81784c32012-11-19 14:55:58 -08004907 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004908 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004909 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004910 // increase sleep time progressively when application underrun condition clears.
4911 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4912 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4913 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004914 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004915 sleepTimeShift--;
4916 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004917 mSleepTimeUs = 0;
4918 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004919 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004920
Eric Laurent81784c32012-11-19 14:55:58 -08004921}
4922
4923void AudioFlinger::MixerThread::threadLoop_sleepTime()
4924{
4925 // If no tracks are ready, sleep once for the duration of an output
4926 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004927 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004928 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004929 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4930 // Using the Monopipe availableToWrite, we estimate the
4931 // sleep time to retry for more data (before we underrun).
4932 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4933 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4934 const size_t pipeFrames = monoPipe->maxFrames();
4935 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4936 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4937 const size_t framesDelay = std::min(
4938 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4939 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4940 pipeFrames, framesLeft, framesDelay);
4941 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4942 } else {
4943 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4944 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4945 mSleepTimeUs = kMinThreadSleepTimeUs;
4946 }
4947 // reduce sleep time in case of consecutive application underruns to avoid
4948 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4949 // duration we would end up writing less data than needed by the audio HAL if
4950 // the condition persists.
4951 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4952 sleepTimeShift++;
4953 }
Eric Laurent81784c32012-11-19 14:55:58 -08004954 }
4955 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004956 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004957 }
4958 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004959 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4960 // before effects processing or output.
4961 if (mMixerBufferValid) {
4962 memset(mMixerBuffer, 0, mMixerBufferSize);
4963 } else {
4964 memset(mSinkBuffer, 0, mSinkBufferSize);
4965 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004966 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004967 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4968 "anticipated start");
4969 }
4970 // TODO add standby time extension fct of effect tail
4971}
4972
4973// prepareTracks_l() must be called with ThreadBase::mLock held
4974AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4975 Vector< sp<Track> > *tracksToRemove)
4976{
Andy Hungc0691382018-09-12 18:01:57 -07004977 // clean up deleted track ids in AudioMixer before allocating new tracks
4978 (void)mTracks.processDeletedTrackIds([this](int trackId) {
4979 // for each trackId, destroy it in the AudioMixer
4980 if (mAudioMixer->exists(trackId)) {
4981 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004982 }
4983 });
Andy Hungc0691382018-09-12 18:01:57 -07004984 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08004985
4986 mixer_state mixerStatus = MIXER_IDLE;
4987 // find out which tracks need to be processed
4988 size_t count = mActiveTracks.size();
4989 size_t mixedTracks = 0;
4990 size_t tracksWithEffect = 0;
4991 // counts only _active_ fast tracks
4992 size_t fastTracks = 0;
4993 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4994
4995 float masterVolume = mMasterVolume;
4996 bool masterMute = mMasterMute;
4997
4998 if (masterMute) {
4999 masterVolume = 0;
5000 }
5001 // Delegate master volume control to effect in output mix effect chain if needed
5002 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
5003 if (chain != 0) {
5004 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
5005 chain->setVolume_l(&v, &v);
5006 masterVolume = (float)((v + (1 << 23)) >> 24);
5007 chain.clear();
5008 }
5009
5010 // prepare a new state to push
5011 FastMixerStateQueue *sq = NULL;
5012 FastMixerState *state = NULL;
5013 bool didModify = false;
5014 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005015 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005016 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005017 sq = mFastMixer->sq();
5018 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005019 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005020 }
5021
Andy Hung69aed5f2014-02-25 17:24:40 -08005022 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005023 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005024
Andy Hungbd3b2b02018-05-21 10:53:11 -07005025 // DeferredOperations handles statistics after setting mixerStatus.
5026 class DeferredOperations {
5027 public:
Andy Hungea840382020-05-05 21:50:17 -07005028 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5029 : mMixerStatus(mixerStatus)
5030 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005031
5032 // when leaving scope, tally frames properly.
5033 ~DeferredOperations() {
5034 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5035 // because that is when the underrun occurs.
5036 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005037 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005038 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005039 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005040 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005041 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005042 }
5043 }
Andy Hungea840382020-05-05 21:50:17 -07005044 // send the max underrun frames for this mixer period
5045 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005046 }
5047
5048 // tallyUnderrunFrames() is called to update the track counters
5049 // with the number of underrun frames for a particular mixer period.
5050 // We defer tallying until we know the final mixer status.
5051 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
5052 mUnderrunFrames.emplace_back(track, underrunFrames);
5053 }
5054
5055 private:
5056 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005057 ThreadMetrics * const mThreadMetrics;
Andy Hungbd3b2b02018-05-21 10:53:11 -07005058 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005059 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005060 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005061
jiabin245cdd92018-12-07 17:55:15 -08005062 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005063 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07005064 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005065
5066 // this const just means the local variable doesn't change
5067 Track* const track = t.get();
5068
5069 // process fast tracks
5070 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005071 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5072 "%s(%d): FastTrack(%d) present without FastMixer",
5073 __func__, id(), track->id());
5074
jiabin245cdd92018-12-07 17:55:15 -08005075 if (track->getHapticPlaybackEnabled()) {
5076 noFastHapticTrack = false;
5077 }
Eric Laurent81784c32012-11-19 14:55:58 -08005078
5079 // It's theoretically possible (though unlikely) for a fast track to be created
5080 // and then removed within the same normal mix cycle. This is not a problem, as
5081 // the track never becomes active so it's fast mixer slot is never touched.
5082 // The converse, of removing an (active) track and then creating a new track
5083 // at the identical fast mixer slot within the same normal mix cycle,
5084 // is impossible because the slot isn't marked available until the end of each cycle.
5085 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005086 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005087 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5088 FastTrack *fastTrack = &state->mFastTracks[j];
5089
5090 // Determine whether the track is currently in underrun condition,
5091 // and whether it had a recent underrun.
5092 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5093 FastTrackUnderruns underruns = ftDump->mUnderruns;
5094 uint32_t recentFull = (underruns.mBitFields.mFull -
5095 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
5096 uint32_t recentPartial = (underruns.mBitFields.mPartial -
5097 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
5098 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
5099 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
5100 uint32_t recentUnderruns = recentPartial + recentEmpty;
5101 track->mObservedUnderruns = underruns;
5102 // don't count underruns that occur while stopping or pausing
5103 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005104 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005105 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5106 recentUnderruns > 0) {
5107 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005108 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005109 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005110 // Immediately account for FastTrack underruns.
5111 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005112
5113 // This is similar to the state machine for normal tracks,
5114 // with a few modifications for fast tracks.
5115 bool isActive = true;
5116 switch (track->mState) {
5117 case TrackBase::STOPPING_1:
5118 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005119 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005120 track->mState = TrackBase::STOPPING_2;
5121 }
5122 break;
5123 case TrackBase::PAUSING:
5124 // ramp down is not yet implemented
5125 track->setPaused();
5126 break;
5127 case TrackBase::RESUMING:
5128 // ramp up is not yet implemented
5129 track->mState = TrackBase::ACTIVE;
5130 break;
5131 case TrackBase::ACTIVE:
5132 if (recentFull > 0 || recentPartial > 0) {
5133 // track has provided at least some frames recently: reset retry count
5134 track->mRetryCount = kMaxTrackRetries;
5135 }
5136 if (recentUnderruns == 0) {
5137 // no recent underruns: stay active
5138 break;
5139 }
5140 // there has recently been an underrun of some kind
5141 if (track->sharedBuffer() == 0) {
5142 // were any of the recent underruns "empty" (no frames available)?
5143 if (recentEmpty == 0) {
5144 // no, then ignore the partial underruns as they are allowed indefinitely
5145 break;
5146 }
5147 // there has recently been an "empty" underrun: decrement the retry counter
5148 if (--(track->mRetryCount) > 0) {
5149 break;
5150 }
5151 // indicate to client process that the track was disabled because of underrun;
5152 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005153 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005154 // remove from active list, but state remains ACTIVE [confusing but true]
5155 isActive = false;
5156 break;
5157 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005158 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08005159 case TrackBase::STOPPING_2:
5160 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08005161 case TrackBase::STOPPED:
5162 case TrackBase::FLUSHED: // flush() while active
5163 // Check for presentation complete if track is inactive
5164 // We have consumed all the buffers of this track.
5165 // This would be incomplete if we auto-paused on underrun
5166 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005167 uint32_t latency = 0;
5168 status_t result = mOutput->stream->getLatency(&latency);
5169 ALOGE_IF(result != OK,
5170 "Error when retrieving output stream latency: %d", result);
5171 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005172 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005173 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5174 // track stays in active list until presentation is complete
5175 break;
5176 }
5177 }
5178 if (track->isStopping_2()) {
5179 track->mState = TrackBase::STOPPED;
5180 }
5181 if (track->isStopped()) {
5182 // Can't reset directly, as fast mixer is still polling this track
5183 // track->reset();
5184 // So instead mark this track as needing to be reset after push with ack
5185 resetMask |= 1 << i;
5186 }
5187 isActive = false;
5188 break;
5189 case TrackBase::IDLE:
5190 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08005191 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005192 }
5193
5194 if (isActive) {
5195 // was it previously inactive?
5196 if (!(state->mTrackMask & (1 << j))) {
5197 ExtendedAudioBufferProvider *eabp = track;
5198 VolumeProvider *vp = track;
5199 fastTrack->mBufferProvider = eabp;
5200 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08005201 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07005202 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08005203 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005204 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005205 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005206 fastTrack->mGeneration++;
5207 state->mTrackMask |= 1 << j;
5208 didModify = true;
5209 // no acknowledgement required for newly active tracks
5210 }
Kevin Rocard12381092018-04-11 09:19:59 -07005211 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurenteab90452019-06-24 15:17:46 -07005212 float volume;
5213 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5214 volume = 0.f;
5215 } else {
5216 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5217 }
5218
5219 handleVoipVolume_l(&volume);
5220
Eric Laurent81784c32012-11-19 14:55:58 -08005221 // cache the combined master volume and stream type volume for fast mixer; this
5222 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005223 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005224 proxy->framesReleased()).first;
5225 volume *= vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07005226 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005227 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5228 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
5229 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07005230
Kevin Rocard12381092018-04-11 09:19:59 -07005231 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08005232 ++fastTracks;
5233 } else {
5234 // was it previously active?
5235 if (state->mTrackMask & (1 << j)) {
5236 fastTrack->mBufferProvider = NULL;
5237 fastTrack->mGeneration++;
5238 state->mTrackMask &= ~(1 << j);
5239 didModify = true;
5240 // If any fast tracks were removed, we must wait for acknowledgement
5241 // because we're about to decrement the last sp<> on those tracks.
5242 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5243 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005244 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5245 // AudioTrack may start (which may not be with a start() but with a write()
5246 // after underrun) and immediately paused or released. In that case the
5247 // FastTrack state hasn't had time to update.
5248 // TODO Remove the ALOGW when this theory is confirmed.
5249 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005250 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
5251 j, track->mState, state->mTrackMask, recentUnderruns,
5252 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005253 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005254 }
5255 tracksToRemove->add(track);
5256 // Avoids a misleading display in dumpsys
5257 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
5258 }
jiabin245cdd92018-12-07 17:55:15 -08005259 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5260 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5261 didModify = true;
5262 }
Eric Laurent81784c32012-11-19 14:55:58 -08005263 continue;
5264 }
5265
5266 { // local variable scope to avoid goto warning
5267
5268 audio_track_cblk_t* cblk = track->cblk();
5269
5270 // The first time a track is added we wait
5271 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005272 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005273
5274 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005275 // use the trackId as the AudioMixer name.
5276 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005277 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005278 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005279 track->mChannelMask,
5280 track->mFormat,
5281 track->mSessionId);
5282 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005283 ALOGW("%s(): AudioMixer cannot create track(%d)"
5284 " mask %#x, format %#x, sessionId %d",
5285 __func__, trackId,
5286 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005287 tracksToRemove->add(track);
5288 track->invalidate(); // consider it dead.
5289 continue;
5290 }
5291 }
5292
Eric Laurent81784c32012-11-19 14:55:58 -08005293 // make sure that we have enough frames to mix one full buffer.
5294 // enforce this condition only once to enable draining the buffer in case the client
5295 // app does not call stop() and relies on underrun to stop:
5296 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5297 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005298 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07005299 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005300 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005301
5302 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005303 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005304 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5305 // add frames already consumed but not yet released by the resampler
5306 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005307 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005308
Eric Laurent81784c32012-11-19 14:55:58 -08005309 uint32_t minFrames = 1;
5310 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5311 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005312 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005313 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005314
5315 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005316 if (ATRACE_ENABLED()) {
5317 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005318 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005319 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005320 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005321 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005322 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005323 !track->isPaused() && !track->isTerminated())
5324 {
Andy Hungc0691382018-09-12 18:01:57 -07005325 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005326
5327 mixedTracks++;
5328
Andy Hung69aed5f2014-02-25 17:24:40 -08005329 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5330 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005331 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005332 if (track->mainBuffer() != mSinkBuffer &&
5333 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005334 if (mEffectBufferEnabled) {
5335 mEffectBufferValid = true; // Later can set directly.
5336 }
Eric Laurent81784c32012-11-19 14:55:58 -08005337 chain = getEffectChain_l(track->sessionId());
5338 // Delegate volume control to effect in track effect chain if needed
5339 if (chain != 0) {
5340 tracksWithEffect++;
5341 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005342 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005343 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005344 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005345 }
5346 }
5347
5348
5349 int param = AudioMixer::VOLUME;
5350 if (track->mFillingUpStatus == Track::FS_FILLED) {
5351 // no ramp for the first volume setting
5352 track->mFillingUpStatus = Track::FS_ACTIVE;
5353 if (track->mState == TrackBase::RESUMING) {
5354 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005355 // If a new track is paused immediately after start, do not ramp on resume.
5356 if (cblk->mServer != 0) {
5357 param = AudioMixer::RAMP_VOLUME;
5358 }
Eric Laurent81784c32012-11-19 14:55:58 -08005359 }
Andy Hungc0691382018-09-12 18:01:57 -07005360 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005361 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005362 // FIXME should not make a decision based on mServer
5363 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005364 // If the track is stopped before the first frame was mixed,
5365 // do not apply ramp
5366 param = AudioMixer::RAMP_VOLUME;
5367 }
5368
5369 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005370 uint32_t vl, vr; // in U8.24 integer format
5371 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005372 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005373 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005374 // Always fetch volumeshaper volume to ensure state is updated.
5375 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5376 const float vh = track->getVolumeHandler()->getVolume(
5377 track->mAudioTrackServerProxy->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005378
Eric Laurenteab90452019-06-24 15:17:46 -07005379 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5380 v = 0;
5381 }
5382
5383 handleVoipVolume_l(&v);
5384
5385 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005386 vl = vr = 0;
5387 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005388 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005389 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005390 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005391 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5392 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005393 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005394 if (vlf > GAIN_FLOAT_UNITY) {
5395 ALOGV("Track left volume out of range: %.3g", vlf);
5396 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005397 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005398 if (vrf > GAIN_FLOAT_UNITY) {
5399 ALOGV("Track right volume out of range: %.3g", vrf);
5400 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005401 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005402 // now apply the master volume and stream type volume and shaper volume
5403 vlf *= v * vh;
5404 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005405 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005406 // then derive vl and vr as U8.24 versions for the effect chain
5407 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5408 vl = (uint32_t) (scaleto8_24 * vlf);
5409 vr = (uint32_t) (scaleto8_24 * vrf);
5410 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005411 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005412 // send level comes from shared memory and so may be corrupt
5413 if (sendLevel > MAX_GAIN_INT) {
5414 ALOGV("Track send level out of range: %04X", sendLevel);
5415 sendLevel = MAX_GAIN_INT;
5416 }
Andy Hung6be49402014-05-30 10:42:03 -07005417 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5418 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005419 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005420
Kevin Rocard12381092018-04-11 09:19:59 -07005421 track->setFinalVolume((vrf + vlf) / 2.f);
5422
Eric Laurent81784c32012-11-19 14:55:58 -08005423 // Delegate volume control to effect in track effect chain if needed
5424 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5425 // Do not ramp volume if volume is controlled by effect
5426 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005427 // Update remaining floating point volume levels
5428 vlf = (float)vl / (1 << 24);
5429 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08005430 track->mHasVolumeController = true;
5431 } else {
5432 // force no volume ramp when volume controller was just disabled or removed
5433 // from effect chain to avoid volume spike
5434 if (track->mHasVolumeController) {
5435 param = AudioMixer::VOLUME;
5436 }
5437 track->mHasVolumeController = false;
5438 }
5439
Eric Laurent81784c32012-11-19 14:55:58 -08005440 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07005441 mAudioMixer->setBufferProvider(trackId, track);
5442 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005443
Andy Hungc0691382018-09-12 18:01:57 -07005444 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5445 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5446 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005447 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005448 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005449 AudioMixer::TRACK,
5450 AudioMixer::FORMAT, (void *)track->format());
5451 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005452 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005453 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005454 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07005455 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005456 trackId,
Andy Hung9a592762014-07-21 21:56:01 -07005457 AudioMixer::TRACK,
jiabin245cdd92018-12-07 17:55:15 -08005458 AudioMixer::MIXER_CHANNEL_MASK,
Eric Laurentf1f22e72021-07-13 14:04:14 +02005459 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
Glenn Kastene3aa6592012-12-04 12:22:46 -08005460 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005461 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005462 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005463 if (reqSampleRate == 0) {
5464 reqSampleRate = mSampleRate;
5465 } else if (reqSampleRate > maxSampleRate) {
5466 reqSampleRate = maxSampleRate;
5467 }
Eric Laurent81784c32012-11-19 14:55:58 -08005468 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005469 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005470 AudioMixer::RESAMPLE,
5471 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005472 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005473
Andy Hung333ab962019-05-28 20:23:35 -07005474 AudioPlaybackRate playbackRate = proxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005475 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005476 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005477 AudioMixer::TIMESTRETCH,
5478 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005479 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005480
Andy Hung69aed5f2014-02-25 17:24:40 -08005481 /*
5482 * Select the appropriate output buffer for the track.
5483 *
Andy Hung98ef9782014-03-04 14:46:50 -08005484 * Tracks with effects go into their own effects chain buffer
5485 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005486 *
5487 * Other tracks can use mMixerBuffer for higher precision
5488 * channel accumulation. If this buffer is enabled
5489 * (mMixerBufferEnabled true), then selected tracks will accumulate
5490 * into it.
5491 *
5492 */
5493 if (mMixerBufferEnabled
5494 && (track->mainBuffer() == mSinkBuffer
5495 || track->mainBuffer() == mMixerBuffer)) {
5496 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005497 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005498 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08005499 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08005500 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005501 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005502 AudioMixer::TRACK,
5503 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5504 // TODO: override track->mainBuffer()?
5505 mMixerBufferValid = true;
5506 } else {
5507 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005508 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005509 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07005510 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005511 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005512 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005513 AudioMixer::TRACK,
5514 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5515 }
Eric Laurent81784c32012-11-19 14:55:58 -08005516 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005517 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005518 AudioMixer::TRACK,
5519 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005520 mAudioMixer->setParameter(
5521 trackId,
5522 AudioMixer::TRACK,
5523 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005524 mAudioMixer->setParameter(
5525 trackId,
5526 AudioMixer::TRACK,
5527 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Lais Andradebc3f37a2021-07-02 00:13:19 +01005528 mAudioMixer->setParameter(
5529 trackId,
5530 AudioMixer::TRACK,
5531 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)(&(track->mHapticMaxAmplitude)));
Eric Laurent81784c32012-11-19 14:55:58 -08005532
5533 // reset retry count
5534 track->mRetryCount = kMaxTrackRetries;
5535
5536 // If one track is ready, set the mixer ready if:
5537 // - the mixer was not ready during previous round OR
5538 // - no other track is not ready
5539 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5540 mixerStatus != MIXER_TRACKS_ENABLED) {
5541 mixerStatus = MIXER_TRACKS_READY;
5542 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005543
5544 // Enable the next few lines to instrument a test for underrun log handling.
5545 // TODO: Remove when we have a better way of testing the underrun log.
5546#if 0
5547 static int i;
5548 if ((++i & 0xf) == 0) {
5549 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5550 }
5551#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005552 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005553 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005554 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005555 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5556 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005557 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005558 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005559 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005560
Eric Laurent81784c32012-11-19 14:55:58 -08005561 // clear effect chain input buffer if an active track underruns to avoid sending
5562 // previous audio buffer again to effects
5563 chain = getEffectChain_l(track->sessionId());
5564 if (chain != 0) {
5565 chain->clearInputBuffer();
5566 }
5567
Andy Hungc0691382018-09-12 18:01:57 -07005568 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005569 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5570 track->isStopped() || track->isPaused()) {
5571 // We have consumed all the buffers of this track.
5572 // Remove it from the list of active tracks.
5573 // TODO: use actual buffer filling status instead of latency when available from
5574 // audio HAL
5575 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005576 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005577 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5578 if (track->isStopped()) {
5579 track->reset();
5580 }
5581 tracksToRemove->add(track);
5582 }
5583 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005584 // No buffers for this track. Give it a few chances to
5585 // fill a buffer, then remove it from active list.
5586 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005587 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5588 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005589 tracksToRemove->add(track);
5590 // indicate to client process that the track was disabled because of underrun;
5591 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005592 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005593 // If one track is not ready, mark the mixer also not ready if:
5594 // - the mixer was ready during previous round OR
5595 // - no other track is ready
5596 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5597 mixerStatus != MIXER_TRACKS_READY) {
5598 mixerStatus = MIXER_TRACKS_ENABLED;
5599 }
5600 }
Andy Hungc0691382018-09-12 18:01:57 -07005601 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005602 }
5603
5604 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005605
5606 }
5607
jiabin245cdd92018-12-07 17:55:15 -08005608 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5609 // When there is no fast track playing haptic and FastMixer exists,
5610 // enabling the first FastTrack, which provides mixed data from normal
5611 // tracks, to play haptic data.
5612 FastTrack *fastTrack = &state->mFastTracks[0];
5613 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5614 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5615 didModify = true;
5616 }
5617 }
5618
Eric Laurent81784c32012-11-19 14:55:58 -08005619 // Push the new FastMixer state if necessary
5620 bool pauseAudioWatchdog = false;
5621 if (didModify) {
5622 state->mFastTracksGen++;
5623 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5624 if (kUseFastMixer == FastMixer_Dynamic &&
5625 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5626 state->mCommand = FastMixerState::COLD_IDLE;
5627 state->mColdFutexAddr = &mFastMixerFutex;
5628 state->mColdGen++;
5629 mFastMixerFutex = 0;
5630 if (kUseFastMixer == FastMixer_Dynamic) {
5631 mNormalSink = mOutputSink;
5632 }
5633 // If we go into cold idle, need to wait for acknowledgement
5634 // so that fast mixer stops doing I/O.
5635 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5636 pauseAudioWatchdog = true;
5637 }
Eric Laurent81784c32012-11-19 14:55:58 -08005638 }
5639 if (sq != NULL) {
5640 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005641 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5642 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5643 // when bringing the output sink into standby.)
5644 //
5645 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5646 //
5647 // This occurs with BT suspend when we idle the FastMixer with
5648 // active tracks, which may be added or removed.
5649 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005650 }
5651#ifdef AUDIO_WATCHDOG
5652 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5653 mAudioWatchdog->pause();
5654 }
5655#endif
5656
5657 // Now perform the deferred reset on fast tracks that have stopped
5658 while (resetMask != 0) {
5659 size_t i = __builtin_ctz(resetMask);
5660 ALOG_ASSERT(i < count);
5661 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005662 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005663 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5664 track->reset();
5665 }
5666
Andy Hung80d03d22018-04-10 10:32:11 -07005667 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5668 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5669 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5670 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5671 // See also the implementation of destroyTrack_l().
5672 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005673 const int trackId = track->id();
5674 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5675 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005676 }
5677 }
5678
Eric Laurent81784c32012-11-19 14:55:58 -08005679 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005680 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005681
Eric Laurentb3f315a2021-07-13 15:09:05 +02005682 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
5683 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07005684 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005685 }
5686
5687 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005688 // as long as there are effects we should clear the effects buffer, to avoid
5689 // passing a non-clean buffer to the effect chain
5690 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07005691 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005692 // sink or mix buffer must be cleared if all tracks are connected to an
5693 // effect chain as in this case the mixer will not write to the sink or mix buffer
5694 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08005695 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5696 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005697 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005698 if (mMixerBufferValid) {
5699 memset(mMixerBuffer, 0, mMixerBufferSize);
5700 // TODO: In testing, mSinkBuffer below need not be cleared because
5701 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5702 // after mixing.
5703 //
5704 // To enforce this guarantee:
5705 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5706 // (mixedTracks == 0 && fastTracks > 0))
5707 // must imply MIXER_TRACKS_READY.
5708 // Later, we may clear buffers regardless, and skip much of this logic.
5709 }
Andy Hung98ef9782014-03-04 14:46:50 -08005710 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005711 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005712 }
5713
5714 // if any fast tracks, then status is ready
5715 mMixerStatusIgnoringFastTracks = mixerStatus;
5716 if (fastTracks > 0) {
5717 mixerStatus = MIXER_TRACKS_READY;
5718 }
5719 return mixerStatus;
5720}
5721
Eric Laurentad7dd962016-09-22 12:38:37 -07005722// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005723uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005724{
5725 uint32_t trackCount = 0;
5726 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005727 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005728 trackCount++;
5729 }
5730 }
5731 return trackCount;
5732}
5733
Andy Hung1bc088a2018-02-09 15:57:31 -08005734// isTrackAllowed_l() must be called with ThreadBase::mLock held
5735bool AudioFlinger::MixerThread::isTrackAllowed_l(
5736 audio_channel_mask_t channelMask, audio_format_t format,
5737 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005738{
Andy Hung1bc088a2018-02-09 15:57:31 -08005739 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5740 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005741 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005742 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005743 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005744 ALOGW("%s: invalid format: %#x", __func__, format);
5745 return false;
5746 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005747 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005748 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5749 return false;
5750 }
5751 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005752}
5753
Eric Laurent10351942014-05-08 18:49:52 -07005754// checkForNewParameter_l() must be called with ThreadBase::mLock held
5755bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5756 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005757{
Eric Laurent81784c32012-11-19 14:55:58 -08005758 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07005759 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005760
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005761 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005762
Eric Laurent10351942014-05-08 18:49:52 -07005763 AudioParameter param = AudioParameter(keyValuePair);
5764 int value;
5765 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5766 reconfig = true;
5767 }
5768 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005769 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005770 status = BAD_VALUE;
5771 } else {
5772 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005773 reconfig = true;
5774 }
Eric Laurent10351942014-05-08 18:49:52 -07005775 }
5776 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005777 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005778 status = BAD_VALUE;
5779 } else {
5780 // no need to save value, since it's constant
5781 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005782 }
Eric Laurent10351942014-05-08 18:49:52 -07005783 }
5784 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5785 // do not accept frame count changes if tracks are open as the track buffer
5786 // size depends on frame count and correct behavior would not be guaranteed
5787 // if frame count is changed after track creation
5788 if (!mTracks.isEmpty()) {
5789 status = INVALID_OPERATION;
5790 } else {
5791 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005792 }
Eric Laurent10351942014-05-08 18:49:52 -07005793 }
5794 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07005795 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07005796 }
Eric Laurent81784c32012-11-19 14:55:58 -08005797
Eric Laurent10351942014-05-08 18:49:52 -07005798 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005799 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005800 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005801 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07005802 if (!mStandby) {
5803 mThreadMetrics.logEndInterval();
5804 mStandby = true;
5805 }
Eric Laurent10351942014-05-08 18:49:52 -07005806 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005807 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005808 }
Eric Laurent10351942014-05-08 18:49:52 -07005809 if (status == NO_ERROR && reconfig) {
5810 readOutputParameters_l();
5811 delete mAudioMixer;
5812 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005813 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07005814 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005815 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005816 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005817 track->mChannelMask,
5818 track->mFormat,
5819 track->mSessionId);
5820 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07005821 "%s(): AudioMixer cannot create track(%d)"
5822 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08005823 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07005824 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005825 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005826 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005827 }
Eric Laurent81784c32012-11-19 14:55:58 -08005828 }
5829
Dean Wheatley68918102021-03-19 22:09:19 +11005830 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08005831}
5832
5833
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005834void AudioFlinger::MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08005835{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005836 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005837 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005838 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005839 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005840 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
5841 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
5842 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005843 if (hasFastMixer()) {
5844 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5845
5846 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5847 // while we are dumping it. It may be inconsistent, but it won't mutate!
5848 // This is a large object so we place it on the heap.
5849 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07005850 const std::unique_ptr<FastMixerDumpState> copy =
5851 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005852 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005853
5854#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005855 // Similar for state queue
5856 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5857 observerCopy.dump(fd);
5858 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5859 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005860#endif
5861
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005862#ifdef AUDIO_WATCHDOG
5863 if (mAudioWatchdog != 0) {
5864 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5865 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5866 wdCopy.dump(fd);
5867 }
5868#endif
5869
5870 } else {
5871 dprintf(fd, " No FastMixer\n");
5872 }
Eric Laurent81784c32012-11-19 14:55:58 -08005873}
5874
5875uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5876{
5877 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5878}
5879
5880uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5881{
5882 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5883}
5884
5885void AudioFlinger::MixerThread::cacheParameters_l()
5886{
5887 PlaybackThread::cacheParameters_l();
5888
5889 // FIXME: Relaxed timing because of a certain device that can't meet latency
5890 // Should be reduced to 2x after the vendor fixes the driver issue
5891 // increase threshold again due to low power audio mode. The way this warning
5892 // threshold is calculated and its usefulness should be reconsidered anyway.
5893 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5894}
5895
5896// ----------------------------------------------------------------------------
5897
5898AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07005899 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady)
5900 : PlaybackThread(audioFlinger, output, id, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005901{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005902 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005903}
5904
Eric Laurent81784c32012-11-19 14:55:58 -08005905AudioFlinger::DirectOutputThread::~DirectOutputThread()
5906{
5907}
5908
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005909void AudioFlinger::DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005910{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005911 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005912 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
5913 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
5914}
5915
5916void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
5917{
5918 Mutex::Autolock _l(mLock);
5919 if (mMasterBalance != balance) {
5920 mMasterBalance.store(balance);
5921 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
5922 broadcast_l();
5923 }
5924}
5925
Eric Laurent5850c4c2016-11-10 13:04:31 -08005926void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005927{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005928 float left, right;
5929
Andy Hung333ab962019-05-28 20:23:35 -07005930 // Ensure volumeshaper state always advances even when muted.
5931 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5932 const auto [shaperVolume, shaperActive] = track->getVolumeHandler()->getVolume(
5933 proxy->framesReleased());
5934 mVolumeShaperActive = shaperActive;
5935
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08005936 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005937 left = right = 0;
5938 } else {
5939 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005940 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005941
Glenn Kastenc56f3422014-03-21 17:53:17 -07005942 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5943 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5944 if (left > GAIN_FLOAT_UNITY) {
5945 left = GAIN_FLOAT_UNITY;
5946 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005947 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07005948 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5949 if (right > GAIN_FLOAT_UNITY) {
5950 right = GAIN_FLOAT_UNITY;
5951 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005952 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005953 }
5954
5955 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005956 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005957 if (left != mLeftVolFloat || right != mRightVolFloat) {
5958 mLeftVolFloat = left;
5959 mRightVolFloat = right;
5960
Eric Laurentbfb1b832013-01-07 09:53:42 -08005961 // Delegate volume control to effect in track effect chain if needed
5962 // only one effect chain can be present on DirectOutputThread, so if
5963 // there is one, the track is connected to it
5964 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09005965 // if effect chain exists, volume is handled by it.
5966 // Convert volumes from float to 8.24
5967 uint32_t vl = (uint32_t)(left * (1 << 24));
5968 uint32_t vr = (uint32_t)(right * (1 << 24));
5969 // Direct/Offload effect chains set output volume in setVolume_l().
5970 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
5971 } else {
5972 // otherwise we directly set the volume.
5973 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005974 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005975 }
5976 }
5977}
5978
Phil Burk43b4dcc2015-06-09 16:53:44 -07005979void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5980{
5981 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005982 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005983
Eric Laurent0f0631e2015-07-06 18:01:25 -07005984 if (previousTrack != 0 && latestTrack != 0) {
5985 if (mType == DIRECT) {
5986 if (previousTrack.get() != latestTrack.get()) {
5987 mFlushPending = true;
5988 }
5989 } else /* mType == OFFLOAD */ {
5990 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5991 mFlushPending = true;
5992 }
5993 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08005994 } else if (previousTrack == 0) {
5995 // there could be an old track added back during track transition for direct
5996 // output, so always issues flush to flush data of the previous track if it
5997 // was already destroyed with HAL paused, then flush can resume the playback
5998 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005999 }
6000 PlaybackThread::onAddNewTrack_l();
6001}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006002
Eric Laurent81784c32012-11-19 14:55:58 -08006003AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
6004 Vector< sp<Track> > *tracksToRemove
6005)
6006{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006007 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006008 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006009 bool doHwPause = false;
6010 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006011
6012 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006013 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006014 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006015 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006016 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006017 continue;
6018 }
6019
Eric Laurent5850c4c2016-11-10 13:04:31 -08006020 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006021#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006022 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006023#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006024 // Only consider last track started for volume and mixer state control.
6025 // In theory an older track could underrun and restart after the new one starts
6026 // but as we only care about the transition phase between two tracks on a
6027 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006028 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006029 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006030
Kuowei Li23666472021-01-20 10:23:25 +08006031 if (track->isPausePending()) {
6032 track->pauseAck();
6033 // It is possible a track might have been flushed or stopped.
6034 // Other operations such as flush pending might occur on the next prepare.
6035 if (track->isPausing()) {
6036 track->setPaused();
6037 }
6038 // Always perform pause, as an immediate flush will change
6039 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006040 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006041 doHwPause = true;
6042 mHwPaused = true;
6043 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006044 } else if (track->isFlushPending()) {
6045 track->flushAck();
6046 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006047 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006048 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006049 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006050 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006051 if (last) {
6052 mLeftVolFloat = mRightVolFloat = -1.0;
6053 if (mHwPaused) {
6054 doHwResume = true;
6055 mHwPaused = false;
6056 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006057 }
6058 }
6059
Eric Laurent81784c32012-11-19 14:55:58 -08006060 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006061 // for all its buffers to be filled before processing it.
6062 // Allow draining the buffer in case the client
6063 // app does not call stop() and relies on underrun to stop:
6064 // hence the test on (track->mRetryCount > 1).
Andy Hung455982f2021-04-27 17:46:12 -07006065 // If track->mRetryCount <= 1 then track is about to be disabled, paused, removed,
6066 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6067 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006068 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006069
6070 // target retry count that we will use is based on the time we wait for retries.
6071 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6072 // the retry threshold is when we accept any size for PCM data. This is slightly
6073 // smaller than the retry count so we can push small bits of data without a glitch.
6074 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006075 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006076 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung455982f2021-04-27 17:46:12 -07006077 && (track->mRetryCount > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006078 minFrames = mNormalFrameCount;
6079 } else {
6080 minFrames = 1;
6081 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006082
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006083 const size_t framesReady = track->framesReady();
6084 const int trackId = track->id();
6085 if (ATRACE_ENABLED()) {
6086 std::string traceName("nRdy");
6087 traceName += std::to_string(trackId);
6088 ATRACE_INT(traceName.c_str(), framesReady);
6089 }
6090 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006091 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006092 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006093 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006094
6095 if (track->mFillingUpStatus == Track::FS_FILLED) {
6096 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006097 if (last) {
6098 // make sure processVolume_l() will apply new volume even if 0
6099 mLeftVolFloat = mRightVolFloat = -1.0;
6100 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006101 if (!mHwSupportsPause) {
6102 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006103 }
6104 }
6105
6106 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006107 processVolume_l(track, last);
6108 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006109 sp<Track> previousTrack = mPreviousTrack.promote();
6110 if (previousTrack != 0) {
6111 if (track != previousTrack.get()) {
6112 // Flush any data still being written from last track
6113 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006114 // Invalidate previous track to force a seek when resuming.
6115 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006116 }
6117 }
6118 mPreviousTrack = track;
6119
Eric Laurentd595b7c2013-04-03 17:27:56 -07006120 // reset retry count
Andy Hung455982f2021-04-27 17:46:12 -07006121 track->mRetryCount = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006122 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006123 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006124 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006125 doHwResume = true;
6126 mHwPaused = false;
6127 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006128 }
Eric Laurent81784c32012-11-19 14:55:58 -08006129 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006130 // clear effect chain input buffer if the last active track started underruns
6131 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006132 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006133 mEffectChains[0]->clearInputBuffer();
6134 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006135 if (track->isStopping_1()) {
6136 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07006137 if (last && mHwPaused) {
6138 doHwResume = true;
6139 mHwPaused = false;
6140 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006141 }
6142 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6143 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006144 // We have consumed all the buffers of this track.
6145 // Remove it from the list of active tracks.
Eric Laurentfd477972013-10-25 18:10:40 -07006146 if (mStandby || !last ||
Andy Hung59de4262021-06-14 10:53:54 -07006147 track->presentationComplete(latency_l()) ||
Jindong32dc26e2019-11-11 18:10:01 +08006148 track->isPaused() || mHwPaused) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07006149 if (track->isStopping_2()) {
6150 track->mState = TrackBase::STOPPED;
6151 }
Eric Laurent81784c32012-11-19 14:55:58 -08006152 if (track->isStopped()) {
6153 track->reset();
6154 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006155 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006156 }
6157 } else {
6158 // No buffers for this track. Give it a few chances to
6159 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006160 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08006161 if (--(track->mRetryCount) <= 0) {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006162 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
Eric Laurentd595b7c2013-04-03 17:27:56 -07006163 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08006164 // indicate to client process that the track was disabled because of underrun;
6165 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006166 track->disable();
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006167 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6168 // unlike mixerthread, HAL can be paused for direct output
Phil Burkca5e6142015-07-14 09:42:29 -07006169 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6170 "minFrames = %u, mFormat = %#x",
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006171 framesReady, minFrames, mFormat);
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006172 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006173 doHwPause = true;
6174 mHwPaused = true;
6175 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006176 } else if (last) {
6177 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006178 }
6179 }
6180 }
6181 }
6182
Eric Laurentd1f69b02014-12-15 14:33:13 -08006183 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006184 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006185 for (size_t i = 0; i < mTracks.size(); i++) {
6186 if (mTracks[i]->isFlushPending()) {
6187 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006188 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006189 }
6190 }
6191 }
6192
6193 // make sure the pause/flush/resume sequence is executed in the right order.
6194 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6195 // before flush and then resume HW. This can happen in case of pause/flush/resume
6196 // if resume is received before pause is executed.
6197 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006198 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006199 status_t result = mOutput->stream->pause();
6200 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006201 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006202 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006203 flushHw_l();
6204 }
6205 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006206 status_t result = mOutput->stream->resume();
6207 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006208 }
Eric Laurent81784c32012-11-19 14:55:58 -08006209 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006210 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006211
6212 return mixerStatus;
6213}
6214
6215void AudioFlinger::DirectOutputThread::threadLoop_mix()
6216{
Eric Laurent81784c32012-11-19 14:55:58 -08006217 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006218 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006219 // output audio to hardware
6220 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006221 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006222 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006223 status_t status = mActiveTrack->getNextBuffer(&buffer);
6224 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006225 // no need to pad with 0 for compressed audio
6226 if (audio_has_proportional_frames(mFormat)) {
6227 memset(curBuf, 0, frameCount * mFrameSize);
6228 }
Eric Laurent81784c32012-11-19 14:55:58 -08006229 break;
6230 }
6231 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6232 frameCount -= buffer.frameCount;
6233 curBuf += buffer.frameCount * mFrameSize;
6234 mActiveTrack->releaseBuffer(&buffer);
6235 }
Andy Hung2098f272014-02-27 14:00:06 -08006236 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006237 mSleepTimeUs = 0;
6238 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006239 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006240}
6241
6242void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
6243{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006244 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006245 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006246 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006247 return;
6248 }
Andy Hung85ba3332021-04-27 17:40:26 -07006249 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6250 mSleepTimeUs = mActiveSleepTimeUs;
6251 } else {
6252 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006253 }
Andy Hung85ba3332021-04-27 17:40:26 -07006254 // Note: In S or later, we do not write zeroes for
6255 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006256}
6257
Eric Laurentd1f69b02014-12-15 14:33:13 -08006258void AudioFlinger::DirectOutputThread::threadLoop_exit()
6259{
6260 {
6261 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006262 for (size_t i = 0; i < mTracks.size(); i++) {
6263 if (mTracks[i]->isFlushPending()) {
6264 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006265 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006266 }
6267 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006268 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006269 flushHw_l();
6270 }
6271 }
6272 PlaybackThread::threadLoop_exit();
6273}
6274
6275// must be called with thread mutex locked
6276bool AudioFlinger::DirectOutputThread::shouldStandby_l()
6277{
6278 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006279 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006280
6281 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6282 // after a timeout and we will enter standby then.
6283 if (mTracks.size() > 0) {
6284 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006285 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
6286 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006287 }
6288
Eric Laurent5cff4032015-05-26 13:49:58 -07006289 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006290}
6291
Eric Laurent10351942014-05-08 18:49:52 -07006292// checkForNewParameter_l() must be called with ThreadBase::mLock held
6293bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
6294 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006295{
6296 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006297 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006298
Eric Laurent10351942014-05-08 18:49:52 -07006299 AudioParameter param = AudioParameter(keyValuePair);
6300 int value;
6301 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006302 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006303 }
Eric Laurent10351942014-05-08 18:49:52 -07006304 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6305 // do not accept frame count changes if tracks are open as the track buffer
6306 // size depends on frame count and correct behavior would not be garantied
6307 // if frame count is changed after track creation
6308 if (!mTracks.isEmpty()) {
6309 status = INVALID_OPERATION;
6310 } else {
6311 reconfig = true;
6312 }
6313 }
6314 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006315 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006316 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006317 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006318 if (!mStandby) {
6319 mThreadMetrics.logEndInterval();
6320 mStandby = true;
6321 }
Eric Laurent10351942014-05-08 18:49:52 -07006322 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006323 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006324 }
6325 if (status == NO_ERROR && reconfig) {
6326 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006327 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006328 }
6329 }
6330
Dean Wheatley68918102021-03-19 22:09:19 +11006331 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006332}
6333
6334uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
6335{
6336 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006337 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006338 time = PlaybackThread::activeSleepTimeUs();
6339 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006340 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006341 }
6342 return time;
6343}
6344
6345uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
6346{
6347 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006348 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006349 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6350 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006351 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006352 }
6353 return time;
6354}
6355
6356uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
6357{
6358 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006359 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006360 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6361 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006362 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006363 }
6364 return time;
6365}
6366
6367void AudioFlinger::DirectOutputThread::cacheParameters_l()
6368{
6369 PlaybackThread::cacheParameters_l();
6370
6371 // use shorter standby delay as on normal output to release
6372 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006373 // no delay on outputs with HW A/V sync
6374 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006375 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006376 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006377 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006378 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006379 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006380 }
Eric Laurent81784c32012-11-19 14:55:58 -08006381}
6382
Eric Laurente659ef42014-09-29 13:06:46 -07006383void AudioFlinger::DirectOutputThread::flushHw_l()
6384{
Phil Burk062e67a2015-02-11 13:40:50 -08006385 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006386 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006387 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11006388 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11006389 mTimestamp.clear();
Eric Laurente659ef42014-09-29 13:06:46 -07006390}
6391
Andy Hung10cbff12017-02-21 17:30:14 -08006392int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
6393 // If a VolumeShaper is active, we must wake up periodically to update volume.
6394 const int64_t NS_PER_MS = 1000000;
6395 return mVolumeShaperActive ?
6396 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6397}
6398
Eric Laurent81784c32012-11-19 14:55:58 -08006399// ----------------------------------------------------------------------------
6400
Eric Laurentbfb1b832013-01-07 09:53:42 -08006401AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07006402 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006403 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006404 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006405 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006406 mDrainSequence(0),
6407 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006408{
6409}
6410
6411AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
6412{
6413}
6414
6415void AudioFlinger::AsyncCallbackThread::onFirstRef()
6416{
6417 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6418}
6419
6420bool AudioFlinger::AsyncCallbackThread::threadLoop()
6421{
6422 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006423 uint32_t writeAckSequence;
6424 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006425 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006426
6427 {
6428 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006429 while (!((mWriteAckSequence & 1) ||
6430 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006431 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006432 exitPending())) {
6433 mWaitWorkCV.wait(mLock);
6434 }
6435
Eric Laurentbfb1b832013-01-07 09:53:42 -08006436 if (exitPending()) {
6437 break;
6438 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006439 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
6440 mWriteAckSequence, mDrainSequence);
6441 writeAckSequence = mWriteAckSequence;
6442 mWriteAckSequence &= ~1;
6443 drainSequence = mDrainSequence;
6444 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006445 asyncError = mAsyncError;
6446 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006447 }
6448 {
Eric Laurent4de95592013-09-26 15:28:21 -07006449 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6450 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006451 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006452 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006453 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006454 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006455 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006456 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006457 if (asyncError) {
6458 playbackThread->onAsyncError();
6459 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006460 }
6461 }
6462 }
6463 return false;
6464}
6465
6466void AudioFlinger::AsyncCallbackThread::exit()
6467{
6468 ALOGV("AsyncCallbackThread::exit");
6469 Mutex::Autolock _l(mLock);
6470 requestExit();
6471 mWaitWorkCV.broadcast();
6472}
6473
Eric Laurent3b4529e2013-09-05 18:09:19 -07006474void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006475{
6476 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006477 // bit 0 is cleared
6478 mWriteAckSequence = sequence << 1;
6479}
6480
6481void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6482{
6483 Mutex::Autolock _l(mLock);
6484 // ignore unexpected callbacks
6485 if (mWriteAckSequence & 2) {
6486 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006487 mWaitWorkCV.signal();
6488 }
6489}
6490
Eric Laurent3b4529e2013-09-05 18:09:19 -07006491void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006492{
6493 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006494 // bit 0 is cleared
6495 mDrainSequence = sequence << 1;
6496}
6497
6498void AudioFlinger::AsyncCallbackThread::resetDraining()
6499{
6500 Mutex::Autolock _l(mLock);
6501 // ignore unexpected callbacks
6502 if (mDrainSequence & 2) {
6503 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006504 mWaitWorkCV.signal();
6505 }
6506}
6507
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006508void AudioFlinger::AsyncCallbackThread::setAsyncError()
6509{
6510 Mutex::Autolock _l(mLock);
6511 mAsyncError = true;
6512 mWaitWorkCV.signal();
6513}
6514
Eric Laurentbfb1b832013-01-07 09:53:42 -08006515
6516// ----------------------------------------------------------------------------
6517AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07006518 AudioStreamOut* output, audio_io_handle_t id, bool systemReady)
6519 : DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07006520 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
6521 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006522{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07006523 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07006524 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07006525 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006526}
6527
Eric Laurentbfb1b832013-01-07 09:53:42 -08006528void AudioFlinger::OffloadThread::threadLoop_exit()
6529{
6530 if (mFlushPending || mHwPaused) {
6531 // If a flush is pending or track was paused, just discard buffered data
6532 flushHw_l();
6533 } else {
6534 mMixerStatus = MIXER_DRAIN_ALL;
6535 threadLoop_drain();
6536 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006537 if (mUseAsyncWrite) {
6538 ALOG_ASSERT(mCallbackThread != 0);
6539 mCallbackThread->exit();
6540 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006541 PlaybackThread::threadLoop_exit();
6542}
6543
6544AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6545 Vector< sp<Track> > *tracksToRemove
6546)
6547{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006548 size_t count = mActiveTracks.size();
6549
6550 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006551 bool doHwPause = false;
6552 bool doHwResume = false;
6553
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006554 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006555
Eric Laurentbfb1b832013-01-07 09:53:42 -08006556 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006557 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006558 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006559#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006560 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006561#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006562 // Only consider last track started for volume and mixer state control.
6563 // In theory an older track could underrun and restart after the new one starts
6564 // but as we only care about the transition phase between two tracks on a
6565 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006566 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006567 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006568
Haynes Mathew George7844f672014-01-15 12:32:55 -08006569 if (track->isInvalid()) {
6570 ALOGW("An invalidated track shouldn't be in active list");
6571 tracksToRemove->add(track);
6572 continue;
6573 }
6574
6575 if (track->mState == TrackBase::IDLE) {
6576 ALOGW("An idle track shouldn't be in active list");
6577 continue;
6578 }
6579
Kuowei Li23666472021-01-20 10:23:25 +08006580 if (track->isPausePending()) {
6581 track->pauseAck();
6582 // It is possible a track might have been flushed or stopped.
6583 // Other operations such as flush pending might occur on the next prepare.
6584 if (track->isPausing()) {
6585 track->setPaused();
6586 }
6587 // Always perform pause if last, as an immediate flush will change
6588 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08006589 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006590 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006591 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006592 mHwPaused = true;
6593 }
6594 // If we were part way through writing the mixbuffer to
6595 // the HAL we must save this until we resume
6596 // BUG - this will be wrong if a different track is made active,
6597 // in that case we want to discard the pending data in the
6598 // mixbuffer and tell the client to present it again when the
6599 // track is resumed
6600 mPausedWriteLength = mCurrentWriteLength;
6601 mPausedBytesRemaining = mBytesRemaining;
6602 mBytesRemaining = 0; // stop writing
6603 }
6604 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006605 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006606 if (track->isStopping_1()) {
6607 track->mRetryCount = kMaxTrackStopRetriesOffload;
6608 } else {
6609 track->mRetryCount = kMaxTrackRetriesOffload;
6610 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006611 track->flushAck();
6612 if (last) {
6613 mFlushPending = true;
6614 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006615 } else if (track->isResumePending()){
6616 track->resumeAck();
6617 if (last) {
6618 if (mPausedBytesRemaining) {
6619 // Need to continue write that was interrupted
6620 mCurrentWriteLength = mPausedWriteLength;
6621 mBytesRemaining = mPausedBytesRemaining;
6622 mPausedBytesRemaining = 0;
6623 }
6624 if (mHwPaused) {
6625 doHwResume = true;
6626 mHwPaused = false;
6627 // threadLoop_mix() will handle the case that we need to
6628 // resume an interrupted write
6629 }
6630 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006631 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006632
Eric Laurent3df841a2016-07-15 15:15:40 -07006633 mLeftVolFloat = mRightVolFloat = -1.0;
6634
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006635 // Do not handle new data in this iteration even if track->framesReady()
6636 mixerStatus = MIXER_TRACKS_ENABLED;
6637 }
6638 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006639 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006640 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006641 if (track->mFillingUpStatus == Track::FS_FILLED) {
6642 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006643 if (last) {
6644 // make sure processVolume_l() will apply new volume even if 0
6645 mLeftVolFloat = mRightVolFloat = -1.0;
6646 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006647 }
6648
6649 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006650 sp<Track> previousTrack = mPreviousTrack.promote();
6651 if (previousTrack != 0) {
6652 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006653 // Flush any data still being written from last track
6654 mBytesRemaining = 0;
6655 if (mPausedBytesRemaining) {
6656 // Last track was paused so we also need to flush saved
6657 // mixbuffer state and invalidate track so that it will
6658 // re-submit that unwritten data when it is next resumed
6659 mPausedBytesRemaining = 0;
6660 // Invalidate is a bit drastic - would be more efficient
6661 // to have a flag to tell client that some of the
6662 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006663 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006664 }
6665 // flush data already sent to the DSP if changing audio session as audio
6666 // comes from a different source. Also invalidate previous track to force a
6667 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006668 if (previousTrack->sessionId() != track->sessionId()) {
6669 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006670 }
6671 }
6672 }
6673 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006674 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006675 if (track->isStopping_1()) {
6676 track->mRetryCount = kMaxTrackStopRetriesOffload;
6677 } else {
6678 track->mRetryCount = kMaxTrackRetriesOffload;
6679 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006680 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006681 mixerStatus = MIXER_TRACKS_READY;
6682 }
6683 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006684 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006685 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006686 if (--(track->mRetryCount) <= 0) {
6687 // Hardware buffer can hold a large amount of audio so we must
6688 // wait for all current track's data to drain before we say
6689 // that the track is stopped.
6690 if (mBytesRemaining == 0) {
6691 // Only start draining when all data in mixbuffer
6692 // has been written
6693 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6694 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6695 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6696 if (last && !mStandby) {
6697 // do not modify drain sequence if we are already draining. This happens
6698 // when resuming from pause after drain.
6699 if ((mDrainSequence & 1) == 0) {
6700 mSleepTimeUs = 0;
6701 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6702 mixerStatus = MIXER_DRAIN_TRACK;
6703 mDrainSequence += 2;
6704 }
6705 if (mHwPaused) {
6706 // It is possible to move from PAUSED to STOPPING_1 without
6707 // a resume so we must ensure hardware is running
6708 doHwResume = true;
6709 mHwPaused = false;
6710 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006711 }
6712 }
Eric Laurente93cc032016-05-05 10:15:10 -07006713 } else if (last) {
6714 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6715 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006716 }
6717 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006718 // Drain has completed or we are in standby, signal presentation complete
6719 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006720 track->mState = TrackBase::STOPPED;
Andy Hung59de4262021-06-14 10:53:54 -07006721 track->presentationComplete(latency_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006722 track->reset();
6723 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11006724 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07006725 if (!mUseAsyncWrite) {
6726 // If we don't get explicit drain notification we must
6727 // register discontinuity regardless of whether this is
6728 // the previous (!last) or the upcoming (last) track
6729 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11006730 mTimestampVerifier.discontinuity(
6731 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07006732 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006733 }
6734 } else {
6735 // No buffers for this track. Give it a few chances to
6736 // fill a buffer, then remove it from active list.
6737 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07006738 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006739 uint64_t position = 0;
6740 struct timespec unused;
6741 // The running check restarts the retry counter at least once.
6742 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6743 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6744 running = true;
6745 mOffloadUnderrunPosition = position;
6746 }
6747 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07006748 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6749 (long long)position, (long long)mOffloadUnderrunPosition);
6750 }
6751 if (running) { // still running, give us more time.
6752 track->mRetryCount = kMaxTrackRetriesOffload;
6753 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006754 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6755 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07006756 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006757 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006758 // it will then automatically call start() when data is available
6759 track->disable();
6760 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006761 } else if (last){
6762 mixerStatus = MIXER_TRACKS_ENABLED;
6763 }
6764 }
6765 }
6766 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08006767 if (track->isReady()) { // check ready to prevent premature start.
6768 processVolume_l(track, last);
6769 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006770 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006771
Eric Laurentea0fade2013-10-04 16:23:48 -07006772 // make sure the pause/flush/resume sequence is executed in the right order.
6773 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6774 // before flush and then resume HW. This can happen in case of pause/flush/resume
6775 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006776 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006777 status_t result = mOutput->stream->pause();
6778 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006779 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006780 if (mFlushPending) {
6781 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006782 }
Eric Laurentfd477972013-10-25 18:10:40 -07006783 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006784 status_t result = mOutput->stream->resume();
6785 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006786 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006787
Eric Laurentbfb1b832013-01-07 09:53:42 -08006788 // remove all the tracks that need to be...
6789 removeTracks_l(*tracksToRemove);
6790
6791 return mixerStatus;
6792}
6793
Eric Laurentbfb1b832013-01-07 09:53:42 -08006794// must be called with thread mutex locked
6795bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6796{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006797 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6798 mWriteAckSequence, mDrainSequence);
6799 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006800 return true;
6801 }
6802 return false;
6803}
6804
Eric Laurentbfb1b832013-01-07 09:53:42 -08006805bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6806{
6807 Mutex::Autolock _l(mLock);
6808 return waitingAsyncCallback_l();
6809}
6810
6811void AudioFlinger::OffloadThread::flushHw_l()
6812{
Eric Laurente659ef42014-09-29 13:06:46 -07006813 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006814 // Flush anything still waiting in the mixbuffer
6815 mCurrentWriteLength = 0;
6816 mBytesRemaining = 0;
6817 mPausedWriteLength = 0;
6818 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006819 // reset bytes written count to reflect that DSP buffers are empty after flush.
6820 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006821 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006822
Eric Laurentbfb1b832013-01-07 09:53:42 -08006823 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006824 // discard any pending drain or write ack by incrementing sequence
6825 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6826 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006827 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006828 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6829 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006830 }
6831}
6832
Haynes Mathew George05317d22016-05-03 16:34:26 -07006833void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6834{
6835 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006836 if (PlaybackThread::invalidateTracks_l(streamType)) {
6837 mFlushPending = true;
6838 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006839}
6840
Eric Laurentbfb1b832013-01-07 09:53:42 -08006841// ----------------------------------------------------------------------------
6842
Eric Laurent81784c32012-11-19 14:55:58 -08006843AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006844 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
jiabinc52b1ff2019-10-31 17:20:42 -07006845 : MixerThread(audioFlinger, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006846 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006847 mWaitTimeMs(UINT_MAX)
6848{
6849 addOutputTrack(mainThread);
6850}
6851
6852AudioFlinger::DuplicatingThread::~DuplicatingThread()
6853{
6854 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6855 mOutputTracks[i]->destroy();
6856 }
6857}
6858
6859void AudioFlinger::DuplicatingThread::threadLoop_mix()
6860{
6861 // mix buffers...
6862 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006863 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006864 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006865 if (mMixerBufferValid) {
6866 memset(mMixerBuffer, 0, mMixerBufferSize);
6867 } else {
6868 memset(mSinkBuffer, 0, mSinkBufferSize);
6869 }
Eric Laurent81784c32012-11-19 14:55:58 -08006870 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006871 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006872 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006873 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006874 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006875}
6876
6877void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6878{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006879 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006880 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006881 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006882 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006883 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006884 }
6885 } else if (mBytesWritten != 0) {
6886 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6887 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006888 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006889 } else {
6890 // flush remaining overflow buffers in output tracks
6891 writeFrames = 0;
6892 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006893 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006894 }
6895}
6896
Eric Laurentbfb1b832013-01-07 09:53:42 -08006897ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006898{
6899 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006900 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6901
6902 // Consider the first OutputTrack for timestamp and frame counting.
6903
6904 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6905 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6906 // we always claim success.
6907 if (i == 0) {
6908 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6909 ALOGD_IF(correction != 0 && writeFrames != 0,
6910 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6911 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6912 mFramesWritten -= correction;
6913 }
6914
6915 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006916 }
Andy Hungcf10d742020-04-28 15:38:24 -07006917 if (mStandby) {
6918 mThreadMetrics.logBeginInterval();
6919 mStandby = false;
6920 }
Andy Hung25c2dac2014-02-27 14:56:00 -08006921 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006922}
6923
6924void AudioFlinger::DuplicatingThread::threadLoop_standby()
6925{
6926 // DuplicatingThread implements standby by stopping all tracks
6927 for (size_t i = 0; i < outputTracks.size(); i++) {
6928 outputTracks[i]->stop();
6929 }
6930}
6931
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006932void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Andy Hung1bc088a2018-02-09 15:57:31 -08006933{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006934 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08006935
6936 std::stringstream ss;
6937 const size_t numTracks = mOutputTracks.size();
6938 ss << " " << numTracks << " OutputTracks";
6939 if (numTracks > 0) {
6940 ss << ":";
6941 for (const auto &track : mOutputTracks) {
6942 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07006943 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08006944 if (thread.get() != nullptr) {
6945 ss << thread.get() << ", " << thread->id();
6946 } else {
6947 ss << "null";
6948 }
6949 ss << ")";
6950 }
6951 }
6952 ss << "\n";
6953 std::string result = ss.str();
6954 write(fd, result.c_str(), result.size());
6955}
6956
Eric Laurent81784c32012-11-19 14:55:58 -08006957void AudioFlinger::DuplicatingThread::saveOutputTracks()
6958{
6959 outputTracks = mOutputTracks;
6960}
6961
6962void AudioFlinger::DuplicatingThread::clearOutputTracks()
6963{
6964 outputTracks.clear();
6965}
6966
6967void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6968{
6969 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006970 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6971 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6972 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6973 const size_t frameCount =
6974 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6975 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6976 // from different OutputTracks and their associated MixerThreads (e.g. one may
6977 // nearly empty and the other may be dropping data).
6978
Svet Ganov33761132021-05-13 22:51:08 +00006979 // TODO b/182392769: use attribution source util, move to server edge
6980 AttributionSourceState attributionSource = AttributionSourceState();
6981 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07006982 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00006983 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07006984 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00006985 attributionSource.token = sp<BBinder>::make();
Andy Hungc25b84a2015-01-14 19:04:10 -08006986 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006987 this,
6988 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006989 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006990 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006991 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00006992 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006993 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6994 if (status != NO_ERROR) {
6995 ALOGE("addOutputTrack() initCheck failed %d", status);
6996 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006997 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006998 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6999 mOutputTracks.add(outputTrack);
7000 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7001 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007002}
7003
7004void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
7005{
7006 Mutex::Autolock _l(mLock);
7007 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7008 if (mOutputTracks[i]->thread() == thread) {
7009 mOutputTracks[i]->destroy();
7010 mOutputTracks.removeAt(i);
7011 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07007012 if (thread->getOutput() == mOutput) {
7013 mOutput = NULL;
7014 }
Eric Laurent81784c32012-11-19 14:55:58 -08007015 return;
7016 }
7017 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007018 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007019}
7020
7021// caller must hold mLock
7022void AudioFlinger::DuplicatingThread::updateWaitTime_l()
7023{
7024 mWaitTimeMs = UINT_MAX;
7025 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7026 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
7027 if (strong != 0) {
7028 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7029 if (waitTimeMs < mWaitTimeMs) {
7030 mWaitTimeMs = waitTimeMs;
7031 }
7032 }
7033 }
7034}
7035
7036
7037bool AudioFlinger::DuplicatingThread::outputsReady(
7038 const SortedVector< sp<OutputTrack> > &outputTracks)
7039{
7040 for (size_t i = 0; i < outputTracks.size(); i++) {
7041 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
7042 if (thread == 0) {
7043 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7044 outputTracks[i].get());
7045 return false;
7046 }
7047 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
7048 // see note at standby() declaration
7049 if (playbackThread->standby() && !playbackThread->isSuspended()) {
7050 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7051 thread.get());
7052 return false;
7053 }
7054 }
7055 return true;
7056}
7057
Kevin Rocard12381092018-04-11 09:19:59 -07007058void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
7059 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007060{
Kevin Rocard12381092018-04-11 09:19:59 -07007061 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7062 outputTrack->setMetadatas(metadata.tracks);
7063 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007064}
7065
Eric Laurent81784c32012-11-19 14:55:58 -08007066uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
7067{
7068 return (mWaitTimeMs * 1000) / 2;
7069}
7070
7071void AudioFlinger::DuplicatingThread::cacheParameters_l()
7072{
7073 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7074 updateWaitTime_l();
7075
7076 MixerThread::cacheParameters_l();
7077}
7078
Eric Laurentb3f315a2021-07-13 15:09:05 +02007079// ----------------------------------------------------------------------------
7080
7081AudioFlinger::VirtualizerStageThread::VirtualizerStageThread(const sp<AudioFlinger>& audioFlinger,
7082 AudioStreamOut* output,
7083 audio_io_handle_t id,
7084 bool systemReady,
7085 audio_config_base_t *mixerConfig)
7086 : MixerThread(audioFlinger, output, id, systemReady, VIRTUALIZER_STAGE, mixerConfig)
7087{
7088}
7089
7090void AudioFlinger::VirtualizerStageThread::checkOutputStageEffects()
7091{
7092 bool hasVirtualizer = false;
7093 bool hasDownMixer = false;
7094 sp<EffectHandle> finalDownMixer;
7095 {
7096 Mutex::Autolock _l(mLock);
7097 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
7098 if (chain != 0) {
7099 hasVirtualizer = chain->getEffectFromType_l(FX_IID_VIRTUALIZER_STAGE) != nullptr;
7100 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7101 }
7102
7103 finalDownMixer = mFinalDownMixer;
7104 mFinalDownMixer.clear();
7105 }
7106
7107 if (hasVirtualizer) {
7108 if (finalDownMixer != nullptr) {
7109 int32_t ret;
7110 finalDownMixer->disable(&ret);
7111 }
7112 finalDownMixer.clear();
7113 } else if (!hasDownMixer) {
7114 std::vector<effect_descriptor_t> descriptors;
7115 status_t status = mAudioFlinger->mEffectsFactoryHal->getDescriptors(
7116 EFFECT_UIID_DOWNMIX, &descriptors);
7117 if (status != NO_ERROR) {
7118 return;
7119 }
7120 ALOG_ASSERT(!descriptors.empty(),
7121 "%s getDescriptors() returned no error but empty list", __func__);
7122
7123 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7124 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
7125 &status, false /*pinned*/, false /*probe*/);
7126
7127 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7128 ALOGW("%s error creating downmixer %d", __func__, status);
7129 finalDownMixer.clear();
7130 } else {
7131 int32_t ret;
7132 finalDownMixer->enable(&ret);
7133 }
7134 }
7135
7136 {
7137 Mutex::Autolock _l(mLock);
7138 mFinalDownMixer = finalDownMixer;
7139 }
7140}
7141
Eric Laurent6acd1d42017-01-04 14:23:29 -08007142
Eric Laurent81784c32012-11-19 14:55:58 -08007143// ----------------------------------------------------------------------------
7144// Record
7145// ----------------------------------------------------------------------------
7146
7147AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
7148 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007149 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007150 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007151 ) :
Andy Hungcf10d742020-04-28 15:38:24 -07007152 ThreadBase(audioFlinger, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007153 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007154 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007155 mActiveTracks(&this->mLocalLog),
7156 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007157 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007158 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007159 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7160 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007161 // mFastCapture below
7162 , mFastCaptureFutex(0)
7163 // mInputSource
7164 // mPipeSink
7165 // mPipeSource
7166 , mPipeFramesP2(0)
7167 // mPipeMemory
7168 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007169 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007170 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007171{
Glenn Kastend7dca052015-03-05 16:05:54 -08007172 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
7173 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007174
George Burgess IVa8f90c12020-05-14 11:27:19 -07007175 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007176 mIsMsdDevice = strcmp(
7177 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7178 }
7179
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007180 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007181
Andy Hungc8fddf32018-08-08 18:32:37 -07007182 // TODO: We may also match on address as well as device type for
7183 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007184 // TODO: This property should be ensure that only contains one single device type.
7185 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7186 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007187 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7188 : AUDIO_DEVICE_NONE));
7189
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007190 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007191 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007192 size_t numCounterOffers = 0;
7193 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007194#if !LOG_NDEBUG
7195 ssize_t index =
7196#else
7197 (void)
7198#endif
7199 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007200 ALOG_ASSERT(index == 0);
7201
7202 // initialize fast capture depending on configuration
7203 bool initFastCapture;
7204 switch (kUseFastCapture) {
7205 case FastCapture_Never:
7206 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007207 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007208 break;
7209 case FastCapture_Always:
7210 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007211 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007212 break;
7213 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07007214 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007215 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
7216 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
7217 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007218 break;
7219 // case FastCapture_Dynamic:
7220 }
7221
7222 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007223 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007224 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007225 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7226 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007227 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007228 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007229 const sp<MemoryDealer> roHeap(readOnlyHeap());
7230 sp<IMemory> pipeMemory;
7231 if ((roHeap == 0) ||
7232 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007233 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007234 ALOGE("not enough memory for pipe buffer size=%zu; "
7235 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7236 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7237 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007238 goto failed;
7239 }
7240 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7241 memset(pipeBuffer, 0, pipeSize);
7242 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
7243 const NBAIO_Format offers[1] = {format};
7244 size_t numCounterOffers = 0;
7245 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
7246 ALOG_ASSERT(index == 0);
7247 mPipeSink = pipe;
7248 PipeReader *pipeReader = new PipeReader(*pipe);
7249 numCounterOffers = 0;
7250 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
7251 ALOG_ASSERT(index == 0);
7252 mPipeSource = pipeReader;
7253 mPipeFramesP2 = pipeFramesP2;
7254 mPipeMemory = pipeMemory;
7255
7256 // create fast capture
7257 mFastCapture = new FastCapture();
7258 FastCaptureStateQueue *sq = mFastCapture->sq();
7259#ifdef STATE_QUEUE_DUMP
7260 // FIXME
7261#endif
7262 FastCaptureState *state = sq->begin();
7263 state->mCblk = NULL;
7264 state->mInputSource = mInputSource.get();
7265 state->mInputSourceGen++;
7266 state->mPipeSink = pipe;
7267 state->mPipeSinkGen++;
7268 state->mFrameCount = mFrameCount;
7269 state->mCommand = FastCaptureState::COLD_IDLE;
7270 // already done in constructor initialization list
7271 //mFastCaptureFutex = 0;
7272 state->mColdFutexAddr = &mFastCaptureFutex;
7273 state->mColdGen++;
7274 state->mDumpState = &mFastCaptureDumpState;
7275#ifdef TEE_SINK
7276 // FIXME
7277#endif
7278 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
7279 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7280 sq->end();
7281 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7282
7283 // start the fast capture
7284 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7285 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007286 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007287 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007288#ifdef AUDIO_WATCHDOG
7289 // FIXME
7290#endif
7291
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007292 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007293 }
Andy Hung8946a282018-04-19 20:04:56 -07007294#ifdef TEE_SINK
7295 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7296 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7297#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007298failed: ;
7299
7300 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007301}
7302
Eric Laurent81784c32012-11-19 14:55:58 -08007303AudioFlinger::RecordThread::~RecordThread()
7304{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007305 if (mFastCapture != 0) {
7306 FastCaptureStateQueue *sq = mFastCapture->sq();
7307 FastCaptureState *state = sq->begin();
7308 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7309 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7310 if (old == -1) {
7311 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7312 }
7313 }
7314 state->mCommand = FastCaptureState::EXIT;
7315 sq->end();
7316 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7317 mFastCapture->join();
7318 mFastCapture.clear();
7319 }
7320 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07007321 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07007322 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08007323}
7324
7325void AudioFlinger::RecordThread::onFirstRef()
7326{
Glenn Kastend7dca052015-03-05 16:05:54 -08007327 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08007328}
7329
Eric Laurent555530a2017-02-07 18:17:24 -08007330void AudioFlinger::RecordThread::preExit()
7331{
7332 ALOGV(" preExit()");
7333 Mutex::Autolock _l(mLock);
7334 for (size_t i = 0; i < mTracks.size(); i++) {
7335 sp<RecordTrack> track = mTracks[i];
7336 track->invalidate();
7337 }
7338 mActiveTracks.clear();
7339 mStartStopCond.broadcast();
7340}
7341
Eric Laurent81784c32012-11-19 14:55:58 -08007342bool AudioFlinger::RecordThread::threadLoop()
7343{
Eric Laurent81784c32012-11-19 14:55:58 -08007344 nsecs_t lastWarning = 0;
7345
7346 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007347
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007348reacquire_wakelock:
7349 sp<RecordTrack> activeTrack;
7350 {
7351 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07007352 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007353 }
7354
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007355 // used to request a deferred sleep, to be executed later while mutex is unlocked
7356 uint32_t sleepUs = 0;
7357
Andy Hung446f4df2019-02-21 12:26:41 -08007358 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
7359
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007360 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08007361 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007362 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07007363
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007364 // activeTracks accumulates a copy of a subset of mActiveTracks
7365 Vector< sp<RecordTrack> > activeTracks;
7366
Glenn Kasten735f45f2014-08-18 15:51:59 -07007367 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007368 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07007369
Glenn Kasten735f45f2014-08-18 15:51:59 -07007370 // reference to a fast track which is about to be removed
7371 sp<RecordTrack> fastTrackToRemove;
7372
Eric Laurent33403f02020-05-29 18:35:06 -07007373 bool silenceFastCapture = false;
7374
Eric Laurent81784c32012-11-19 14:55:58 -08007375 { // scope for mLock
7376 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08007377
Eric Laurent021cf962014-05-13 10:18:14 -07007378 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007379
Eric Laurent000a4192014-01-29 15:17:32 -08007380 // check exitPending here because checkForNewParameters_l() and
7381 // checkForNewParameters_l() can temporarily release mLock
7382 if (exitPending()) {
7383 break;
7384 }
7385
Eric Laurent5c25d562016-07-13 17:17:45 -07007386 // sleep with mutex unlocked
7387 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07007388 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07007389 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
7390 ATRACE_END();
7391 sleepUs = 0;
7392 continue;
7393 }
7394
Glenn Kasten2b806402013-11-20 16:37:38 -08007395 // if no active track(s), then standby and release wakelock
7396 size_t size = mActiveTracks.size();
7397 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07007398 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07007399 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08007400 releaseWakeLock_l();
7401 ALOGV("RecordThread: loop stopping");
7402 // go to sleep
7403 mWaitWorkCV.wait(mLock);
7404 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007405 goto reacquire_wakelock;
7406 }
7407
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007408 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07007409 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007410 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07007411
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007412 activeTrack = mActiveTracks[i];
7413 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07007414 if (activeTrack->isFastTrack()) {
7415 ALOG_ASSERT(fastTrackToRemove == 0);
7416 fastTrackToRemove = activeTrack;
7417 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007418 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08007419 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007420 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07007421 continue;
7422 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007423
7424 TrackBase::track_state activeTrackState = activeTrack->mState;
7425 switch (activeTrackState) {
7426
7427 case TrackBase::PAUSING:
7428 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07007429 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007430 doBroadcast = true;
7431 size--;
7432 continue;
7433
7434 case TrackBase::STARTING_1:
7435 sleepUs = 10000;
7436 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07007437 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007438 continue;
7439
7440 case TrackBase::STARTING_2:
7441 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07007442 if (mStandby) {
7443 mThreadMetrics.logBeginInterval();
7444 mStandby = false;
7445 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007446 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07007447 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007448 break;
7449
7450 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07007451 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007452 break;
7453
Andy Hungce685402018-10-05 17:23:27 -07007454 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
7455 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
7456 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007457 default:
Andy Hungce685402018-10-05 17:23:27 -07007458 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
7459 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07007460 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007461
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007462 if (activeTrack->isFastTrack()) {
7463 ALOG_ASSERT(!mFastTrackAvail);
7464 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07007465 // if the active fast track is silenced either:
7466 // 1) silence the whole capture from fast capture buffer if this is
7467 // the only active track
7468 // 2) invalidate this track: this will cause the client to reconnect and possibly
7469 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007470 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07007471 if (activeTrack->isSilenced()) {
7472 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007473 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07007474 } else {
7475 silenceFastCapture = true;
7476 }
7477 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007478 // Invalidate fast tracks if access to audio history is required as this is not
7479 // possible with fast tracks. Once the fast track has been invalidated, no new
7480 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
7481 if (mMaxSharedAudioHistoryMs != 0) {
7482 invalidate = true;
7483 }
7484 if (invalidate) {
7485 activeTrack->invalidate();
7486 ALOG_ASSERT(fastTrackToRemove == 0);
7487 fastTrackToRemove = activeTrack;
7488 removeTrack_l(activeTrack);
7489 mActiveTracks.remove(activeTrack);
7490 size--;
7491 continue;
7492 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007493 fastTrack = activeTrack;
7494 }
Eric Laurent33403f02020-05-29 18:35:06 -07007495
7496 activeTracks.add(activeTrack);
7497 i++;
7498
Glenn Kasten9e982352013-08-14 14:39:50 -07007499 }
Eric Laurent5c25d562016-07-13 17:17:45 -07007500
Andy Hungdae27702016-10-31 14:01:16 -07007501 mActiveTracks.updatePowerState(this);
7502
Kevin Rocard069c2712018-03-29 19:09:14 -07007503 updateMetadata_l();
7504
Eric Laurent5c25d562016-07-13 17:17:45 -07007505 if (allStopped) {
7506 standbyIfNotAlreadyInStandby();
7507 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007508 if (doBroadcast) {
7509 mStartStopCond.broadcast();
7510 }
7511
7512 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07007513 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007514 if (sleepUs == 0) {
7515 sleepUs = kRecordThreadSleepUs;
7516 }
7517 continue;
7518 }
7519 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07007520
Eric Laurent81784c32012-11-19 14:55:58 -08007521 lockEffectChains_l(effectChains);
7522 }
7523
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007524 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07007525
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007526 size_t size = effectChains.size();
7527 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007528 // thread mutex is not locked, but effect chain is locked
7529 effectChains[i]->process_l();
7530 }
7531
Glenn Kasten735f45f2014-08-18 15:51:59 -07007532 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007533 if (mFastCapture != 0) {
7534 FastCaptureStateQueue *sq = mFastCapture->sq();
7535 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07007536 bool didModify = false;
7537 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007538 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
7539 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
7540 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7541 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7542 if (old == -1) {
7543 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7544 }
7545 }
7546 state->mCommand = FastCaptureState::READ_WRITE;
7547#if 0 // FIXME
7548 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08007549 FastThreadDumpState::kSamplingNforLowRamDevice :
7550 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007551#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07007552 didModify = true;
7553 }
7554 audio_track_cblk_t *cblkOld = state->mCblk;
7555 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
7556 if (cblkNew != cblkOld) {
7557 state->mCblk = cblkNew;
7558 // block until acked if removing a fast track
7559 if (cblkOld != NULL) {
7560 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7561 }
7562 didModify = true;
7563 }
jiabin01c8f562018-07-19 17:47:28 -07007564 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7565 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7566 if (state->mFastPatchRecordBufferProvider != abp) {
7567 state->mFastPatchRecordBufferProvider = abp;
7568 state->mFastPatchRecordFormat = fastTrack == 0 ?
7569 AUDIO_FORMAT_INVALID : fastTrack->format();
7570 didModify = true;
7571 }
Eric Laurent33403f02020-05-29 18:35:06 -07007572 if (state->mSilenceCapture != silenceFastCapture) {
7573 state->mSilenceCapture = silenceFastCapture;
7574 didModify = true;
7575 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07007576 sq->end(didModify);
7577 if (didModify) {
7578 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007579#if 0
7580 if (kUseFastCapture == FastCapture_Dynamic) {
7581 mNormalSource = mPipeSource;
7582 }
7583#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007584 }
7585 }
7586
Glenn Kasten735f45f2014-08-18 15:51:59 -07007587 // now run the fast track destructor with thread mutex unlocked
7588 fastTrackToRemove.clear();
7589
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007590 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7591 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7592 // slow, then this RecordThread will overrun by not calling HAL read often enough.
7593 // If destination is non-contiguous, first read past the nominal end of buffer, then
7594 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007595
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007596 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007597 ssize_t framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007598 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007599
7600 // If an NBAIO source is present, use it to read the normal capture's data
7601 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07007602 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07007603
7604 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7605 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
7606 // we immediately retry the read() to get data and prevent another overflow.
7607 for (int retries = 0; retries <= 2; ++retries) {
7608 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
7609 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
7610 framesToRead);
7611 if (framesRead != OVERRUN) break;
7612 }
7613
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007614 const ssize_t availableToRead = mPipeSource->availableToRead();
7615 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00007616 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07007617 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007618 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
7619 "more frames to read than fifo size, %zd > %zu",
7620 availableToRead, mPipeFramesP2);
7621 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
7622 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
7623 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
7624 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07007625 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
7626 }
7627 if (framesRead < 0) {
7628 status_t status = (status_t) framesRead;
7629 switch (status) {
7630 case OVERRUN:
7631 ALOGW("overrun on read from pipe");
7632 framesRead = 0;
7633 break;
7634 case NEGOTIATE:
7635 ALOGE("re-negotiation is needed");
7636 framesRead = -1; // Will cause an attempt to recover.
7637 break;
7638 default:
7639 ALOGE("unknown error %d on read from pipe", status);
7640 break;
7641 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007642 }
7643 // otherwise use the HAL / AudioStreamIn directly
7644 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07007645 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007646 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07007647 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007648 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07007649 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007650 if (result < 0) {
7651 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007652 } else {
7653 framesRead = bytesRead / mFrameSize;
7654 }
7655 }
7656
Andy Hung446f4df2019-02-21 12:26:41 -08007657 const int64_t lastIoEndNs = systemTime(); // end IO timing
7658
Andy Hung3f0c9022016-01-15 17:49:46 -08007659 // Update server timestamp with server stats
7660 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07007661 if (framesRead >= 0) {
7662 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
7663 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
7664 }
Andy Hung3f0c9022016-01-15 17:49:46 -08007665
7666 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007667 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08007668 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007669 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11007670 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
7671 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
7672 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07007673 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07007674 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
7675
7676 mTimestampVerifier.add(position, time, mSampleRate);
7677
7678 // Correct timestamps
7679 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10007680 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007681 id(), (long long)time, (long long)position);
7682 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
7683 position = correctedTimestamp.mFrames;
7684 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10007685 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007686 id(), (long long)time, (long long)position);
7687 }
7688
Andy Hung3f0c9022016-01-15 17:49:46 -08007689 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
7690 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
7691 // Note: In general record buffers should tend to be empty in
7692 // a properly running pipeline.
7693 //
7694 // Also, it is not advantageous to call get_presentation_position during the read
7695 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007696 } else {
7697 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08007698 }
7699 }
Andy Hunge6c37112019-02-26 17:38:10 -08007700
7701 // From the timestamp, input read latency is negative output write latency.
7702 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
7703 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
7704 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
7705 if (latencyMs != 0.) { // note 0. means timestamp is empty.
7706 mLatencyMs.add(latencyMs);
7707 }
7708
Andy Hung3f0c9022016-01-15 17:49:46 -08007709 // Use this to track timestamp information
7710 // ALOGD("%s", mTimestamp.toString().c_str());
7711
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007712 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007713 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007714 // Force input into standby so that it tries to recover at next read attempt
7715 inputStandBy();
7716 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007717 }
7718 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007719 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007720 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007721 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07007722 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007723
Andy Hung8946a282018-04-19 20:04:56 -07007724#ifdef TEE_SINK
7725 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
7726#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007727 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007728 {
7729 size_t part1 = mRsmpInFramesP2 - rear;
7730 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07007731 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007732 (framesRead - part1) * mFrameSize);
7733 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007734 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11007735 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007736
7737 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007738
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007739 // loop over each active track
7740 for (size_t i = 0; i < size; i++) {
7741 activeTrack = activeTracks[i];
7742
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007743 // skip fast tracks, as those are handled directly by FastCapture
7744 if (activeTrack->isFastTrack()) {
7745 continue;
7746 }
7747
Andy Hung73c02e42015-03-29 01:13:58 -07007748 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07007749 // TODO: Update the activeTrack buffer converter in case of reconfigure.
7750
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007751 enum {
7752 OVERRUN_UNKNOWN,
7753 OVERRUN_TRUE,
7754 OVERRUN_FALSE
7755 } overrun = OVERRUN_UNKNOWN;
7756
7757 // loop over getNextBuffer to handle circular sink
7758 for (;;) {
7759
7760 activeTrack->mSink.frameCount = ~0;
7761 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
7762 size_t framesOut = activeTrack->mSink.frameCount;
7763 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
7764
Andy Hung73c02e42015-03-29 01:13:58 -07007765 // check available frames and handle overrun conditions
7766 // if the record track isn't draining fast enough.
7767 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007768 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07007769 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
7770 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007771 overrun = OVERRUN_TRUE;
7772 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007773 if (framesOut == 0 || framesIn == 0) {
7774 break;
7775 }
7776
Andy Hung6770c6f2015-04-07 13:43:36 -07007777 // Don't allow framesOut to be larger than what is possible with resampling
7778 // from framesIn.
7779 // This isn't strictly necessary but helps limit buffer resizing in
7780 // RecordBufferConverter. TODO: remove when no longer needed.
7781 framesOut = min(framesOut,
7782 destinationFramesPossible(
7783 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007784
7785 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007786 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007787 // straight from RecordThread buffer to RecordTrack buffer.
7788 AudioBufferProvider::Buffer buffer;
7789 buffer.frameCount = framesOut;
7790 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
7791 if (status == OK && buffer.frameCount != 0) {
7792 ALOGV_IF(buffer.frameCount != framesOut,
7793 "%s() read less than expected (%zu vs %zu)",
7794 __func__, buffer.frameCount, framesOut);
7795 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007796 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007797 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
7798 } else {
7799 framesOut = 0;
7800 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
7801 __func__, status, buffer.frameCount);
7802 }
7803 } else {
7804 // process frames from the RecordThread buffer provider to the RecordTrack
7805 // buffer
7806 framesOut = activeTrack->mRecordBufferConverter->convert(
7807 activeTrack->mSink.raw,
7808 activeTrack->mResamplerBufferProvider,
7809 framesOut);
7810 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007811
7812 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
7813 overrun = OVERRUN_FALSE;
7814 }
7815
7816 if (activeTrack->mFramesToDrop == 0) {
7817 if (framesOut > 0) {
7818 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007819 // Sanitize before releasing if the track has no access to the source data
7820 // An idle UID receives silence from non virtual devices until active
7821 if (activeTrack->isSilenced()) {
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07007822 memset(activeTrack->mSink.raw, 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007823 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007824 activeTrack->releaseBuffer(&activeTrack->mSink);
7825 }
7826 } else {
7827 // FIXME could do a partial drop of framesOut
7828 if (activeTrack->mFramesToDrop > 0) {
Mikhail Naganov6d91ba52019-03-26 14:35:28 -07007829 activeTrack->mFramesToDrop -= (ssize_t)framesOut;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007830 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007831 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007832 }
7833 } else {
7834 activeTrack->mFramesToDrop += framesOut;
7835 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
7836 activeTrack->mSyncStartEvent->isCancelled()) {
7837 ALOGW("Synced record %s, session %d, trigger session %d",
7838 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
7839 activeTrack->sessionId(),
7840 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08007841 activeTrack->mSyncStartEvent->triggerSession() :
7842 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007843 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007844 }
7845 }
7846 }
7847
7848 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007849 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007850 }
7851 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007852
7853 switch (overrun) {
7854 case OVERRUN_TRUE:
7855 // client isn't retrieving buffers fast enough
7856 if (!activeTrack->setOverflow()) {
7857 nsecs_t now = systemTime();
7858 // FIXME should lastWarning per track?
7859 if ((now - lastWarning) > kWarningThrottleNs) {
7860 ALOGW("RecordThread: buffer overflow");
7861 lastWarning = now;
7862 }
7863 }
7864 break;
7865 case OVERRUN_FALSE:
7866 activeTrack->clearOverflow();
7867 break;
7868 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007869 break;
7870 }
7871
Andy Hung3f0c9022016-01-15 17:49:46 -08007872 // update frame information and push timestamp out
7873 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08007874 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08007875 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
7876 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007877 }
7878
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007879unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08007880 // enable changes in effect chain
7881 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007882 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07007883 if (audio_has_proportional_frames(mFormat)
7884 && loopCount == lastLoopCountRead + 1) {
7885 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
7886 const double jitterMs =
7887 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
7888 {framesRead, readPeriodNs},
7889 {0, 0} /* lastTimestamp */, mSampleRate);
7890 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
7891
7892 Mutex::Autolock _l(mLock);
7893 mIoJitterMs.add(jitterMs);
7894 mProcessTimeMs.add(processMs);
7895 }
7896 // update timing info.
7897 mLastIoBeginNs = lastIoBeginNs;
7898 mLastIoEndNs = lastIoEndNs;
7899 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007900 }
7901
Glenn Kasten93e471f2013-08-19 08:40:07 -07007902 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08007903
7904 {
7905 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07007906 for (size_t i = 0; i < mTracks.size(); i++) {
7907 sp<RecordTrack> track = mTracks[i];
7908 track->invalidate();
7909 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007910 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007911 mStartStopCond.broadcast();
7912 }
7913
7914 releaseWakeLock();
7915
7916 ALOGV("RecordThread %p exiting", this);
7917 return false;
7918}
7919
Glenn Kasten93e471f2013-08-19 08:40:07 -07007920void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08007921{
7922 if (!mStandby) {
7923 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07007924 mThreadMetrics.logEndInterval();
Eric Laurent81784c32012-11-19 14:55:58 -08007925 mStandby = true;
7926 }
7927}
7928
7929void AudioFlinger::RecordThread::inputStandBy()
7930{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007931 // Idle the fast capture if it's currently running
7932 if (mFastCapture != 0) {
7933 FastCaptureStateQueue *sq = mFastCapture->sq();
7934 FastCaptureState *state = sq->begin();
7935 if (!(state->mCommand & FastCaptureState::IDLE)) {
7936 state->mCommand = FastCaptureState::COLD_IDLE;
7937 state->mColdFutexAddr = &mFastCaptureFutex;
7938 state->mColdGen++;
7939 mFastCaptureFutex = 0;
7940 sq->end();
7941 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7942 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7943#if 0
7944 if (kUseFastCapture == FastCapture_Dynamic) {
7945 // FIXME
7946 }
7947#endif
7948#ifdef AUDIO_WATCHDOG
7949 // FIXME
7950#endif
7951 } else {
7952 sq->end(false /*didModify*/);
7953 }
7954 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07007955 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007956 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007957
7958 // If going into standby, flush the pipe source.
7959 if (mPipeSource.get() != nullptr) {
7960 const ssize_t flushed = mPipeSource->flush();
7961 if (flushed > 0) {
7962 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7963 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7964 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7965 }
7966 }
Eric Laurent81784c32012-11-19 14:55:58 -08007967}
7968
Glenn Kasten05997e22014-03-13 15:08:33 -07007969// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007970sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007971 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007972 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007973 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007974 audio_format_t format,
7975 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007976 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007977 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007978 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07007979 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00007980 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07007981 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007982 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007983 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02007984 audio_port_handle_t portId,
7985 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08007986{
Glenn Kasten74935e42013-12-19 08:56:45 -08007987 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007988 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007989 sp<RecordTrack> track;
7990 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007991 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007992 audio_input_flags_t requestedFlags = *flags;
7993 uint32_t sampleRate;
Svet Ganov33761132021-05-13 22:51:08 +00007994 AttributionSourceState checkedAttributionSource = AudioFlinger::checkAttributionSourcePackage(
7995 attributionSource);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007996
7997 lStatus = initCheck();
7998 if (lStatus != NO_ERROR) {
7999 ALOGE("createRecordTrack_l() audio driver not initialized");
8000 goto Exit;
8001 }
8002
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008003 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8004 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8005 lStatus = BAD_VALUE;
8006 goto Exit;
8007 }
8008
Eric Laurentec376dc2021-04-08 20:41:22 +02008009 if (maxSharedAudioHistoryMs != 0) {
Svet Ganov33761132021-05-13 22:51:08 +00008010 if (!captureHotwordAllowed(checkedAttributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008011 lStatus = PERMISSION_DENIED;
8012 goto Exit;
8013 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008014 if (maxSharedAudioHistoryMs < 0
8015 || maxSharedAudioHistoryMs > AudioFlinger::kMaxSharedAudioHistoryMs) {
8016 lStatus = BAD_VALUE;
8017 goto Exit;
8018 }
8019 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008020 if (*pSampleRate == 0) {
8021 *pSampleRate = mSampleRate;
8022 }
8023 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008024
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008025 // special case for FAST flag considered OK if fast capture is present and access to
8026 // audio history is not required
8027 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008028 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8029 }
8030
Eric Laurentf14db3c2017-12-08 14:20:36 -08008031 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008032 if ((*flags & inputFlags) != *flags) {
8033 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8034 " input flags (%08x)",
8035 *flags, inputFlags);
8036 *flags = (audio_input_flags_t)(*flags & inputFlags);
8037 }
Eric Laurent81784c32012-11-19 14:55:58 -08008038
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008039 // client expresses a preference for FAST and no access to audio history,
8040 // but we get the final say
8041 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008042 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008043 // we formerly checked for a callback handler (non-0 tid),
8044 // but that is no longer required for TRANSFER_OBTAIN mode
8045 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008046 // Frame count is not specified (0), or is less than or equal the pipe depth.
8047 // It is OK to provide a higher capacity than requested.
8048 // We will force it to mPipeFramesP2 below.
8049 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008050 // PCM data
8051 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008052 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008053 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008054 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008055 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008056 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008057 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008058 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008059 hasFastCapture() &&
8060 // there are sufficient fast track slots available
8061 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008062 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008063 // check compatibility with audio effects.
8064 Mutex::Autolock _l(mLock);
8065 // Do not accept FAST flag if the session has software effects
8066 sp<EffectChain> chain = getEffectChain_l(sessionId);
8067 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008068 audio_input_flags_t old = *flags;
8069 chain->checkInputFlagCompatibility(flags);
8070 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008071 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8072 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008073 }
8074 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008075 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008076 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8077 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008078 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008079 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8080 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008081 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008082 this, frameCount, mFrameCount, mPipeFramesP2,
8083 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008084 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008085 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008086 }
8087 }
8088
Eric Laurentf14db3c2017-12-08 14:20:36 -08008089 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8090 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8091 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8092 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8093 lStatus = BAD_TYPE;
8094 goto Exit;
8095 }
8096
Glenn Kasten74105912014-07-03 12:28:53 -07008097 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008098 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008099 // fast track: frame count is exactly the pipe depth
8100 frameCount = mPipeFramesP2;
8101 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008102 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008103 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008104 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8105 // or 20 ms if there is a fast capture
8106 // TODO This could be a roundupRatio inline, and const
8107 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8108 * sampleRate + mSampleRate - 1) / mSampleRate;
8109 // minimum number of notification periods is at least kMinNotifications,
8110 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8111 static const size_t kMinNotifications = 3;
8112 static const uint32_t kMinMs = 30;
8113 // TODO This could be a roundupRatio inline
8114 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8115 // TODO This could be a roundupRatio inline
8116 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8117 maxNotificationFrames;
8118 const size_t minFrameCount = maxNotificationFrames *
8119 max(kMinNotifications, minNotificationsByMs);
8120 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008121 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8122 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008123 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008124 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008125 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008126 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008127
8128 { // scope for mLock
8129 Mutex::Autolock _l(mLock);
Eric Laurent2407ce32021-04-26 14:56:03 +02008130 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008131 if (!mSharedAudioPackageName.empty()
Svet Ganov33761132021-05-13 22:51:08 +00008132 && mSharedAudioPackageName == checkedAttributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008133 && mSharedAudioSessionId == sessionId
Svet Ganov33761132021-05-13 22:51:08 +00008134 && captureHotwordAllowed(checkedAttributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008135 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008136 }
Eric Laurent81784c32012-11-19 14:55:58 -08008137
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008138 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008139 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008140 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008141 checkedAttributionSource, *flags, TrackBase::TYPE_DEFAULT, portId,
8142 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008143
Glenn Kasten03003332013-08-06 15:40:54 -07008144 lStatus = track->initCheck();
8145 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008146 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008147 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008148 goto Exit;
8149 }
8150 mTracks.add(track);
8151
Eric Laurent05067782016-06-01 18:27:28 -07008152 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008153 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8154 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8155 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008156 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008157 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008158
8159 if (maxSharedAudioHistoryMs != 0) {
8160 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8161 }
Eric Laurent81784c32012-11-19 14:55:58 -08008162 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008163
Eric Laurent81784c32012-11-19 14:55:58 -08008164 lStatus = NO_ERROR;
8165
8166Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008167 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008168 return track;
8169}
8170
8171status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
8172 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008173 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008174{
8175 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8176 sp<ThreadBase> strongMe = this;
8177 status_t status = NO_ERROR;
8178
8179 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008180 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008181 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008182 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08008183 triggerSession,
8184 recordTrack->sessionId(),
8185 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008186 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08008187 // Sync event can be cancelled by the trigger session if the track is not in a
8188 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008189 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008190 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008191 } else {
8192 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08008193 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008194 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08008195 }
8196 }
8197
8198 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008199 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08008200 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008201 if (recordTrack->isInvalid()) {
8202 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008203 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8204 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008205 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008206 if (mActiveTracks.indexOf(recordTrack) >= 0) {
8207 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008208 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8209 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008210 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008211 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008212 } else {
8213 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008214 }
8215 return status;
8216 }
8217
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008218 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8219 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8220 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008221 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08008222 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008223 status_t status = NO_ERROR;
8224 if (recordTrack->isExternalTrack()) {
8225 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008226 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07008227 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07008228 if (recordTrack->isInvalid()) {
8229 recordTrack->clearSyncStartEvent();
8230 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
8231 recordTrack->mState = TrackBase::STARTING_2;
8232 // STARTING_2 forces destroy to call stopInput.
8233 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008234 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8235 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008236 }
8237 if (recordTrack->mState != TrackBase::STARTING_1) {
8238 ALOGW("%s(%d): unsynchronized mState:%d change",
8239 __func__, recordTrack->id(), recordTrack->mState);
8240 // Someone else has changed state, let them take over,
8241 // leave mState in the new state.
8242 recordTrack->clearSyncStartEvent();
8243 return INVALID_OPERATION;
8244 }
8245 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008246 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008247 ALOGW("%s(%d): startInput failed, status %d",
8248 __func__, recordTrack->id(), status);
8249 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8250 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008251 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008252 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008253 return status;
8254 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008255 sendIoConfigEvent_l(
8256 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008257 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008258
8259 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8260
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008261 // Catch up with current buffer indices if thread is already running.
8262 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8263 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8264 // see previously buffered data before it called start(), but with greater risk of overrun.
8265
Andy Hung73c02e42015-03-29 01:13:58 -07008266 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008267 if (!recordTrack->isDirect()) {
8268 // clear any converter state as new data will be discontinuous
8269 recordTrack->mRecordBufferConverter->reset();
8270 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008271 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08008272 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08008273 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08008274 return status;
8275 }
Eric Laurent81784c32012-11-19 14:55:58 -08008276}
8277
Eric Laurent81784c32012-11-19 14:55:58 -08008278void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
8279{
8280 sp<SyncEvent> strongEvent = event.promote();
8281
8282 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08008283 sp<RefBase> ptr = strongEvent->cookie().promote();
8284 if (ptr != 0) {
8285 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
8286 recordTrack->handleSyncStartEvent(strongEvent);
8287 }
Eric Laurent81784c32012-11-19 14:55:58 -08008288 }
8289}
8290
Glenn Kastena8356f62013-07-25 14:37:52 -07008291bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08008292 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008293 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008294 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07008295 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008296 return false;
8297 }
Glenn Kasten47c20702013-08-13 15:37:35 -07008298 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08008299 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07008300
Andy Hungabfab202019-03-07 19:45:54 -08008301 // NOTE: Waiting here is important to keep stop synchronous.
8302 // This is needed for proper patchRecord peer release.
Andy Hungce685402018-10-05 17:23:27 -07008303 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
8304 mWaitWorkCV.broadcast(); // signal thread to stop
8305 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008306 }
Andy Hungce685402018-10-05 17:23:27 -07008307
8308 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008309 ALOGV("Record stopped OK");
8310 return true;
8311 }
Andy Hungce685402018-10-05 17:23:27 -07008312
8313 // don't handle anything - we've been invalidated or restarted and in a different state
8314 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
8315 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008316 return false;
8317}
8318
Glenn Kasten0f11b512014-01-31 16:18:54 -08008319bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08008320{
8321 return false;
8322}
8323
Glenn Kasten0f11b512014-01-31 16:18:54 -08008324status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008325{
8326#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8327 if (!isValidSyncEvent(event)) {
8328 return BAD_VALUE;
8329 }
8330
Glenn Kastend848eb42016-03-08 13:42:11 -08008331 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08008332 status_t ret = NAME_NOT_FOUND;
8333
8334 Mutex::Autolock _l(mLock);
8335
8336 for (size_t i = 0; i < mTracks.size(); i++) {
8337 sp<RecordTrack> track = mTracks[i];
8338 if (eventSession == track->sessionId()) {
8339 (void) track->setSyncEvent(event);
8340 ret = NO_ERROR;
8341 }
8342 }
8343 return ret;
8344#else
8345 return BAD_VALUE;
8346#endif
8347}
8348
jiabin653cc0a2018-01-17 17:54:10 -08008349status_t AudioFlinger::RecordThread::getActiveMicrophones(
8350 std::vector<media::MicrophoneInfo>* activeMicrophones)
8351{
8352 ALOGV("RecordThread::getActiveMicrophones");
8353 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008354 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008355 return NO_INIT;
8356 }
jiabin9ff780e2018-03-19 18:19:52 -07008357 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
8358 return status;
jiabin653cc0a2018-01-17 17:54:10 -08008359}
8360
Paul McLean12340082019-03-19 09:35:05 -06008361status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection(
8362 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008363{
Paul McLean12340082019-03-19 09:35:05 -06008364 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008365 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008366 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008367 return NO_INIT;
8368 }
Paul McLean12340082019-03-19 09:35:05 -06008369 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008370}
8371
Paul McLean12340082019-03-19 09:35:05 -06008372status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008373{
Paul McLean12340082019-03-19 09:35:05 -06008374 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008375 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008376 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008377 return NO_INIT;
8378 }
Paul McLean12340082019-03-19 09:35:05 -06008379 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008380}
8381
Eric Laurentec376dc2021-04-08 20:41:22 +02008382status_t AudioFlinger::RecordThread::shareAudioHistory(
8383 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8384 int64_t sharedAudioStartMs) {
8385 AutoMutex _l(mLock);
8386 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
8387}
8388
8389status_t AudioFlinger::RecordThread::shareAudioHistory_l(
8390 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8391 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008392
Eric Laurentec376dc2021-04-08 20:41:22 +02008393 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
8394 return BAD_VALUE;
8395 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008396
8397 if (sharedAudioStartMs < 0
8398 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008399 return BAD_VALUE;
8400 }
8401
Eric Laurent2407ce32021-04-26 14:56:03 +02008402 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
8403 // As we cannot detect more than one wraparound, only accept values up current write position
8404 // after one wraparound
8405 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
8406 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02008407 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02008408 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
8409 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02008410 // Bring the start frame position within the input buffer to match the documented
8411 // "best effort" behavior of the API.
8412 if (sharedOffset < 0) {
8413 sharedAudioStartFrames = mRsmpInRear;
8414 } else if (sharedOffset > mRsmpInFrames) {
8415 sharedAudioStartFrames =
8416 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02008417 }
8418
Eric Laurentec376dc2021-04-08 20:41:22 +02008419 mSharedAudioPackageName = sharedAudioPackageName;
8420 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008421 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02008422 } else {
8423 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02008424 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008425 }
8426 return NO_ERROR;
8427}
8428
Eric Laurent92d0a322021-07-16 15:32:33 +02008429void AudioFlinger::RecordThread::resetAudioHistory_l() {
8430 mSharedAudioSessionId = AUDIO_SESSION_NONE;
8431 mSharedAudioStartFrames = -1;
8432 mSharedAudioPackageName = "";
8433}
8434
Kevin Rocard069c2712018-03-29 19:09:14 -07008435void AudioFlinger::RecordThread::updateMetadata_l()
8436{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008437 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
8438 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07008439 }
8440 StreamInHalInterface::SinkMetadata metadata;
8441 for (const sp<RecordTrack> &track : mActiveTracks) {
Eric Laurentb9cc0ab2021-01-29 11:46:52 +01008442 // Do not forward PatchRecord metadata to audio HAL
8443 if (track->isPatchTrack()) {
8444 continue;
8445 }
Kevin Rocard069c2712018-03-29 19:09:14 -07008446 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +01008447 record_track_metadata_v7_t trackMetadata;
8448 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -07008449 .source = track->attributes().source,
8450 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +01008451 };
8452 trackMetadata.channel_mask = track->channelMask(),
8453 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
8454
8455 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -07008456 }
8457 mInput->stream->updateSinkMetadata(metadata);
8458}
8459
Eric Laurent81784c32012-11-19 14:55:58 -08008460// destroyTrack_l() must be called with ThreadBase::mLock held
8461void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
8462{
Eric Laurentbfb1b832013-01-07 09:53:42 -08008463 track->terminate();
8464 track->mState = TrackBase::STOPPED;
Eric Laurentec376dc2021-04-08 20:41:22 +02008465
Eric Laurent81784c32012-11-19 14:55:58 -08008466 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08008467 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08008468 removeTrack_l(track);
8469 }
8470}
8471
8472void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
8473{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008474 String8 result;
8475 track->appendDump(result, false /* active */);
8476 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
8477
Eric Laurent81784c32012-11-19 14:55:58 -08008478 mTracks.remove(track);
8479 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008480 if (track->isFastTrack()) {
8481 ALOG_ASSERT(!mFastTrackAvail);
8482 mFastTrackAvail = true;
8483 }
Eric Laurent81784c32012-11-19 14:55:58 -08008484}
8485
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008486void AudioFlinger::RecordThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008487{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07008488 AudioStreamIn *input = mInput;
8489 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
8490 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08008491 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07008492 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07008493 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008494 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008495 }
Andy Hungbfa64962017-06-12 14:43:19 -07008496
8497 if (input != nullptr) {
8498 dprintf(fd, " Hal stream dump:\n");
8499 (void)input->stream->dump(fd);
8500 }
8501
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008502 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008503 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08008504
Glenn Kasten2f90c512015-12-02 11:40:09 -08008505 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
8506 // while we are dumping it. It may be inconsistent, but it won't mutate!
8507 // This is a large object so we place it on the heap.
8508 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07008509 const std::unique_ptr<FastCaptureDumpState> copy =
8510 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08008511 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08008512}
8513
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008514void AudioFlinger::RecordThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008515{
Eric Laurent81784c32012-11-19 14:55:58 -08008516 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08008517 size_t numtracks = mTracks.size();
8518 size_t numactive = mActiveTracks.size();
8519 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008520 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008521 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08008522 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008523 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008524 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008525 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008526 for (size_t i = 0; i < numtracks ; ++i) {
8527 sp<RecordTrack> track = mTracks[i];
8528 if (track != 0) {
8529 bool active = mActiveTracks.indexOf(track) >= 0;
8530 if (active) {
8531 numactiveseen++;
8532 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008533 result.append(prefix);
8534 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08008535 }
Eric Laurent81784c32012-11-19 14:55:58 -08008536 }
Marco Nelissenb2208842014-02-07 14:00:50 -08008537 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008538 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008539 }
8540
Marco Nelissenb2208842014-02-07 14:00:50 -08008541 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008542 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08008543 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008544 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008545 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008546 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08008547 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08008548 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008549 result.append(prefix);
8550 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08008551 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008552 }
Eric Laurent81784c32012-11-19 14:55:58 -08008553
8554 }
8555 write(fd, result.string(), result.size());
8556}
8557
Eric Laurent5ada82e2019-08-29 17:53:54 -07008558void AudioFlinger::RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008559{
8560 Mutex::Autolock _l(mLock);
8561 for (size_t i = 0; i < mTracks.size() ; i++) {
8562 sp<RecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07008563 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008564 track->setSilenced(silenced);
8565 }
8566 }
8567}
Andy Hung73c02e42015-03-29 01:13:58 -07008568
8569void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
8570{
8571 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8572 RecordThread *recordThread = (RecordThread *) threadBase.get();
Andy Hung73c02e42015-03-29 01:13:58 -07008573 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02008574 const int32_t rear = recordThread->mRsmpInRear;
8575 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02008576 if (mRecordTrack->startFrames() >= 0) {
8577 int32_t startFrames = mRecordTrack->startFrames();
8578 // Accept a recent wraparound of mRsmpInRear
8579 if (startFrames <= rear) {
8580 deltaFrames = rear - startFrames;
8581 } else {
8582 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02008583 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008584 // start frame cannot be further in the past than start of resampling buffer
8585 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
8586 deltaFrames = recordThread->mRsmpInFrames;
8587 }
8588 }
8589 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07008590}
8591
8592void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
8593 size_t *framesAvailable, bool *hasOverrun)
8594{
8595 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8596 RecordThread *recordThread = (RecordThread *) threadBase.get();
8597 const int32_t rear = recordThread->mRsmpInRear;
8598 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008599 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07008600
8601 size_t framesIn;
8602 bool overrun = false;
8603 if (filled < 0) {
8604 // should not happen, but treat like a massive overrun and re-sync
8605 framesIn = 0;
8606 mRsmpInFront = rear;
8607 overrun = true;
8608 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
8609 framesIn = (size_t) filled;
8610 } else {
8611 // client is not keeping up with server, but give it latest data
8612 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07008613 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
8614 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07008615 overrun = true;
8616 }
8617 if (framesAvailable != NULL) {
8618 *framesAvailable = framesIn;
8619 }
8620 if (hasOverrun != NULL) {
8621 *hasOverrun = overrun;
8622 }
8623}
8624
Eric Laurent81784c32012-11-19 14:55:58 -08008625// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008626status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08008627 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008628{
Andy Hung73c02e42015-03-29 01:13:58 -07008629 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008630 if (threadBase == 0) {
8631 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008632 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008633 return NOT_ENOUGH_DATA;
8634 }
8635 RecordThread *recordThread = (RecordThread *) threadBase.get();
8636 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07008637 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008638 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008639 // FIXME should not be P2 (don't want to increase latency)
8640 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008641 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07008642 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008643
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008644 front &= recordThread->mRsmpInFramesP2 - 1;
8645 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07008646 if (part1 > (size_t) filled) {
8647 part1 = filled;
8648 }
8649 size_t ask = buffer->frameCount;
8650 ALOG_ASSERT(ask > 0);
8651 if (part1 > ask) {
8652 part1 = ask;
8653 }
8654 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07008655 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07008656 buffer->raw = NULL;
8657 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07008658 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07008659 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08008660 }
8661
Andy Hung57446612015-04-19 23:56:46 -07008662 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07008663 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07008664 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08008665 return NO_ERROR;
8666}
8667
8668// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008669void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
8670 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008671{
Hongwei Wang95e37682019-04-12 11:13:36 -07008672 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008673 if (stepCount == 0) {
8674 return;
8675 }
Andy Hung73c02e42015-03-29 01:13:58 -07008676 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
8677 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07008678 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008679 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08008680 buffer->frameCount = 0;
8681}
8682
Eric Laurentd8365c52017-07-16 15:27:05 -07008683void AudioFlinger::RecordThread::checkBtNrec()
8684{
8685 Mutex::Autolock _l(mLock);
8686 checkBtNrec_l();
8687}
8688
8689void AudioFlinger::RecordThread::checkBtNrec_l()
8690{
8691 // disable AEC and NS if the device is a BT SCO headset supporting those
8692 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07008693 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Eric Laurentd8365c52017-07-16 15:27:05 -07008694 mAudioFlinger->btNrecIsOff();
8695 if (mBtNrecSuspended.exchange(suspend) != suspend) {
8696 for (size_t i = 0; i < mEffectChains.size(); i++) {
8697 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
8698 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
8699 }
8700 }
8701}
8702
Andy Hung97a893e2015-03-29 01:03:07 -07008703
Eric Laurent10351942014-05-08 18:49:52 -07008704bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
8705 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08008706{
8707 bool reconfig = false;
8708
Eric Laurent10351942014-05-08 18:49:52 -07008709 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08008710
Eric Laurent10351942014-05-08 18:49:52 -07008711 audio_format_t reqFormat = mFormat;
8712 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07008713 // TODO this may change if we want to support capture from HDMI PCM multi channel (e.g on TVs).
Eric Laurent10351942014-05-08 18:49:52 -07008714 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
8715
8716 AudioParameter param = AudioParameter(keyValuePair);
8717 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07008718
8719 // scope for AutoPark extends to end of method
8720 AutoPark<FastCapture> park(mFastCapture);
8721
Eric Laurent10351942014-05-08 18:49:52 -07008722 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
8723 // channel count change can be requested. Do we mandate the first client defines the
8724 // HAL sampling rate and channel count or do we allow changes on the fly?
8725 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
8726 samplingRate = value;
8727 reconfig = true;
8728 }
8729 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07008730 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07008731 status = BAD_VALUE;
8732 } else {
8733 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08008734 reconfig = true;
8735 }
Eric Laurent10351942014-05-08 18:49:52 -07008736 }
8737 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
8738 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07008739 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07008740 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07008741 status = BAD_VALUE;
8742 } else {
8743 channelMask = mask;
8744 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008745 }
Eric Laurent10351942014-05-08 18:49:52 -07008746 }
8747 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
8748 // do not accept frame count changes if tracks are open as the track buffer
8749 // size depends on frame count and correct behavior would not be guaranteed
8750 // if frame count is changed after track creation
8751 if (mActiveTracks.size() > 0) {
8752 status = INVALID_OPERATION;
8753 } else {
8754 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008755 }
Eric Laurent10351942014-05-08 18:49:52 -07008756 }
8757 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07008758 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008759 }
8760 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
8761 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07008762 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008763 }
Glenn Kastene198c362013-08-13 09:13:36 -07008764
Eric Laurent10351942014-05-08 18:49:52 -07008765 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008766 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008767 if (status == INVALID_OPERATION) {
8768 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008769 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008770 }
8771 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008772 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00008773 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
8774 if (mInput->stream->getAudioProperties(&config) == OK &&
8775 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
8776 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07008777 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008778 status = NO_ERROR;
8779 }
Eric Laurent81784c32012-11-19 14:55:58 -08008780 }
Eric Laurent10351942014-05-08 18:49:52 -07008781 if (status == NO_ERROR) {
8782 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07008783 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08008784 }
8785 }
Eric Laurent81784c32012-11-19 14:55:58 -08008786 }
Eric Laurent10351942014-05-08 18:49:52 -07008787
Eric Laurent81784c32012-11-19 14:55:58 -08008788 return reconfig;
8789}
8790
8791String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
8792{
Eric Laurent81784c32012-11-19 14:55:58 -08008793 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008794 if (initCheck() == NO_ERROR) {
8795 String8 out_s8;
8796 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
8797 return out_s8;
8798 }
Eric Laurent81784c32012-11-19 14:55:58 -08008799 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008800 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08008801}
8802
Mikhail Naganov88536df2021-07-26 17:30:29 -07008803void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008804 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07008805 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08008806 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008807 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008808 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07008809 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07008810 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
8811 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08008812 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07008813 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07008814 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07008815 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07008816 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08008817 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07008818 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08008819 break;
8820 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07008821 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08008822}
8823
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008824void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008825{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008826 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8827 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07008828 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008829 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8830 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07008831 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
8832 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008833 } else {
Andy Hung936845a2021-06-08 00:09:06 -07008834 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008835 ALOGI("HAL format %#x is not linear pcm", mFormat);
8836 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008837 result = mInput->stream->getFrameSize(&mFrameSize);
8838 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008839 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
8840 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008841 result = mInput->stream->getBufferSize(&mBufferSize);
8842 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08008843 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008844 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
8845 "mBufferSize=%zu, mFrameCount=%zu",
8846 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008847
Eric Laurentec376dc2021-04-08 20:41:22 +02008848 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
8849 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008850 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08008851
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008852 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
8853 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07008854
8855 audio_input_flags_t flags = mInput->flags;
8856 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
8857 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
8858 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
8859 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
8860 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
8861 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
8862 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
8863 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
8864 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08008865}
8866
Glenn Kasten5f972c02014-01-13 09:59:31 -08008867uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08008868{
8869 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008870 uint32_t result;
8871 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
8872 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08008873 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008874 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008875}
8876
Glenn Kastend848eb42016-03-08 13:42:11 -08008877KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08008878{
Glenn Kastend848eb42016-03-08 13:42:11 -08008879 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08008880 Mutex::Autolock _l(mLock);
8881 for (size_t j = 0; j < mTracks.size(); ++j) {
8882 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08008883 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08008884 if (ids.indexOfKey(sessionId) < 0) {
8885 ids.add(sessionId, true);
8886 }
8887 }
8888 return ids;
8889}
8890
8891AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
8892{
8893 Mutex::Autolock _l(mLock);
8894 AudioStreamIn *input = mInput;
8895 mInput = NULL;
8896 return input;
8897}
8898
8899// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008900sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08008901{
8902 if (mInput == NULL) {
8903 return NULL;
8904 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008905 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08008906}
8907
8908status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8909{
Eric Laurent81784c32012-11-19 14:55:58 -08008910 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07008911 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08008912 chain->setInBuffer(NULL);
8913 chain->setOutBuffer(NULL);
8914
8915 checkSuspendOnAddEffectChain_l(chain);
8916
Eric Laurent1b928682014-10-02 19:41:47 -07008917 // make sure enabled pre processing effects state is communicated to the HAL as we
8918 // just moved them to a new input stream.
8919 chain->syncHalEffectsState();
8920
Eric Laurent81784c32012-11-19 14:55:58 -08008921 mEffectChains.add(chain);
8922
8923 return NO_ERROR;
8924}
8925
8926size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8927{
8928 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008929
8930 for (size_t i = 0; i < mEffectChains.size(); i++) {
8931 if (chain == mEffectChains[i]) {
8932 mEffectChains.removeAt(i);
8933 break;
8934 }
Eric Laurent81784c32012-11-19 14:55:58 -08008935 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008936 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08008937}
8938
Eric Laurent1c333e22014-05-20 10:48:17 -07008939status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
8940 audio_patch_handle_t *handle)
8941{
8942 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008943
8944 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07008945 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07008946 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02008947 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07008948 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08008949 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07008950 }
8951
Eric Laurentd8365c52017-07-16 15:27:05 -07008952 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07008953
8954 // store new source and send to effects
8955 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8956 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07008957 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07008958 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07008959 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008960 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008961
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008962 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008963 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8964 status = hwDevice->createAudioPatch(patch->num_sources,
8965 patch->sources,
8966 patch->num_sinks,
8967 patch->sinks,
8968 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008969 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008970 char *address;
8971 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
8972 address = audio_device_address_to_parameter(
8973 patch->sources[0].ext.device.type,
8974 patch->sources[0].ext.device.address);
8975 } else {
8976 address = (char *)calloc(1, 1);
8977 }
8978 AudioParameter param = AudioParameter(String8(address));
8979 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008980 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07008981 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008982 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07008983 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008984 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07008985 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07008986 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008987
jiabinc52b1ff2019-10-31 17:20:42 -07008988 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07008989 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07008990 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07008991 }
Eric Laurent296fb132015-05-01 11:38:42 -07008992
Andy Hungc2b11cb2020-04-22 09:04:01 -07008993 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07008994 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07008995 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07008996 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07008997 // also dispatch to active AudioRecords
8998 for (const auto &track : mActiveTracks) {
8999 track->logEndInterval();
9000 track->logBeginInterval(pathSourcesAsString);
9001 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009002 return status;
9003}
9004
9005status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9006{
9007 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009008
jiabinc52b1ff2019-10-31 17:20:42 -07009009 mPatch = audio_patch{};
9010 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009011
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009012 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009013 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9014 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009015 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07009016 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07009017 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009018 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07009019 }
9020 return status;
9021}
9022
jiabinc52b1ff2019-10-31 17:20:42 -07009023void AudioFlinger::RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
9024{
wendy lin56aa82b2020-12-02 15:19:55 +08009025 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07009026 mOutDevices = outDevices;
9027 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9028 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009029 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009030 }
9031}
9032
Eric Laurentec376dc2021-04-08 20:41:22 +02009033int32_t AudioFlinger::RecordThread::getOldestFront_l()
9034{
9035 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009036 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009037 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009038 int32_t oldestFront = mRsmpInRear;
9039 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009040 for (size_t i = 0; i < mTracks.size(); i++) {
Eric Laurent2407ce32021-04-26 14:56:03 +02009041 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
9042 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009043 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009044 if (filled > maxFilled) {
9045 oldestFront = front;
9046 maxFilled = filled;
9047 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009048 }
Eric Laurent92d0a322021-07-16 15:32:33 +02009049 if (maxFilled > mRsmpInFrames) {
9050 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9051 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009052 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009053}
9054
9055void AudioFlinger::RecordThread::updateFronts_l(int32_t offset)
9056{
9057 if (offset == 0) {
9058 return;
9059 }
9060 for (size_t i = 0; i < mTracks.size(); i++) {
9061 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
9062 front = audio_utils::safe_sub_overflow(front, offset);
9063 mTracks[i]->mResamplerBufferProvider->setFront(front);
9064 }
9065}
9066
9067void AudioFlinger::RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
9068{
9069 // This is the formula for calculating the temporary buffer size.
9070 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9071 // 1 full output buffer, regardless of the alignment of the available input.
9072 // The value is somewhat arbitrary, and could probably be even larger.
9073 // A larger value should allow more old data to be read after a track calls start(),
9074 // without increasing latency.
9075 //
9076 // Note this is independent of the maximum downsampling ratio permitted for capture.
9077 size_t minRsmpInFrames = mFrameCount * 7;
9078
9079 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9080 // capture history available to another client using the same session ID:
9081 // dimension the resampler input buffer accordingly.
9082
9083 // Get oldest client read position: getOldestFront_l() must be called before altering
9084 // mRsmpInRear, or mRsmpInFrames
9085 int32_t previousFront = getOldestFront_l();
9086 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9087 int32_t previousRear = mRsmpInRear;
9088 mRsmpInRear = 0;
9089
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009090 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
9091 && maxSharedAudioHistoryMs <= AudioFlinger::kMaxSharedAudioHistoryMs,
9092 "resizeInputBuffer_l() called with invalid max shared history %d",
9093 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009094 if (maxSharedAudioHistoryMs != 0) {
9095 // resizeInputBuffer_l should never be called with a non zero shared history if the
9096 // buffer was not already allocated
9097 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9098 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9099 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9100 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009101 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009102 return;
9103 }
9104 mRsmpInFrames = rsmpInFrames;
9105 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009106 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009107 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9108 // initialized
9109 if (mRsmpInFrames < minRsmpInFrames) {
9110 mRsmpInFrames = minRsmpInFrames;
9111 }
9112 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9113
9114 // TODO optimize audio capture buffer sizes ...
9115 // Here we calculate the size of the sliding buffer used as a source
9116 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9117 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9118 // be better to have it derived from the pipe depth in the long term.
9119 // The current value is higher than necessary. However it should not add to latency.
9120
9121 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9122 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9123
9124 void *rsmpInBuffer;
9125 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9126 // if posix_memalign fails, will segv here.
9127 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9128
9129 // Copy audio history if any from old buffer before freeing it
9130 if (previousRear != 0) {
9131 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9132 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9133
9134 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9135 previousFront &= previousRsmpInFramesP2 - 1;
9136 size_t part1 = previousRsmpInFramesP2 - previousFront;
9137 if (part1 > (size_t) unread) {
9138 part1 = unread;
9139 }
9140 if (part1 != 0) {
9141 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9142 part1 * mFrameSize);
9143 mRsmpInRear = part1;
9144 part1 = unread - part1;
9145 if (part1 != 0) {
9146 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9147 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9148 mRsmpInRear += part1;
9149 }
9150 }
9151 // Update front for all clients according to new rear
9152 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9153 } else {
9154 mRsmpInRear = 0;
9155 }
9156 free(mRsmpInBuffer);
9157 mRsmpInBuffer = rsmpInBuffer;
9158}
9159
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009160void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009161{
9162 Mutex::Autolock _l(mLock);
9163 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009164 if (record->getSource()) {
9165 mSource = record->getSource();
9166 }
Eric Laurent83b88082014-06-20 18:31:16 -07009167}
9168
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009169void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009170{
9171 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009172 if (mSource == record->getSource()) {
9173 mSource = mInput;
9174 }
Eric Laurent83b88082014-06-20 18:31:16 -07009175 destroyTrack_l(record);
9176}
9177
Mikhail Naganovdc769682018-05-04 15:34:08 -07009178void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07009179{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009180 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009181 config->role = AUDIO_PORT_ROLE_SINK;
9182 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9183 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009184 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9185 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9186 config->flags.input = mInput->flags;
9187 }
Eric Laurent83b88082014-06-20 18:31:16 -07009188}
Eric Laurent1c333e22014-05-20 10:48:17 -07009189
Eric Laurent6acd1d42017-01-04 14:23:29 -08009190// ----------------------------------------------------------------------------
9191// Mmap
9192// ----------------------------------------------------------------------------
9193
9194AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
9195 : mThread(thread)
9196{
Phil Burk9fabbf82017-08-03 12:02:00 -07009197 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009198}
9199
9200AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
9201{
Phil Burk9fabbf82017-08-03 12:02:00 -07009202 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009203}
9204
9205status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
9206 struct audio_mmap_buffer_info *info)
9207{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009208 return mThread->createMmapBuffer(minSizeFrames, info);
9209}
9210
9211status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
9212{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009213 return mThread->getMmapPosition(position);
9214}
9215
jiabinb7d8c5a2020-08-26 17:24:52 -07009216status_t AudioFlinger::MmapThreadHandle::getExternalPosition(uint64_t *position,
9217 int64_t *timeNanos) {
9218 return mThread->getExternalPosition(position, timeNanos);
9219}
9220
Eric Laurenta54f1282017-07-01 19:39:32 -07009221status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009222 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009223
9224{
jiabind1f1cb62020-03-24 11:57:57 -07009225 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009226}
9227
9228status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
9229{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009230 return mThread->stop(handle);
9231}
9232
Eric Laurent18b57012017-02-13 16:23:52 -08009233status_t AudioFlinger::MmapThreadHandle::standby()
9234{
Eric Laurent18b57012017-02-13 16:23:52 -08009235 return mThread->standby();
9236}
9237
Eric Laurent6acd1d42017-01-04 14:23:29 -08009238
9239AudioFlinger::MmapThread::MmapThread(
9240 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -07009241 AudioHwDevice *hwDev, sp<StreamHalInterface> stream, bool systemReady, bool isOut)
Andy Hungea840382020-05-05 21:50:17 -07009242 : ThreadBase(audioFlinger, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009243 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009244 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009245 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009246 mActiveTracks(&this->mLocalLog),
9247 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9248 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009249{
Eric Laurent18b57012017-02-13 16:23:52 -08009250 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009251 readHalParameters_l();
9252}
9253
9254AudioFlinger::MmapThread::~MmapThread()
9255{
9256}
9257
9258void AudioFlinger::MmapThread::onFirstRef()
9259{
9260 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9261}
9262
9263void AudioFlinger::MmapThread::disconnect()
9264{
Eric Laurent331679c2018-04-16 17:03:16 -07009265 ActiveTracks<MmapTrack> activeTracks;
9266 {
9267 Mutex::Autolock _l(mLock);
9268 for (const sp<MmapTrack> &t : mActiveTracks) {
9269 activeTracks.add(t);
9270 }
9271 }
9272 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009273 stop(t->portId());
9274 }
Phil Burk9fabbf82017-08-03 12:02:00 -07009275 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009276 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009277 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009278 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009279 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009280 }
9281}
9282
9283
9284void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
9285 audio_stream_type_t streamType __unused,
9286 audio_session_t sessionId,
9287 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009288 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009289 audio_port_handle_t portId)
9290{
9291 mAttr = *attr;
9292 mSessionId = sessionId;
9293 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009294 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009295 mPortId = portId;
9296}
9297
9298status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
9299 struct audio_mmap_buffer_info *info)
9300{
9301 if (mHalStream == 0) {
9302 return NO_INIT;
9303 }
Eric Laurent18b57012017-02-13 16:23:52 -08009304 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009305 return mHalStream->createMmapBuffer(minSizeFrames, info);
9306}
9307
9308status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
9309{
9310 if (mHalStream == 0) {
9311 return NO_INIT;
9312 }
9313 return mHalStream->getMmapPosition(position);
9314}
9315
Eric Laurent331679c2018-04-16 17:03:16 -07009316status_t AudioFlinger::MmapThread::exitStandby()
9317{
9318 status_t ret = mHalStream->start();
9319 if (ret != NO_ERROR) {
9320 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
9321 return ret;
9322 }
Andy Hungcf10d742020-04-28 15:38:24 -07009323 if (mStandby) {
9324 mThreadMetrics.logBeginInterval();
9325 mStandby = false;
9326 }
Eric Laurent331679c2018-04-16 17:03:16 -07009327 return NO_ERROR;
9328}
9329
Eric Laurenta54f1282017-07-01 19:39:32 -07009330status_t AudioFlinger::MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009331 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009332 audio_port_handle_t *handle)
9333{
Eric Laurenta54f1282017-07-01 19:39:32 -07009334 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +00009335 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009336 if (mHalStream == 0) {
9337 return NO_INIT;
9338 }
9339
9340 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009341
Eric Laurenta54f1282017-07-01 19:39:32 -07009342 if (*handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +00009343 // For the first track, reuse portId and session allocated when the stream was opened.
9344 ret = exitStandby();
9345 if (ret == NO_ERROR) {
9346 acquireWakeLock();
9347 }
9348 return ret;
Eric Laurenta54f1282017-07-01 19:39:32 -07009349 }
9350
9351 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
9352
9353 audio_io_handle_t io = mId;
9354 if (isOutput()) {
9355 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9356 config.sample_rate = mSampleRate;
9357 config.channel_mask = mChannelMask;
9358 config.format = mFormat;
9359 audio_stream_type_t stream = streamType();
9360 audio_output_flags_t flags =
9361 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009362 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08009363 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurenta54f1282017-07-01 19:39:32 -07009364 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
9365 mSessionId,
9366 &stream,
Svet Ganov33761132021-05-13 22:51:08 +00009367 client.attributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -07009368 &config,
9369 flags,
9370 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08009371 &portId,
9372 &secondaryOutputs);
9373 ALOGD_IF(!secondaryOutputs.empty(),
9374 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009375 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07009376 audio_config_base_t config;
9377 config.sample_rate = mSampleRate;
9378 config.channel_mask = mChannelMask;
9379 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009380 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07009381 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -07009382 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -07009383 mSessionId,
Svet Ganov33761132021-05-13 22:51:08 +00009384 client.attributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -07009385 &config,
9386 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
9387 &deviceId,
9388 &portId);
9389 }
9390 // APM should not chose a different input or output stream for the same set of attributes
9391 // and audo configuration
9392 if (ret != NO_ERROR || io != mId) {
9393 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
9394 __FUNCTION__, ret, io, mId);
9395 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009396 }
9397
9398 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009399 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009400 } else {
Eric Laurent4eb58f12018-12-07 16:41:02 -08009401 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009402 }
9403
Eric Laurent331679c2018-04-16 17:03:16 -07009404 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009405 // abort if start is rejected by audio policy manager
9406 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009407 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07009408 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07009409 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009410 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009411 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009412 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009413 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009414 }
Eric Laurent331679c2018-04-16 17:03:16 -07009415 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08009416 } else {
9417 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009418 }
9419 return PERMISSION_DENIED;
9420 }
9421
Kevin Rocard1f564ac2018-03-29 13:53:10 -07009422 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
jiabind1f1cb62020-03-24 11:57:57 -07009423 sp<MmapTrack> track = new MmapTrack(this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +00009424 mChannelMask, mSessionId, isOutput(),
9425 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009426 IPCThreadState::self()->getCallingPid(), portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009427
Eric Laurent4eb58f12018-12-07 16:41:02 -08009428 if (isOutput()) {
9429 // force volume update when a new track is added
9430 mHalVolFloat = -1.0f;
9431 } else if (!track->isSilenced_l()) {
9432 for (const sp<MmapTrack> &t : mActiveTracks) {
Svet Ganov33761132021-05-13 22:51:08 +00009433 if (t->isSilenced_l() && t->uid() != client.attributionSource.uid)
Eric Laurent4eb58f12018-12-07 16:41:02 -08009434 t->invalidate();
9435 }
9436 }
9437
9438
Eric Laurent6acd1d42017-01-04 14:23:29 -08009439 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07009440 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009441 if (chain != 0) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02009442 chain->setStrategy(getStrategyForStream(streamType()));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009443 chain->incTrackCnt();
9444 chain->incActiveTrackCnt();
9445 }
9446
Andy Hungc2b11cb2020-04-22 09:04:01 -07009447 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -08009448 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009449 broadcast_l();
9450
Eric Laurenta54f1282017-07-01 19:39:32 -07009451 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009452
9453 return NO_ERROR;
9454}
9455
9456status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
9457{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009458 ALOGV("%s handle %d", __FUNCTION__, handle);
9459
9460 if (mHalStream == 0) {
9461 return NO_INIT;
9462 }
9463
Eric Laurenta54f1282017-07-01 19:39:32 -07009464 if (handle == mPortId) {
9465 mHalStream->stop();
Phil Burk98ab4082020-09-25 21:46:34 +00009466 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -07009467 return NO_ERROR;
9468 }
9469
Eric Laurent331679c2018-04-16 17:03:16 -07009470 Mutex::Autolock _l(mLock);
9471
Eric Laurent6acd1d42017-01-04 14:23:29 -08009472 sp<MmapTrack> track;
9473 for (const sp<MmapTrack> &t : mActiveTracks) {
9474 if (handle == t->portId()) {
9475 track = t;
9476 break;
9477 }
9478 }
9479 if (track == 0) {
9480 return BAD_VALUE;
9481 }
9482
9483 mActiveTracks.remove(track);
9484
Eric Laurent331679c2018-04-16 17:03:16 -07009485 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009486 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009487 AudioSystem::stopOutput(track->portId());
9488 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009489 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009490 AudioSystem::stopInput(track->portId());
9491 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009492 }
Eric Laurent331679c2018-04-16 17:03:16 -07009493 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009494
9495 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
9496 if (chain != 0) {
9497 chain->decActiveTrackCnt();
9498 chain->decTrackCnt();
9499 }
9500
9501 broadcast_l();
9502
Eric Laurent6acd1d42017-01-04 14:23:29 -08009503 return NO_ERROR;
9504}
9505
Eric Laurent18b57012017-02-13 16:23:52 -08009506status_t AudioFlinger::MmapThread::standby()
9507{
9508 ALOGV("%s", __FUNCTION__);
9509
9510 if (mHalStream == 0) {
9511 return NO_INIT;
9512 }
Eric Tan39ec8d62018-07-24 09:49:29 -07009513 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08009514 return INVALID_OPERATION;
9515 }
9516 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07009517 if (!mStandby) {
9518 mThreadMetrics.logEndInterval();
9519 mStandby = true;
9520 }
Eric Laurent18b57012017-02-13 16:23:52 -08009521 releaseWakeLock();
9522 return NO_ERROR;
9523}
9524
Eric Laurent6acd1d42017-01-04 14:23:29 -08009525
9526void AudioFlinger::MmapThread::readHalParameters_l()
9527{
9528 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9529 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
9530 mFormat = mHALFormat;
9531 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
9532 result = mHalStream->getFrameSize(&mFrameSize);
9533 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009534 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9535 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009536 result = mHalStream->getBufferSize(&mBufferSize);
9537 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
9538 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -07009539
Andy Hungcf10d742020-04-28 15:38:24 -07009540 // TODO: make a readHalParameters call?
9541 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -07009542 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9543 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9544 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9545 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9546 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9547 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9548 /*
9549 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9550 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
9551 (int32_t)mHapticChannelMask)
9552 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
9553 (int32_t)mHapticChannelCount)
9554 */
9555 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
9556 formatToString(mHALFormat).c_str())
9557 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
9558 (int32_t)mFrameCount) // sic - added HAL
9559 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009560}
9561
9562bool AudioFlinger::MmapThread::threadLoop()
9563{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009564 checkSilentMode_l();
9565
9566 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
9567
9568 while (!exitPending())
9569 {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009570 Vector< sp<EffectChain> > effectChains;
9571
Andy Hung13850be2019-03-14 11:33:09 -07009572 { // under Thread lock
9573 Mutex::Autolock _l(mLock);
9574
Eric Laurent6acd1d42017-01-04 14:23:29 -08009575 if (mSignalPending) {
9576 // A signal was raised while we were unlocked
9577 mSignalPending = false;
9578 } else {
9579 if (mConfigEvents.isEmpty()) {
9580 // we're about to wait, flush the binder command buffer
9581 IPCThreadState::self()->flushCommands();
9582
9583 if (exitPending()) {
9584 break;
9585 }
9586
Eric Laurent6acd1d42017-01-04 14:23:29 -08009587 // wait until we have something to do...
9588 ALOGV("%s going to sleep", myName.string());
9589 mWaitWorkCV.wait(mLock);
9590 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009591
9592 checkSilentMode_l();
9593
9594 continue;
9595 }
9596 }
9597
9598 processConfigEvents_l();
9599
9600 processVolume_l();
9601
9602 checkInvalidTracks_l();
9603
9604 mActiveTracks.updatePowerState(this);
9605
Kevin Rocard069c2712018-03-29 19:09:14 -07009606 updateMetadata_l();
9607
Eric Laurent6acd1d42017-01-04 14:23:29 -08009608 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -07009609 } // release Thread lock
9610
Eric Laurent6acd1d42017-01-04 14:23:29 -08009611 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -07009612 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -08009613 }
Andy Hung13850be2019-03-14 11:33:09 -07009614
9615 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009616 unlockEffectChains(effectChains);
9617 // Effect chains will be actually deleted here if they were removed from
9618 // mEffectChains list during mixing or effects processing
9619 }
9620
9621 threadLoop_exit();
9622
9623 if (!mStandby) {
9624 threadLoop_standby();
9625 mStandby = true;
9626 }
9627
Eric Laurent6acd1d42017-01-04 14:23:29 -08009628 ALOGV("Thread %p type %d exiting", this, mType);
9629 return false;
9630}
9631
9632// checkForNewParameter_l() must be called with ThreadBase::mLock held
9633bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
9634 status_t& status)
9635{
9636 AudioParameter param = AudioParameter(keyValuePair);
9637 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07009638 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009639 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009640 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009641 }
Eric Laurente6e9a482017-07-25 19:26:02 -07009642 if (sendToHal) {
9643 status = mHalStream->setParameters(keyValuePair);
9644 } else {
9645 status = NO_ERROR;
9646 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009647
9648 return false;
9649}
9650
9651String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
9652{
9653 Mutex::Autolock _l(mLock);
9654 String8 out_s8;
9655 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
9656 return out_s8;
9657 }
9658 return String8();
9659}
9660
Mikhail Naganov88536df2021-07-26 17:30:29 -07009661void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009662 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009663 sp<AudioIoDescriptor> desc;
9664 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009665 switch (event) {
9666 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009667 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009668 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009669 isInput = true;
9670 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009671 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009672 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009673 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009674 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
9675 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009676 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009677 case AUDIO_INPUT_CLOSED:
9678 case AUDIO_OUTPUT_CLOSED:
9679 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009680 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009681 break;
9682 }
9683 mAudioFlinger->ioConfigChanged(event, desc, pid);
9684}
9685
9686status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
9687 audio_patch_handle_t *handle)
9688{
9689 status_t status = NO_ERROR;
9690
9691 // store new device and send to effects
9692 audio_devices_t type = AUDIO_DEVICE_NONE;
9693 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -07009694 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
9695 AudioDeviceTypeAddr sourceDeviceTypeAddr;
9696 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009697 if (isOutput()) {
9698 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07009699 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
9700 && !mAudioHwDev->supportsAudioPatches(),
9701 "Enumerated device type(%#x) must not be used "
9702 "as it does not support audio patches",
9703 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07009704 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07009705 sinkDeviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
9706 patch->sinks[i].ext.device.address));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009707 }
9708 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009709 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009710 } else {
9711 type = patch->sources[0].ext.device.type;
9712 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009713 numDevices = mPatch.num_sources;
9714 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009715 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009716 }
9717
9718 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009719 if (isOutput()) {
9720 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
9721 } else {
9722 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
9723 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009724 }
9725
jiabinc52b1ff2019-10-31 17:20:42 -07009726 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009727 // store new source and send to effects
9728 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9729 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
9730 for (size_t i = 0; i < mEffectChains.size(); i++) {
9731 mEffectChains[i]->setAudioSource_l(mAudioSource);
9732 }
9733 }
9734 }
9735
9736 if (mAudioHwDev->supportsAudioPatches()) {
9737 status = mHalDevice->createAudioPatch(patch->num_sources,
9738 patch->sources,
9739 patch->num_sinks,
9740 patch->sinks,
9741 handle);
9742 } else {
9743 char *address;
9744 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
9745 //FIXME: we only support address on first sink with HAL version < 3.0
9746 address = audio_device_address_to_parameter(
9747 patch->sinks[0].ext.device.type,
9748 patch->sinks[0].ext.device.address);
9749 } else {
9750 address = (char *)calloc(1, 1);
9751 }
9752 AudioParameter param = AudioParameter(String8(address));
9753 free(address);
9754 param.addInt(String8(AudioParameter::keyRouting), (int)type);
9755 if (!isOutput()) {
9756 param.addInt(String8(AudioParameter::keyInputSource),
9757 (int)patch->sinks[0].ext.mix.usecase.source);
9758 }
9759 status = mHalStream->setParameters(param.toString());
9760 *handle = AUDIO_PATCH_HANDLE_NONE;
9761 }
9762
jiabinc52b1ff2019-10-31 17:20:42 -07009763 if (numDevices == 0 || mDeviceId != deviceId) {
9764 if (isOutput()) {
9765 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
9766 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07009767 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -07009768 } else {
9769 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
9770 mInDeviceTypeAddr = sourceDeviceTypeAddr;
9771 }
Phil Burk7f6b40d2017-02-09 13:18:38 -08009772 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009773 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009774 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08009775 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07009776 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009777 }
jiabinc52b1ff2019-10-31 17:20:42 -07009778 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009779 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009780 }
9781 return status;
9782}
9783
9784status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9785{
9786 status_t status = NO_ERROR;
9787
jiabinc52b1ff2019-10-31 17:20:42 -07009788 mPatch = audio_patch{};
9789 mOutDeviceTypeAddrs.clear();
9790 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009791
9792 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
9793 supportsAudioPatches : false;
9794
9795 if (supportsAudioPatches) {
9796 status = mHalDevice->releaseAudioPatch(handle);
9797 } else {
9798 AudioParameter param;
9799 param.addInt(String8(AudioParameter::keyRouting), 0);
9800 status = mHalStream->setParameters(param.toString());
9801 }
9802 return status;
9803}
9804
Mikhail Naganovdc769682018-05-04 15:34:08 -07009805void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009806{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009807 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009808 if (isOutput()) {
9809 config->role = AUDIO_PORT_ROLE_SOURCE;
9810 config->ext.mix.hw_module = mAudioHwDev->handle();
9811 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
9812 } else {
9813 config->role = AUDIO_PORT_ROLE_SINK;
9814 config->ext.mix.hw_module = mAudioHwDev->handle();
9815 config->ext.mix.usecase.source = mAudioSource;
9816 }
9817}
9818
9819status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
9820{
9821 audio_session_t session = chain->sessionId();
9822
9823 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
9824 // Attach all tracks with same session ID to this chain.
9825 // indicate all active tracks in the chain
9826 for (const sp<MmapTrack> &track : mActiveTracks) {
9827 if (session == track->sessionId()) {
9828 chain->incTrackCnt();
9829 chain->incActiveTrackCnt();
9830 }
9831 }
9832
9833 chain->setThread(this);
9834 chain->setInBuffer(nullptr);
9835 chain->setOutBuffer(nullptr);
9836 chain->syncHalEffectsState();
9837
9838 mEffectChains.add(chain);
9839 checkSuspendOnAddEffectChain_l(chain);
9840 return NO_ERROR;
9841}
9842
9843size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
9844{
9845 audio_session_t session = chain->sessionId();
9846
9847 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
9848
9849 for (size_t i = 0; i < mEffectChains.size(); i++) {
9850 if (chain == mEffectChains[i]) {
9851 mEffectChains.removeAt(i);
9852 // detach all active tracks from the chain
9853 // detach all tracks with same session ID from this chain
9854 for (const sp<MmapTrack> &track : mActiveTracks) {
9855 if (session == track->sessionId()) {
9856 chain->decActiveTrackCnt();
9857 chain->decTrackCnt();
9858 }
9859 }
9860 break;
9861 }
9862 }
9863 return mEffectChains.size();
9864}
9865
Eric Laurent6acd1d42017-01-04 14:23:29 -08009866void AudioFlinger::MmapThread::threadLoop_standby()
9867{
9868 mHalStream->standby();
9869}
9870
9871void AudioFlinger::MmapThread::threadLoop_exit()
9872{
Phil Burk7dce7282017-09-27 13:51:41 -07009873 // Do not call callback->onTearDown() because it is redundant for thread exit
9874 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08009875}
9876
9877status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
9878{
9879 return BAD_VALUE;
9880}
9881
9882bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
9883{
9884 return false;
9885}
9886
9887status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
9888 const effect_descriptor_t *desc, audio_session_t sessionId)
9889{
9890 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -08009891 if (audio_is_global_session(sessionId)) {
9892 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -08009893 desc->name, mThreadName);
9894 return BAD_VALUE;
9895 }
9896
9897 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
9898 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
9899 desc->name);
9900 return BAD_VALUE;
9901 }
9902 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08009903 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
9904 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009905 return BAD_VALUE;
9906 }
9907
9908 // Only allow effects without processing load or latency
9909 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
9910 return BAD_VALUE;
9911 }
9912
jiabineb3bda02020-06-30 14:07:03 -07009913 if (EffectModule::isHapticGenerator(&desc->type)) {
9914 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
9915 return BAD_VALUE;
9916 }
9917
Eric Laurent6acd1d42017-01-04 14:23:29 -08009918 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009919}
9920
9921void AudioFlinger::MmapThread::checkInvalidTracks_l()
9922{
9923 for (const sp<MmapTrack> &track : mActiveTracks) {
9924 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009925 sp<MmapStreamCallback> callback = mCallback.promote();
9926 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009927 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07009928 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07009929 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07009930 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9931 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
9932 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009933 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009934 }
9935 }
9936}
9937
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009938void AudioFlinger::MmapThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009939{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009940 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
9941 mAttr.content_type, mAttr.usage, mAttr.source);
9942 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -07009943 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009944 dprintf(fd, " No active clients\n");
9945 }
9946}
9947
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009948void AudioFlinger::MmapThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009949{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009950 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009951 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009952 dprintf(fd, " %zu Tracks\n", numtracks);
9953 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08009954 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009955 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07009956 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009957 for (size_t i = 0; i < numtracks ; ++i) {
9958 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009959 result.append(prefix);
9960 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009961 }
9962 } else {
9963 dprintf(fd, "\n");
9964 }
9965 write(fd, result.string(), result.size());
9966}
9967
9968AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
9969 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -07009970 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -07009971 : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -08009972 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009973 mStreamVolume(1.0),
9974 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009975 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009976{
9977 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
9978 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
9979 mMasterVolume = audioFlinger->masterVolume_l();
9980 mMasterMute = audioFlinger->masterMute_l();
9981 if (mAudioHwDev) {
9982 if (mAudioHwDev->canSetMasterVolume()) {
9983 mMasterVolume = 1.0;
9984 }
9985
9986 if (mAudioHwDev->canSetMasterMute()) {
9987 mMasterMute = false;
9988 }
9989 }
9990}
9991
9992void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
9993 audio_stream_type_t streamType,
9994 audio_session_t sessionId,
9995 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009996 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009997 audio_port_handle_t portId)
9998{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009999 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010000 mStreamType = streamType;
10001}
10002
10003AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
10004{
10005 Mutex::Autolock _l(mLock);
10006 AudioStreamOut *output = mOutput;
10007 mOutput = NULL;
10008 return output;
10009}
10010
10011void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
10012{
10013 Mutex::Autolock _l(mLock);
10014 // Don't apply master volume in SW if our HAL can do it for us.
10015 if (mAudioHwDev &&
10016 mAudioHwDev->canSetMasterVolume()) {
10017 mMasterVolume = 1.0;
10018 } else {
10019 mMasterVolume = value;
10020 }
10021}
10022
10023void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
10024{
10025 Mutex::Autolock _l(mLock);
10026 // Don't apply master mute in SW if our HAL can do it for us.
10027 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10028 mMasterMute = false;
10029 } else {
10030 mMasterMute = muted;
10031 }
10032}
10033
10034void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
10035{
10036 Mutex::Autolock _l(mLock);
10037 if (stream == mStreamType) {
10038 mStreamVolume = value;
10039 broadcast_l();
10040 }
10041}
10042
10043float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
10044{
10045 Mutex::Autolock _l(mLock);
10046 if (stream == mStreamType) {
10047 return mStreamVolume;
10048 }
10049 return 0.0f;
10050}
10051
10052void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
10053{
10054 Mutex::Autolock _l(mLock);
10055 if (stream == mStreamType) {
10056 mStreamMute= muted;
10057 broadcast_l();
10058 }
10059}
10060
10061void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
10062{
10063 Mutex::Autolock _l(mLock);
10064 if (streamType == mStreamType) {
10065 for (const sp<MmapTrack> &track : mActiveTracks) {
10066 track->invalidate();
10067 }
10068 broadcast_l();
10069 }
10070}
10071
10072void AudioFlinger::MmapPlaybackThread::processVolume_l()
10073{
10074 float volume;
10075
10076 if (mMasterMute || mStreamMute) {
10077 volume = 0;
10078 } else {
10079 volume = mMasterVolume * mStreamVolume;
10080 }
10081
10082 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010083
10084 // Convert volumes from float to 8.24
10085 uint32_t vol = (uint32_t)(volume * (1 << 24));
10086
10087 // Delegate volume control to effect in track effect chain if needed
10088 // only one effect chain can be present on DirectOutputThread, so if
10089 // there is one, the track is connected to it
10090 if (!mEffectChains.isEmpty()) {
10091 mEffectChains[0]->setVolume_l(&vol, &vol);
10092 volume = (float)vol / (1 << 24);
10093 }
Eric Laurentdff774a2017-04-21 15:29:38 -070010094 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070010095 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
10096 mHalVolFloat = volume; // HW volume control worked, so update value.
10097 mNoCallbackWarningCount = 0;
10098 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070010099 sp<MmapStreamCallback> callback = mCallback.promote();
10100 if (callback != 0) {
10101 int channelCount;
10102 if (isOutput()) {
10103 channelCount = audio_channel_count_from_out_mask(mChannelMask);
10104 } else {
10105 channelCount = audio_channel_count_from_in_mask(mChannelMask);
10106 }
10107 Vector<float> values;
10108 for (int i = 0; i < channelCount; i++) {
10109 values.add(volume);
10110 }
Phil Burk56ecf3e2018-03-12 15:38:17 -070010111 mHalVolFloat = volume; // SW volume control worked, so update value.
10112 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -070010113 mLock.unlock();
10114 callback->onVolumeChanged(mChannelMask, values);
10115 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010116 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010117 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10118 ALOGW("Could not set MMAP stream volume: no volume callback!");
10119 mNoCallbackWarningCount++;
10120 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010121 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010122 }
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010123 for (const sp<MmapTrack> &track : mActiveTracks) {
10124 track->setMetadataHasChanged();
10125 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010126 }
10127}
10128
Kevin Rocard069c2712018-03-29 19:09:14 -070010129void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
10130{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010131 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10132 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010133 }
10134 StreamOutHalInterface::SourceMetadata metadata;
10135 for (const sp<MmapTrack> &track : mActiveTracks) {
10136 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010137 playback_track_metadata_v7_t trackMetadata;
10138 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010139 .usage = track->attributes().usage,
10140 .content_type = track->attributes().content_type,
10141 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010142 };
10143 trackMetadata.channel_mask = track->channelMask(),
10144 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10145 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010146 }
10147 mOutput->stream->updateSourceMetadata(metadata);
10148}
10149
Eric Laurent6acd1d42017-01-04 14:23:29 -080010150void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
10151{
10152 if (!mMasterMute) {
10153 char value[PROPERTY_VALUE_MAX];
10154 if (property_get("ro.audio.silent", value, "0") > 0) {
10155 char *endptr;
10156 unsigned long ul = strtoul(value, &endptr, 0);
10157 if (*endptr == '\0' && ul != 0) {
10158 ALOGD("Silence is golden");
10159 // The setprop command will not allow a property to be changed after
10160 // the first time it is set, so we don't have to worry about un-muting.
10161 setMasterMute_l(true);
10162 }
10163 }
10164 }
10165}
10166
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010167void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
10168{
10169 MmapThread::toAudioPortConfig(config);
10170 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10171 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10172 config->flags.output = mOutput->flags;
10173 }
10174}
10175
jiabinb7d8c5a2020-08-26 17:24:52 -070010176status_t AudioFlinger::MmapPlaybackThread::getExternalPosition(uint64_t *position,
10177 int64_t *timeNanos)
10178{
10179 if (mOutput == nullptr) {
10180 return NO_INIT;
10181 }
10182 struct timespec timestamp;
10183 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10184 if (status == NO_ERROR) {
10185 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10186 }
10187 return status;
10188}
10189
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010190void AudioFlinger::MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010191{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010192 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010193
Glenn Kastend3bb6452016-12-05 18:14:37 -080010194 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
10195 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010196 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
10197}
10198
10199AudioFlinger::MmapCaptureThread::MmapCaptureThread(
10200 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010201 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010202 : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010203 mInput(input)
10204{
10205 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
10206 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
10207}
10208
Eric Laurent331679c2018-04-16 17:03:16 -070010209status_t AudioFlinger::MmapCaptureThread::exitStandby()
10210{
Phil Burkf054fc32018-12-06 09:45:59 -080010211 {
10212 // mInput might have been cleared by clearInput()
10213 Mutex::Autolock _l(mLock);
10214 if (mInput != nullptr && mInput->stream != nullptr) {
10215 mInput->stream->setGain(1.0f);
10216 }
10217 }
Eric Laurent331679c2018-04-16 17:03:16 -070010218 return MmapThread::exitStandby();
10219}
10220
Eric Laurent6acd1d42017-01-04 14:23:29 -080010221AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
10222{
10223 Mutex::Autolock _l(mLock);
10224 AudioStreamIn *input = mInput;
10225 mInput = NULL;
10226 return input;
10227}
Kevin Rocard069c2712018-03-29 19:09:14 -070010228
Eric Laurent331679c2018-04-16 17:03:16 -070010229
10230void AudioFlinger::MmapCaptureThread::processVolume_l()
10231{
10232 bool changed = false;
10233 bool silenced = false;
10234
10235 sp<MmapStreamCallback> callback = mCallback.promote();
10236 if (callback == 0) {
10237 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10238 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
10239 mNoCallbackWarningCount++;
10240 }
10241 }
10242
10243 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
10244 // track is silenced and unmute otherwise
10245 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
10246 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
10247 changed = true;
10248 silenced = mActiveTracks[i]->isSilenced_l();
10249 }
10250 }
10251
10252 if (changed) {
10253 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
10254 }
10255}
10256
Kevin Rocard069c2712018-03-29 19:09:14 -070010257void AudioFlinger::MmapCaptureThread::updateMetadata_l()
10258{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010259 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10260 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010261 }
10262 StreamInHalInterface::SinkMetadata metadata;
10263 for (const sp<MmapTrack> &track : mActiveTracks) {
10264 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010265 record_track_metadata_v7_t trackMetadata;
10266 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010267 .source = track->attributes().source,
10268 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010010269 };
10270 trackMetadata.channel_mask = track->channelMask(),
10271 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10272 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010273 }
10274 mInput->stream->updateSinkMetadata(metadata);
10275}
10276
Eric Laurent5ada82e2019-08-29 17:53:54 -070010277void AudioFlinger::MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070010278{
10279 Mutex::Autolock _l(mLock);
10280 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070010281 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070010282 mActiveTracks[i]->setSilenced_l(silenced);
10283 broadcast_l();
10284 }
10285 }
10286}
10287
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010288void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
10289{
10290 MmapThread::toAudioPortConfig(config);
10291 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10292 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10293 config->flags.input = mInput->flags;
10294 }
10295}
10296
jiabinb7d8c5a2020-08-26 17:24:52 -070010297status_t AudioFlinger::MmapCaptureThread::getExternalPosition(
10298 uint64_t *position, int64_t *timeNanos)
10299{
10300 if (mInput == nullptr) {
10301 return NO_INIT;
10302 }
10303 return mInput->getCapturePosition((int64_t*)position, timeNanos);
10304}
10305
Glenn Kasten63238ef2015-03-02 15:50:29 -080010306} // namespace android