blob: a14c1dd1e96df1f2453ace061ed50b321901aa76 [file] [log] [blame]
Eric Laurent81784c32012-11-19 14:55:58 -08001/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
Alex Ray371eb972012-11-30 11:11:54 -080021#define ATRACE_TAG ATRACE_TAG_AUDIO
Eric Laurent81784c32012-11-19 14:55:58 -080022
Glenn Kasten153b9fe2013-07-15 11:23:36 -070023#include "Configuration.h"
Eric Laurent81784c32012-11-19 14:55:58 -080024#include <math.h>
25#include <fcntl.h>
Eric Tan7b651152018-07-13 10:17:19 -070026#include <memory>
Andy Hungb68f5eb2019-12-03 16:49:17 -080027#include <sstream>
Eric Tan7b651152018-07-13 10:17:19 -070028#include <string>
Glenn Kastenad8510a2015-02-17 16:24:07 -080029#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080030#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080031#include <sys/syscall.h>
Glenn Kastenc9a23672020-06-30 12:12:42 -070032#include <cutils/bitops.h>
Eric Laurent81784c32012-11-19 14:55:58 -080033#include <cutils/properties.h>
jiabinc52b1ff2019-10-31 17:20:42 -070034#include <media/AudioContainers.h>
35#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070036#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070037#include <media/AudioResamplerPublic.h>
Andy Hung89816052017-01-11 17:08:23 -080038#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070039#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080041#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080042
43#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070044#include <private/android_filesystem_config.h>
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +010045#include <audio_utils/Balance.h>
jiabinf6eb4c32020-02-25 14:06:25 -080046#include <audio_utils/Metadata.h>
jiabin245cdd92018-12-07 17:55:15 -080047#include <audio_utils/channels.h>
Glenn Kasten6bf707f2017-02-23 16:53:58 -080048#include <audio_utils/mono_blend.h>
Eric Laurent81784c32012-11-19 14:55:58 -080049#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080050#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070051#include <audio_utils/minifloat.h>
Hongwei Wang95e37682019-04-12 11:13:36 -070052#include <audio_utils/safe_math.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070053#include <system/audio_effects/effect_aec.h>
Eric Laurentb3f315a2021-07-13 15:09:05 +020054#include <system/audio_effects/effect_downmix.h>
55#include <system/audio_effects/effect_ns.h>
Eric Laurent1c5e2e32021-08-18 18:50:28 +020056#include <system/audio_effects/effect_spatializer.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070057#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080058
59// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070060#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080061#include <media/nbaio/AudioStreamOutSink.h>
62#include <media/nbaio/MonoPipe.h>
63#include <media/nbaio/MonoPipeReader.h>
64#include <media/nbaio/Pipe.h>
65#include <media/nbaio/PipeReader.h>
66#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080067#include <mediautils/BatteryNotifier.h>
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 Laurent1c5e2e32021-08-18 18:50:28 +0200512 case SPATIALIZER:
513 return "SPATIALIZER";
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 Laurent1c5e2e32021-08-18 18:50:28 +02001040 case SPATIALIZER:
1041 return String16("AudioSpatial");
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 Laurentf690c462021-09-17 14:47:03 +02001346 if (memcmp(&desc->type, FX_IID_SPATIALIZER, sizeof(effect_uuid_t)) == 0
1347 && mType != SPATIALIZER) {
1348 ALOGW("%s: attempt to create a spatializer effect on a thread of type %d",
1349 __func__, mType);
1350 return BAD_VALUE;
1351 }
1352
Eric Laurent4c415062016-06-17 16:14:16 -07001353 switch (mType) {
1354 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001355#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001356 // Reject any effect on mixer multichannel sinks.
1357 // TODO: fix both format and multichannel issues with effects.
1358 if (mChannelCount != FCC_2) {
1359 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1360 " thread %s", desc->name, mChannelCount, mThreadName);
1361 return BAD_VALUE;
1362 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001363#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001364 audio_output_flags_t flags = mOutput->flags;
1365 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1366 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1367 // global effects are applied only to non fast tracks if they are SW
1368 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1369 break;
1370 }
1371 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
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 output stage session", desc->name);
1376 return BAD_VALUE;
1377 }
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001378 } else if (sessionId == AUDIO_SESSION_DEVICE) {
1379 // only post processing on output stage session
1380 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1381 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1382 " on device session", desc->name);
1383 return BAD_VALUE;
1384 }
Eric Laurent4c415062016-06-17 16:14:16 -07001385 } else {
1386 // no restriction on effects applied on non fast tracks
1387 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1388 break;
1389 }
1390 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001391
Eric Laurent4c415062016-06-17 16:14:16 -07001392 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1393 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1394 desc->name);
1395 return BAD_VALUE;
1396 }
1397 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1398 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1399 " in fast mode", desc->name);
1400 return BAD_VALUE;
1401 }
1402 }
1403 } break;
1404 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001405 // nothing actionable on offload threads, if the effect:
1406 // - is offloadable: the effect can be created
1407 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1408 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001409 break;
1410 case DIRECT:
1411 // Reject any effect on Direct output threads for now, since the format of
1412 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1413 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1414 desc->name, mThreadName);
1415 return BAD_VALUE;
1416 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001417#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001418 // Reject any effect on mixer multichannel sinks.
1419 // TODO: fix both format and multichannel issues with effects.
1420 if (mChannelCount != FCC_2) {
1421 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1422 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1423 return BAD_VALUE;
1424 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001425#endif
Eric Laurent3f75a5b2019-11-12 15:55:51 -08001426 if (audio_is_global_session(sessionId)) {
Eric Laurent4c415062016-06-17 16:14:16 -07001427 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1428 " thread %s", desc->name, mThreadName);
1429 return BAD_VALUE;
1430 }
1431 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1432 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1433 " DUPLICATING thread %s", desc->name, mThreadName);
1434 return BAD_VALUE;
1435 }
1436 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1437 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1438 " DUPLICATING thread %s", desc->name, mThreadName);
1439 return BAD_VALUE;
1440 }
1441 break;
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001442 case SPATIALIZER:
Eric Laurentb3f315a2021-07-13 15:09:05 +02001443 if (!audio_is_global_session(sessionId)) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001444 ALOGW("checkEffectCompatibility_l(): non global effect %s on SPATIALIZER"
Eric Laurentb3f315a2021-07-13 15:09:05 +02001445 " thread %s", desc->name, mThreadName);
1446 return BAD_VALUE;
1447 }
1448 break;
Eric Laurent4c415062016-06-17 16:14:16 -07001449 default:
1450 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1451 }
1452
1453 return NO_ERROR;
1454}
1455
Eric Laurent81784c32012-11-19 14:55:58 -08001456// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1457sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1458 const sp<AudioFlinger::Client>& client,
1459 const sp<IEffectClient>& effectClient,
1460 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001461 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001462 effect_descriptor_t *desc,
1463 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001464 status_t *status,
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001465 bool pinned,
Eric Laurentde8caf42021-08-11 17:19:25 +02001466 bool probe,
1467 bool notifyFramesProcessed)
Eric Laurent81784c32012-11-19 14:55:58 -08001468{
1469 sp<EffectModule> effect;
1470 sp<EffectHandle> handle;
1471 status_t lStatus;
1472 sp<EffectChain> chain;
1473 bool chainCreated = false;
1474 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001475 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001476
1477 lStatus = initCheck();
1478 if (lStatus != NO_ERROR) {
1479 ALOGW("createEffect_l() Audio driver not initialized.");
1480 goto Exit;
1481 }
1482
Eric Laurent81784c32012-11-19 14:55:58 -08001483 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1484
1485 { // scope for mLock
1486 Mutex::Autolock _l(mLock);
1487
Eric Laurent4c415062016-06-17 16:14:16 -07001488 lStatus = checkEffectCompatibility_l(desc, sessionId);
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001489 if (probe || lStatus != NO_ERROR) {
Eric Laurent4c415062016-06-17 16:14:16 -07001490 goto Exit;
1491 }
1492
Eric Laurent81784c32012-11-19 14:55:58 -08001493 // check for existing effect chain with the requested audio session
1494 chain = getEffectChain_l(sessionId);
1495 if (chain == 0) {
1496 // create a new chain for this session
1497 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1498 chain = new EffectChain(this, sessionId);
1499 addEffectChain_l(chain);
1500 chain->setStrategy(getStrategyForSession_l(sessionId));
1501 chainCreated = true;
1502 } else {
1503 effect = chain->getEffectFromDesc_l(desc);
1504 }
1505
1506 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1507
1508 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001509 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001510 // create a new effect module if none present in the chain
Eric Laurent6b446ce2019-12-13 10:56:31 -08001511 lStatus = chain->createEffect_l(effect, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001512 if (lStatus != NO_ERROR) {
1513 goto Exit;
1514 }
1515 effectCreated = true;
1516
jiabinc52b1ff2019-10-31 17:20:42 -07001517 // FIXME: use vector of device and address when effect interface is ready.
jiabin8f278ee2019-11-11 12:16:27 -08001518 effect->setDevices(outDeviceTypeAddrs());
1519 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001520 effect->setMode(mAudioFlinger->getMode());
1521 effect->setAudioSource(mAudioSource);
1522 }
jiabin1319f5a2021-03-30 22:21:24 +00001523 if (effect->isHapticGenerator()) {
1524 // TODO(b/184194057): Use the vibrator information from the vibrator that will be used
1525 // for the HapticGenerator.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001526 const std::optional<media::AudioVibratorInfo> defaultVibratorInfo =
1527 std::move(mAudioFlinger->getDefaultVibratorInfo_l());
1528 if (defaultVibratorInfo) {
jiabin1319f5a2021-03-30 22:21:24 +00001529 // Only set the vibrator info when it is a valid one.
Lais Andradebc3f37a2021-07-02 00:13:19 +01001530 effect->setVibratorInfo(*defaultVibratorInfo);
jiabin1319f5a2021-03-30 22:21:24 +00001531 }
1532 }
Eric Laurent81784c32012-11-19 14:55:58 -08001533 // create effect handle and connect it to effect module
Eric Laurentde8caf42021-08-11 17:19:25 +02001534 handle = new EffectHandle(effect, client, effectClient, priority, notifyFramesProcessed);
Glenn Kastene75da402013-11-20 13:54:52 -08001535 lStatus = handle->initCheck();
1536 if (lStatus == OK) {
1537 lStatus = effect->addHandle(handle.get());
Eric Laurentb3f315a2021-07-13 15:09:05 +02001538 sendCheckOutputStageEffectsEvent_l();
Glenn Kastene75da402013-11-20 13:54:52 -08001539 }
Eric Laurent81784c32012-11-19 14:55:58 -08001540 if (enabled != NULL) {
1541 *enabled = (int)effect->isEnabled();
1542 }
1543 }
1544
1545Exit:
Eric Laurent2fe0acd2020-03-13 14:30:46 -07001546 if (!probe && lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
Eric Laurent81784c32012-11-19 14:55:58 -08001547 Mutex::Autolock _l(mLock);
1548 if (effectCreated) {
1549 chain->removeEffect_l(effect);
1550 }
Eric Laurent81784c32012-11-19 14:55:58 -08001551 if (chainCreated) {
1552 removeEffectChain_l(chain);
1553 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001554 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001555 }
1556
Glenn Kasten9156ef32013-08-06 15:39:08 -07001557 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001558 return handle;
1559}
1560
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001561void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1562 bool unpinIfLast)
1563{
1564 bool remove = false;
1565 sp<EffectModule> effect;
1566 {
1567 Mutex::Autolock _l(mLock);
Eric Laurent41709552019-12-16 19:34:05 -08001568 sp<EffectBase> effectBase = handle->effect().promote();
1569 if (effectBase == nullptr) {
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001570 return;
1571 }
Eric Laurentb82e6b72019-11-22 17:25:04 -08001572 effect = effectBase->asEffectModule();
1573 if (effect == nullptr) {
1574 return;
1575 }
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001576 // restore suspended effects if the disconnected handle was enabled and the last one.
1577 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1578 if (remove) {
1579 removeEffect_l(effect, true);
1580 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02001581 sendCheckOutputStageEffectsEvent_l();
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001582 }
1583 if (remove) {
1584 mAudioFlinger->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001585 if (handle->enabled()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001586 effect->checkSuspendOnEffectEnabled(false, false /*threadLocked*/);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001587 }
1588 }
1589}
1590
Eric Laurent6b446ce2019-12-13 10:56:31 -08001591void AudioFlinger::ThreadBase::onEffectEnable(const sp<EffectModule>& effect) {
Andy Hungea840382020-05-05 21:50:17 -07001592 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001593 Mutex::Autolock _l(mLock);
1594 broadcast_l();
1595 }
1596 if (!effect->isOffloadable()) {
1597 if (mType == ThreadBase::OFFLOAD) {
1598 PlaybackThread *t = (PlaybackThread *)this;
1599 t->invalidateTracks(AUDIO_STREAM_MUSIC);
1600 }
1601 if (effect->sessionId() == AUDIO_SESSION_OUTPUT_MIX) {
1602 mAudioFlinger->onNonOffloadableGlobalEffectEnable();
1603 }
1604 }
1605}
1606
1607void AudioFlinger::ThreadBase::onEffectDisable() {
Andy Hungea840382020-05-05 21:50:17 -07001608 if (isOffloadOrMmap()) {
Eric Laurent6b446ce2019-12-13 10:56:31 -08001609 Mutex::Autolock _l(mLock);
1610 broadcast_l();
1611 }
1612}
1613
Glenn Kastend848eb42016-03-08 13:42:11 -08001614sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1615 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001616{
1617 Mutex::Autolock _l(mLock);
1618 return getEffect_l(sessionId, effectId);
1619}
1620
Glenn Kastend848eb42016-03-08 13:42:11 -08001621sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1622 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001623{
1624 sp<EffectChain> chain = getEffectChain_l(sessionId);
1625 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1626}
1627
Eric Laurent6c796322019-04-09 14:13:17 -07001628std::vector<int> AudioFlinger::ThreadBase::getEffectIds_l(audio_session_t sessionId)
1629{
1630 sp<EffectChain> chain = getEffectChain_l(sessionId);
1631 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1632}
1633
Eric Laurent81784c32012-11-19 14:55:58 -08001634// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1635// PlaybackThread::mLock held
1636status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1637{
1638 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001639 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001640 sp<EffectChain> chain = getEffectChain_l(sessionId);
1641 bool chainCreated = false;
1642
Eric Laurent5baf2af2013-09-12 17:37:00 -07001643 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001644 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001645 this, effect->desc().name, effect->desc().flags);
1646
Eric Laurent81784c32012-11-19 14:55:58 -08001647 if (chain == 0) {
1648 // create a new chain for this session
1649 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1650 chain = new EffectChain(this, sessionId);
1651 addEffectChain_l(chain);
1652 chain->setStrategy(getStrategyForSession_l(sessionId));
1653 chainCreated = true;
1654 }
1655 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1656
1657 if (chain->getEffectFromId_l(effect->id()) != 0) {
1658 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1659 this, effect->desc().name, chain.get());
1660 return BAD_VALUE;
1661 }
1662
Eric Laurent5baf2af2013-09-12 17:37:00 -07001663 effect->setOffloaded(mType == OFFLOAD, mId);
1664
Eric Laurent81784c32012-11-19 14:55:58 -08001665 status_t status = chain->addEffect_l(effect);
1666 if (status != NO_ERROR) {
1667 if (chainCreated) {
1668 removeEffectChain_l(chain);
1669 }
1670 return status;
1671 }
1672
jiabin8f278ee2019-11-11 12:16:27 -08001673 effect->setDevices(outDeviceTypeAddrs());
1674 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001675 effect->setMode(mAudioFlinger->getMode());
1676 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001677
Eric Laurent81784c32012-11-19 14:55:58 -08001678 return NO_ERROR;
1679}
1680
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001681void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001682
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001683 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001684 effect_descriptor_t desc = effect->desc();
1685 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1686 detachAuxEffect_l(effect->id());
1687 }
1688
Andy Hungfda44002021-06-03 17:23:16 -07001689 sp<EffectChain> chain = effect->getCallback()->chain().promote();
Eric Laurent81784c32012-11-19 14:55:58 -08001690 if (chain != 0) {
1691 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001692 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001693 removeEffectChain_l(chain);
1694 }
1695 } else {
1696 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1697 }
1698}
1699
1700void AudioFlinger::ThreadBase::lockEffectChains_l(
1701 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1702{
1703 effectChains = mEffectChains;
1704 for (size_t i = 0; i < mEffectChains.size(); i++) {
1705 mEffectChains[i]->lock();
1706 }
1707}
1708
1709void AudioFlinger::ThreadBase::unlockEffectChains(
1710 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1711{
1712 for (size_t i = 0; i < effectChains.size(); i++) {
1713 effectChains[i]->unlock();
1714 }
1715}
1716
Glenn Kastend848eb42016-03-08 13:42:11 -08001717sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001718{
1719 Mutex::Autolock _l(mLock);
1720 return getEffectChain_l(sessionId);
1721}
1722
Glenn Kastend848eb42016-03-08 13:42:11 -08001723sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1724 const
Eric Laurent81784c32012-11-19 14:55:58 -08001725{
1726 size_t size = mEffectChains.size();
1727 for (size_t i = 0; i < size; i++) {
1728 if (mEffectChains[i]->sessionId() == sessionId) {
1729 return mEffectChains[i];
1730 }
1731 }
1732 return 0;
1733}
1734
1735void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1736{
1737 Mutex::Autolock _l(mLock);
1738 size_t size = mEffectChains.size();
1739 for (size_t i = 0; i < size; i++) {
1740 mEffectChains[i]->setMode_l(mode);
1741 }
1742}
1743
Mikhail Naganovdc769682018-05-04 15:34:08 -07001744void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001745{
1746 config->type = AUDIO_PORT_TYPE_MIX;
1747 config->ext.mix.handle = mId;
1748 config->sample_rate = mSampleRate;
1749 config->format = mFormat;
1750 config->channel_mask = mChannelMask;
1751 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1752 AUDIO_PORT_CONFIG_FORMAT;
1753}
1754
Eric Laurent72e3f392015-05-20 14:43:50 -07001755void AudioFlinger::ThreadBase::systemReady()
1756{
1757 Mutex::Autolock _l(mLock);
1758 if (mSystemReady) {
1759 return;
1760 }
1761 mSystemReady = true;
1762
1763 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1764 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1765 }
1766 mPendingConfigEvents.clear();
1767}
1768
Andy Hungdae27702016-10-31 14:01:16 -07001769template <typename T>
1770ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1771 ssize_t index = mActiveTracks.indexOf(track);
1772 if (index >= 0) {
1773 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1774 return index;
1775 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001776 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001777 mActiveTracksGeneration++;
1778 mLatestActiveTrack = track;
1779 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001780 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001781 return mActiveTracks.add(track);
1782}
1783
1784template <typename T>
1785ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1786 ssize_t index = mActiveTracks.remove(track);
1787 if (index < 0) {
1788 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1789 return index;
1790 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001791 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001792 mActiveTracksGeneration++;
1793 --mBatteryCounter[track->uid()].second;
1794 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001795 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001796#ifdef TEE_SINK
1797 track->dumpTee(-1 /* fd */, "_REMOVE");
1798#endif
Andy Hungc2b11cb2020-04-22 09:04:01 -07001799 track->logEndInterval(); // log to MediaMetrics
Andy Hungdae27702016-10-31 14:01:16 -07001800 return index;
1801}
1802
1803template <typename T>
1804void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1805 for (const sp<T> &track : mActiveTracks) {
1806 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001807 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001808 }
1809 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001810 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001811 mActiveTracks.clear();
1812 mLatestActiveTrack.clear();
1813 mBatteryCounter.clear();
1814}
1815
1816template <typename T>
1817void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1818 sp<ThreadBase> thread, bool force) {
1819 // Updates ActiveTracks client uids to the thread wakelock.
1820 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1821 thread->updateWakeLockUids_l(getWakeLockUids());
1822 mLastActiveTracksGeneration = mActiveTracksGeneration;
1823 }
1824
1825 // Updates BatteryNotifier uids
1826 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1827 const uid_t uid = it->first;
1828 ssize_t &previous = it->second.first;
1829 ssize_t &current = it->second.second;
1830 if (current > 0) {
1831 if (previous == 0) {
1832 BatteryNotifier::getInstance().noteStartAudio(uid);
1833 }
1834 previous = current;
1835 ++it;
1836 } else if (current == 0) {
1837 if (previous > 0) {
1838 BatteryNotifier::getInstance().noteStopAudio(uid);
1839 }
1840 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1841 } else /* (current < 0) */ {
1842 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1843 }
1844 }
1845}
Eric Laurent83b88082014-06-20 18:31:16 -07001846
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001847template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001848bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001849 bool hasChanged = mHasChanged;
Kevin Rocard069c2712018-03-29 19:09:14 -07001850 mHasChanged = false;
Jasmine Chaeaa10e42021-05-11 10:11:14 +08001851
1852 for (const sp<T> &track : mActiveTracks) {
1853 // Do not short-circuit as all hasChanged states must be reset
1854 // as all the metadata are going to be sent
1855 hasChanged |= track->readAndClearHasChanged();
1856 }
Kevin Rocard069c2712018-03-29 19:09:14 -07001857 return hasChanged;
1858}
1859
1860template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001861void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1862 const char *funcName, const sp<T> &track) const {
1863 if (mLocalLog != nullptr) {
1864 String8 result;
1865 track->appendDump(result, false /* active */);
1866 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1867 }
1868}
1869
Eric Laurent6acd1d42017-01-04 14:23:29 -08001870void AudioFlinger::ThreadBase::broadcast_l()
1871{
1872 // Thread could be blocked waiting for async
1873 // so signal it to handle state changes immediately
1874 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1875 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1876 mSignalPending = true;
1877 mWaitWorkCV.broadcast();
1878}
1879
Andy Hungd0979812019-02-21 15:51:44 -08001880// Call only from threadLoop() or when it is idle.
1881// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
1882void AudioFlinger::ThreadBase::sendStatistics(bool force)
1883{
1884 // Do not log if we have no stats.
1885 // We choose the timestamp verifier because it is the most likely item to be present.
1886 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1887 if (nstats == 0) {
1888 return;
1889 }
1890
1891 // Don't log more frequently than once per 12 hours.
1892 // We use BOOTTIME to include suspend time.
1893 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1894 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1895 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1896 return;
1897 }
1898
1899 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1900 mLastRecordedTimeNs = timeNs;
1901
Ray Essickf27e9872019-12-07 06:28:46 -08001902 std::unique_ptr<mediametrics::Item> item(mediametrics::Item::create("audiothread"));
Andy Hungd0979812019-02-21 15:51:44 -08001903
1904#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1905
1906 // thread configuration
1907 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1908 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1909 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1910 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1911 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1912 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1913 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabinc52b1ff2019-10-31 17:20:42 -07001914 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
1915 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08001916
1917 // thread statistics
1918 if (mIoJitterMs.getN() > 0) {
1919 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1920 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1921 }
1922 if (mProcessTimeMs.getN() > 0) {
1923 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
1924 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
1925 }
1926 const auto tsjitter = mTimestampVerifier.getJitterMs();
1927 if (tsjitter.getN() > 0) {
1928 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
1929 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
1930 }
1931 if (mLatencyMs.getN() > 0) {
1932 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
1933 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
1934 }
Robert Wu06db0a32021-08-10 19:05:34 +00001935 if (mMonopipePipeDepthStats.getN() > 0) {
1936 item->setDouble(MM_PREFIX "monopipePipeDepthStats.mean",
1937 mMonopipePipeDepthStats.getMean());
1938 item->setDouble(MM_PREFIX "monopipePipeDepthStats.std",
1939 mMonopipePipeDepthStats.getStdDev());
1940 }
Andy Hungd0979812019-02-21 15:51:44 -08001941
1942 item->selfrecord();
1943}
1944
Eric Laurentd66d7a12021-07-13 13:35:32 +02001945product_strategy_t AudioFlinger::ThreadBase::getStrategyForStream(audio_stream_type_t stream) const
1946{
1947 if (!mAudioFlinger->isAudioPolicyReady()) {
1948 return PRODUCT_STRATEGY_NONE;
1949 }
1950 return AudioSystem::getStrategyForStream(stream);
1951}
1952
Eric Laurent81784c32012-11-19 14:55:58 -08001953// ----------------------------------------------------------------------------
1954// Playback
1955// ----------------------------------------------------------------------------
1956
1957AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1958 AudioStreamOut* output,
1959 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07001960 type_t type,
Eric Laurentf1f22e72021-07-13 14:04:14 +02001961 bool systemReady,
1962 audio_config_base_t *mixerConfig)
Andy Hungcf10d742020-04-28 15:38:24 -07001963 : ThreadBase(audioFlinger, id, type, systemReady, true /* isOut */),
Andy Hung2098f272014-02-27 14:00:06 -08001964 mNormalFrameCount(0), mSinkBuffer(NULL),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001965 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung69aed5f2014-02-25 17:24:40 -08001966 mMixerBuffer(NULL),
1967 mMixerBufferSize(0),
1968 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1969 mMixerBufferValid(false),
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001970 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision || type == SPATIALIZER),
Andy Hung98ef9782014-03-04 14:46:50 -08001971 mEffectBuffer(NULL),
1972 mEffectBufferSize(0),
1973 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1974 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001975 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001976 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001977 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001978 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001979 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001980 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001981 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08001982 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001983 mMixerStatus(MIXER_IDLE),
1984 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001985 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001986 mBytesRemaining(0),
1987 mCurrentWriteLength(0),
1988 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001989 mWriteAckSequence(0),
1990 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001991 mScreenState(AudioFlinger::mScreenState),
1992 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001993 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001994 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
Eric Laurent74c38dc2020-12-23 18:19:44 +01001995 mLeftVolFloat(-1.0), mRightVolFloat(-1.0),
1996 mDownStreamPatch{}
Eric Laurent81784c32012-11-19 14:55:58 -08001997{
Glenn Kastend7dca052015-03-05 16:05:54 -08001998 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1999 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08002000
2001 // Assumes constructor is called by AudioFlinger with it's mLock held, but
2002 // it would be safer to explicitly pass initial masterVolume/masterMute as
2003 // parameter.
2004 //
2005 // If the HAL we are using has support for master volume or master mute,
2006 // then do not attenuate or mute during mixing (just leave the volume at 1.0
2007 // and the mute set to false).
2008 mMasterVolume = audioFlinger->masterVolume_l();
2009 mMasterMute = audioFlinger->masterMute_l();
George Burgess IV5e4d86f2020-02-18 12:55:36 -08002010 if (mOutput->audioHwDev) {
Eric Laurent81784c32012-11-19 14:55:58 -08002011 if (mOutput->audioHwDev->canSetMasterVolume()) {
2012 mMasterVolume = 1.0;
2013 }
2014
2015 if (mOutput->audioHwDev->canSetMasterMute()) {
2016 mMasterMute = false;
2017 }
Andy Hungc8fddf32018-08-08 18:32:37 -07002018 mIsMsdDevice = strcmp(
2019 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002020 }
2021
Eric Laurentf1f22e72021-07-13 14:04:14 +02002022 if (mixerConfig != nullptr && mixerConfig->channel_mask != AUDIO_CHANNEL_NONE) {
2023 mMixerChannelMask = mixerConfig->channel_mask;
2024 }
2025
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002026 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002027
Eric Laurent1c5e2e32021-08-18 18:50:28 +02002028 if (mType != SPATIALIZER
Eric Laurentb3f315a2021-07-13 15:09:05 +02002029 && mMixerChannelMask != mChannelMask) {
2030 LOG_ALWAYS_FATAL("HAL channel mask %#x does not match mixer channel mask %#x",
2031 mChannelMask, mMixerChannelMask);
2032 }
2033
Andy Hungc8fddf32018-08-08 18:32:37 -07002034 // TODO: We may also match on address as well as device type for
2035 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11002036 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabinc52b1ff2019-10-31 17:20:42 -07002037 // TODO: This property should be ensure that only contains one single device type.
2038 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
2039 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07002040 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
2041 : AUDIO_DEVICE_NONE));
2042 }
2043
Mikhail Naganovf33115d2020-09-25 23:03:05 +00002044 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_FOR_POLICY_CNT; ++i) {
2045 const audio_stream_type_t stream{static_cast<audio_stream_type_t>(i)};
Eric Laurent98e38192018-02-15 18:31:53 -08002046 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08002047 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
2048 }
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002049 // Audio patch and call assistant volume are always max
Eric Laurent98e38192018-02-15 18:31:53 -08002050 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
2051 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent35f8c7c2020-02-08 11:42:35 -08002052 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].volume = 1.0f;
2053 mStreamTypes[AUDIO_STREAM_CALL_ASSISTANT].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08002054}
2055
2056AudioFlinger::PlaybackThread::~PlaybackThread()
2057{
Glenn Kasten9e58b552013-01-18 15:09:48 -08002058 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07002059 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08002060 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08002061 free(mEffectBuffer);
Eric Laurent39095982021-08-24 18:29:27 +02002062 free(mEffectToSinkBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08002063}
2064
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002065// Thread virtuals
2066
2067void AudioFlinger::PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08002068{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002069 if (!isStreamInitialized()) {
jiabinf6eb4c32020-02-25 14:06:25 -08002070 ALOGE("The stream is not open yet"); // This should not happen.
2071 } else {
2072 // setEventCallback will need a strong pointer as a parameter. Calling it
2073 // here instead of constructor of PlaybackThread so that the onFirstRef
2074 // callback would not be made on an incompletely constructed object.
2075 if (mOutput->stream->setEventCallback(this) != OK) {
jiabinf1a36052020-08-19 14:33:31 -07002076 ALOGD("Failed to add event callback");
jiabinf6eb4c32020-02-25 14:06:25 -08002077 }
2078 }
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002079 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08002080}
2081
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07002082// ThreadBase virtuals
2083void AudioFlinger::PlaybackThread::preExit()
2084{
2085 ALOGV(" preExit()");
2086 // FIXME this is using hard-coded strings but in the future, this functionality will be
2087 // converted to use audio HAL extensions required to support tunneling
2088 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
2089 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
2090}
2091
2092void AudioFlinger::PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08002093{
Eric Laurent81784c32012-11-19 14:55:58 -08002094 String8 result;
2095
Marco Nelissenb2208842014-02-07 14:00:50 -08002096 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08002097 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
2098 const stream_type_t *st = &mStreamTypes[i];
2099 if (i > 0) {
2100 result.appendFormat(", ");
2101 }
2102 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
2103 if (st->mute) {
2104 result.append("M");
2105 }
2106 }
2107 result.append("\n");
2108 write(fd, result.string(), result.length());
2109 result.clear();
2110
Eric Laurent81784c32012-11-19 14:55:58 -08002111 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
2112 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002113 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08002114 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08002115
2116 size_t numtracks = mTracks.size();
2117 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002118 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08002119 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002120 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08002121 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002122 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002123 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002124 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002125 for (size_t i = 0; i < numtracks; ++i) {
2126 sp<Track> track = mTracks[i];
2127 if (track != 0) {
2128 bool active = mActiveTracks.indexOf(track) >= 0;
2129 if (active) {
2130 numactiveseen++;
2131 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002132 result.append(prefix);
2133 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08002134 }
2135 }
2136 } else {
2137 result.append("\n");
2138 }
2139 if (numactiveseen != numactive) {
2140 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002141 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08002142 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002143 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07002144 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08002145 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07002146 sp<Track> track = mActiveTracks[i];
2147 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002148 result.append(prefix);
2149 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08002150 }
2151 }
2152 }
2153
2154 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08002155}
2156
Andy Hung61589a42021-06-16 09:37:53 -07002157void AudioFlinger::PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08002158{
Andy Hung04cb8f72020-03-20 13:44:33 -07002159 dprintf(fd, " Master volume: %f\n", mMasterVolume);
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07002160 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
Eric Laurentf1f22e72021-07-13 14:04:14 +02002161 dprintf(fd, " Mixer channel Mask: %#x (%s)\n",
2162 mMixerChannelMask, channelMaskToString(mMixerChannelMask, true /* output */).c_str());
jiabin245cdd92018-12-07 17:55:15 -08002163 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
2164 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
2165 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
2166 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07002167 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07002168 dprintf(fd, " Total writes: %d\n", mNumWrites);
2169 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
2170 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
2171 dprintf(fd, " Suspend count: %d\n", mSuspended);
2172 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
2173 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
2174 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
2175 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08002176 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07002177 AudioStreamOut *output = mOutput;
2178 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07002179 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08002180 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07002181 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
2182 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
2183 if (mPipeSink.get() != nullptr) {
2184 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
2185 }
2186 if (output != nullptr) {
2187 dprintf(fd, " Hal stream dump:\n");
Andy Hung61589a42021-06-16 09:37:53 -07002188 (void)output->stream->dump(fd, args);
Andy Hungb54c8542016-09-21 12:55:15 -07002189 }
Eric Laurent81784c32012-11-19 14:55:58 -08002190}
2191
Eric Laurent81784c32012-11-19 14:55:58 -08002192// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
2193sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
2194 const sp<AudioFlinger::Client>& client,
2195 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002196 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08002197 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08002198 audio_format_t format,
2199 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08002200 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08002201 size_t *pNotificationFrameCount,
2202 uint32_t notificationsPerBuffer,
2203 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08002204 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08002205 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07002206 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002207 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00002208 const AttributionSourceState& attributionSource,
Eric Laurent81784c32012-11-19 14:55:58 -08002209 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002210 status_t *status,
jiabinf6eb4c32020-02-25 14:06:25 -08002211 audio_port_handle_t portId,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002212 const sp<media::IAudioTrackCallback>& callback)
Eric Laurent81784c32012-11-19 14:55:58 -08002213{
Glenn Kasten74935e42013-12-19 08:56:45 -08002214 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002215 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002216 sp<Track> track;
2217 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07002218 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08002219 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07002220 uint32_t sampleRate;
2221
2222 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
2223 lStatus = BAD_VALUE;
2224 goto Exit;
2225 }
Eric Laurent21da6472017-11-09 16:29:26 -08002226
2227 if (*pSampleRate == 0) {
2228 *pSampleRate = mSampleRate;
2229 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002230 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002231
2232 // special case for FAST flag considered OK if fast mixer is present
2233 if (hasFastMixer()) {
2234 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2235 }
2236
2237 // Check if requested flags are compatible with output stream flags
2238 if ((*flags & outputFlags) != *flags) {
2239 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2240 *flags, outputFlags);
2241 *flags = (audio_output_flags_t)(*flags & outputFlags);
2242 }
Eric Laurent81784c32012-11-19 14:55:58 -08002243
Eric Laurent81784c32012-11-19 14:55:58 -08002244 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002245 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002246 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002247 // PCM data
2248 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002249 // TODO: extract as a data library function that checks that a computationally
2250 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002251 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002252 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2253 (channelMask == AUDIO_CHANNEL_OUT_MONO
2254 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002255 // hardware sample rate
2256 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002257 // normal mixer has an associated fast mixer
2258 hasFastMixer() &&
2259 // there are sufficient fast track slots available
2260 (mFastTrackAvailMask != 0)
2261 // FIXME test that MixerThread for this fast track has a capable output HAL
2262 // FIXME add a permission test also?
2263 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002264 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2265 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002266 // read the fast track multiplier property the first time it is needed
2267 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2268 if (ok != 0) {
2269 ALOGE("%s pthread_once failed: %d", __func__, ok);
2270 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002271 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002272 }
Eric Laurent4c415062016-06-17 16:14:16 -07002273
2274 // check compatibility with audio effects.
2275 { // scope for mLock
2276 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002277 for (audio_session_t session : {
Eric Laurent3f75a5b2019-11-12 15:55:51 -08002278 AUDIO_SESSION_DEVICE,
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002279 AUDIO_SESSION_OUTPUT_STAGE,
2280 AUDIO_SESSION_OUTPUT_MIX,
2281 sessionId,
2282 }) {
2283 sp<EffectChain> chain = getEffectChain_l(session);
2284 if (chain.get() != nullptr) {
2285 audio_output_flags_t old = *flags;
2286 chain->checkOutputFlagCompatibility(flags);
2287 if (old != *flags) {
2288 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2289 (int)session, (int)old, (int)*flags);
2290 }
Eric Laurent4c415062016-06-17 16:14:16 -07002291 }
2292 }
2293 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002294 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002295 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2296 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002297 } else {
Robert Wu4c7bb7d2021-08-12 18:50:13 +00002298 ALOGD("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002299 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002300 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002301 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002302 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07002303 audio_is_linear_pcm(format), channelMask, sampleRate,
2304 mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002305 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002306 }
2307 }
Eric Laurent21da6472017-11-09 16:29:26 -08002308
2309 if (!audio_has_proportional_frames(format)) {
2310 if (sharedBuffer != 0) {
2311 // Same comment as below about ignoring frameCount parameter for set()
2312 frameCount = sharedBuffer->size();
2313 } else if (frameCount == 0) {
2314 frameCount = mNormalFrameCount;
2315 }
2316 if (notificationFrameCount != frameCount) {
2317 notificationFrameCount = frameCount;
2318 }
2319 } else if (sharedBuffer != 0) {
2320 // FIXME: Ensure client side memory buffers need
2321 // not have additional alignment beyond sample
2322 // (e.g. 16 bit stereo accessed as 32 bit frame).
2323 size_t alignment = audio_bytes_per_sample(format);
2324 if (alignment & 1) {
2325 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2326 alignment = 1;
2327 }
2328 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2329 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2330 if (channelCount > 1) {
2331 // More than 2 channels does not require stronger alignment than stereo
2332 alignment <<= 1;
2333 }
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002334 if (((uintptr_t)sharedBuffer->unsecurePointer() & (alignment - 1)) != 0) {
Eric Laurent21da6472017-11-09 16:29:26 -08002335 ALOGE("Invalid buffer alignment: address %p, channel count %u",
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07002336 sharedBuffer->unsecurePointer(), channelCount);
Eric Laurent21da6472017-11-09 16:29:26 -08002337 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002338 goto Exit;
2339 }
Eric Laurent21da6472017-11-09 16:29:26 -08002340
2341 // When initializing a shared buffer AudioTrack via constructors,
2342 // there's no frameCount parameter.
2343 // But when initializing a shared buffer AudioTrack via set(),
2344 // there _is_ a frameCount parameter. We silently ignore it.
2345 frameCount = sharedBuffer->size() / frameSize;
2346 } else {
2347 size_t minFrameCount = 0;
2348 // For fast tracks we try to respect the application's request for notifications per buffer.
2349 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2350 if (notificationsPerBuffer > 0) {
2351 // Avoid possible arithmetic overflow during multiplication.
2352 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2353 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2354 notificationsPerBuffer, mFrameCount);
2355 } else {
2356 minFrameCount = mFrameCount * notificationsPerBuffer;
2357 }
2358 }
2359 } else {
2360 // For normal PCM streaming tracks, update minimum frame count.
2361 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2362 // cover audio hardware latency.
2363 // This is probably too conservative, but legacy application code may depend on it.
2364 // If you change this calculation, also review the start threshold which is related.
2365 uint32_t latencyMs = latency_l();
2366 if (latencyMs == 0) {
2367 ALOGE("Error when retrieving output stream latency");
2368 lStatus = UNKNOWN_ERROR;
2369 goto Exit;
2370 }
2371
2372 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2373 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2374
Eric Laurent81784c32012-11-19 14:55:58 -08002375 }
Eric Laurent21da6472017-11-09 16:29:26 -08002376 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002377 frameCount = minFrameCount;
2378 }
Eric Laurent81784c32012-11-19 14:55:58 -08002379 }
Eric Laurent21da6472017-11-09 16:29:26 -08002380
2381 // Make sure that application is notified with sufficient margin before underrun.
2382 // The client can divide the AudioTrack buffer into sub-buffers,
2383 // and expresses its desire to server as the notification frame count.
2384 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2385 size_t maxNotificationFrames;
2386 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2387 // notify every HAL buffer, regardless of the size of the track buffer
2388 maxNotificationFrames = mFrameCount;
2389 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002390 // Triple buffer the notification period for a triple buffered mixer period;
2391 // otherwise, double buffering for the notification period is fine.
2392 //
2393 // TODO: This should be moved to AudioTrack to modify the notification period
2394 // on AudioTrack::setBufferSizeInFrames() changes.
2395 const int nBuffering =
2396 (uint64_t{frameCount} * mSampleRate)
2397 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2398
Eric Laurent21da6472017-11-09 16:29:26 -08002399 maxNotificationFrames = frameCount / nBuffering;
2400 // If client requested a fast track but this was denied, then use the smaller maximum.
2401 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2402 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2403 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2404 maxNotificationFrames = maxNotificationFramesFastDenied;
2405 }
2406 }
2407 }
2408 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2409 if (notificationFrameCount == 0) {
2410 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2411 maxNotificationFrames, frameCount);
2412 } else {
2413 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2414 notificationFrameCount, maxNotificationFrames, frameCount);
2415 }
2416 notificationFrameCount = maxNotificationFrames;
2417 }
2418 }
2419
Glenn Kasten74935e42013-12-19 08:56:45 -08002420 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002421 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002422
Glenn Kastenc3df8382014-03-13 15:05:25 -07002423 switch (mType) {
2424
2425 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002426 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002427 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002428 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2429 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002430 sampleRate, format, channelMask, mOutput, mFormat);
2431 lStatus = BAD_VALUE;
2432 goto Exit;
2433 }
2434 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002435 break;
2436
2437 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002438 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002439 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2440 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002441 sampleRate, format, channelMask, mOutput, mFormat);
2442 lStatus = BAD_VALUE;
2443 goto Exit;
2444 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002445 break;
2446
2447 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002448 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002449 ALOGE("createTrack_l() Bad parameter: format %#x \""
2450 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002451 format, mOutput, mFormat);
2452 lStatus = BAD_VALUE;
2453 goto Exit;
2454 }
Andy Hungcd044842014-08-07 11:04:34 -07002455 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002456 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2457 lStatus = BAD_VALUE;
2458 goto Exit;
2459 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002460 break;
2461
Eric Laurent81784c32012-11-19 14:55:58 -08002462 }
2463
2464 lStatus = initCheck();
2465 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002466 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002467 goto Exit;
2468 }
2469
2470 { // scope for mLock
2471 Mutex::Autolock _l(mLock);
2472
2473 // all tracks in same audio session must share the same routing strategy otherwise
2474 // conflicts will happen when tracks are moved from one output to another by audio policy
2475 // manager
Eric Laurentd66d7a12021-07-13 13:35:32 +02002476 product_strategy_t strategy = getStrategyForStream(streamType);
Eric Laurent81784c32012-11-19 14:55:58 -08002477 for (size_t i = 0; i < mTracks.size(); ++i) {
2478 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002479 if (t != 0 && t->isExternalTrack()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02002480 product_strategy_t actual = getStrategyForStream(t->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08002481 if (sessionId == t->sessionId() && strategy != actual) {
2482 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2483 strategy, actual);
2484 lStatus = BAD_VALUE;
2485 goto Exit;
2486 }
2487 }
2488 }
2489
yucliuc9c49cd2020-07-13 16:25:21 -07002490 // Set DIRECT flag if current thread is DirectOutputThread. This can
2491 // happen when the playback is rerouted to direct output thread by
2492 // dynamic audio policy.
2493 // Do NOT report the flag changes back to client, since the client
2494 // doesn't explicitly request a direct flag.
2495 audio_output_flags_t trackFlags = *flags;
2496 if (mType == DIRECT) {
2497 trackFlags = static_cast<audio_output_flags_t>(trackFlags | AUDIO_OUTPUT_FLAG_DIRECT);
2498 }
2499
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002500 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002501 channelMask, frameCount,
2502 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Svet Ganov33761132021-05-13 22:51:08 +00002503 sessionId, creatorPid, attributionSource, trackFlags,
2504 TrackBase::TYPE_DEFAULT, portId, SIZE_MAX /*frameCountToBeReady*/, speed);
Glenn Kasten03003332013-08-06 15:40:54 -07002505
Glenn Kasten03003332013-08-06 15:40:54 -07002506 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2507 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002508 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002509 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002510 goto Exit;
2511 }
2512 mTracks.add(track);
jiabinf6eb4c32020-02-25 14:06:25 -08002513 {
2514 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2515 if (callback.get() != nullptr) {
jiabin18a4b1c2020-09-17 11:40:42 -07002516 mAudioTrackCallbacks.emplace(track, callback);
jiabinf6eb4c32020-02-25 14:06:25 -08002517 }
2518 }
Eric Laurent81784c32012-11-19 14:55:58 -08002519
2520 sp<EffectChain> chain = getEffectChain_l(sessionId);
2521 if (chain != 0) {
2522 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2523 track->setMainBuffer(chain->inBuffer());
Eric Laurentd66d7a12021-07-13 13:35:32 +02002524 chain->setStrategy(getStrategyForStream(track->streamType()));
Eric Laurent81784c32012-11-19 14:55:58 -08002525 chain->incTrackCnt();
2526 }
2527
Eric Laurent05067782016-06-01 18:27:28 -07002528 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002529 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2530 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2531 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002532 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002533 }
2534 }
2535
2536 lStatus = NO_ERROR;
2537
2538Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002539 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002540 return track;
2541}
2542
Andy Hung1bc088a2018-02-09 15:57:31 -08002543template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002544ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2545{
Andy Hungc0691382018-09-12 18:01:57 -07002546 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002547 const ssize_t index = mTracks.remove(track);
2548 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002549 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002550 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002551 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002552 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002553 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002554 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002555 }
2556 return index;
2557}
2558
Eric Laurent81784c32012-11-19 14:55:58 -08002559uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2560{
2561 return latency;
2562}
2563
2564uint32_t AudioFlinger::PlaybackThread::latency() const
2565{
2566 Mutex::Autolock _l(mLock);
2567 return latency_l();
2568}
2569uint32_t AudioFlinger::PlaybackThread::latency_l() const
2570{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002571 uint32_t latency;
2572 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2573 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002574 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002575 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002576}
2577
2578void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2579{
2580 Mutex::Autolock _l(mLock);
2581 // Don't apply master volume in SW if our HAL can do it for us.
2582 if (mOutput && mOutput->audioHwDev &&
2583 mOutput->audioHwDev->canSetMasterVolume()) {
2584 mMasterVolume = 1.0;
2585 } else {
2586 mMasterVolume = value;
2587 }
2588}
2589
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002590void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2591{
2592 mMasterBalance.store(balance);
2593}
2594
Eric Laurent81784c32012-11-19 14:55:58 -08002595void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2596{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002597 if (isDuplicating()) {
2598 return;
2599 }
Eric Laurent81784c32012-11-19 14:55:58 -08002600 Mutex::Autolock _l(mLock);
2601 // Don't apply master mute in SW if our HAL can do it for us.
2602 if (mOutput && mOutput->audioHwDev &&
2603 mOutput->audioHwDev->canSetMasterMute()) {
2604 mMasterMute = false;
2605 } else {
2606 mMasterMute = muted;
2607 }
2608}
2609
2610void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2611{
2612 Mutex::Autolock _l(mLock);
2613 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002614 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002615}
2616
2617void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2618{
2619 Mutex::Autolock _l(mLock);
2620 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002621 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002622}
2623
2624float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2625{
2626 Mutex::Autolock _l(mLock);
2627 return mStreamTypes[stream].volume;
2628}
2629
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002630void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2631{
2632 mOutput->stream->setVolume(left, right);
2633}
2634
Eric Laurent81784c32012-11-19 14:55:58 -08002635// addTrack_l() must be called with ThreadBase::mLock held
2636status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2637{
2638 status_t status = ALREADY_EXISTS;
2639
Eric Laurent81784c32012-11-19 14:55:58 -08002640 if (mActiveTracks.indexOf(track) < 0) {
2641 // the track is newly added, make sure it fills up all its
2642 // buffers before playing. This is to ensure the client will
2643 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002644 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002645 TrackBase::track_state state = track->mState;
2646 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002647 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002648 mLock.lock();
2649 // abort track was stopped/paused while we released the lock
2650 if (state != track->mState) {
2651 if (status == NO_ERROR) {
2652 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002653 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002654 mLock.lock();
2655 }
2656 return INVALID_OPERATION;
2657 }
2658 // abort if start is rejected by audio policy manager
2659 if (status != NO_ERROR) {
2660 return PERMISSION_DENIED;
2661 }
2662#ifdef ADD_BATTERY_DATA
2663 // to track the speaker usage
2664 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2665#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002666 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002667 }
2668
Eric Laurent51716182016-02-29 18:00:56 -08002669 // set retry count for buffer fill
2670 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002671 if (track->isStopping_1()) {
2672 track->mRetryCount = kMaxTrackStopRetriesOffload;
2673 } else {
2674 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2675 }
2676 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002677 } else {
2678 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002679 track->mFillingUpStatus =
2680 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002681 }
2682
jiabineb3bda02020-06-30 14:07:03 -07002683 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2684 if (mHapticChannelMask != AUDIO_CHANNEL_NONE
2685 && ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2686 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08002687 // Unlock due to VibratorService will lock for this call and will
2688 // call Tracks.mute/unmute which also require thread's lock.
2689 mLock.unlock();
2690 const int intensity = AudioFlinger::onExternalVibrationStart(
2691 track->getExternalVibration());
Lais Andradebc3f37a2021-07-02 00:13:19 +01002692 std::optional<media::AudioVibratorInfo> vibratorInfo;
2693 {
2694 // TODO(b/184194780): Use the vibrator information from the vibrator that will be
2695 // used to play this track.
2696 Mutex::Autolock _l(mAudioFlinger->mLock);
2697 vibratorInfo = std::move(mAudioFlinger->getDefaultVibratorInfo_l());
2698 }
jiabin57303cc2018-12-18 15:45:57 -08002699 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07002700 track->setHapticIntensity(static_cast<os::HapticScale>(intensity));
Lais Andradebc3f37a2021-07-02 00:13:19 +01002701 if (vibratorInfo) {
2702 track->setHapticMaxAmplitude(vibratorInfo->maxAmplitude);
2703 }
2704
jiabin57303cc2018-12-18 15:45:57 -08002705 // Haptic playback should be enabled by vibrator service.
2706 if (track->getHapticPlaybackEnabled()) {
2707 // Disable haptic playback of all active track to ensure only
2708 // one track playing haptic if current track should play haptic.
2709 for (const auto &t : mActiveTracks) {
2710 t->setHapticPlaybackEnabled(false);
2711 }
jiabin245cdd92018-12-07 17:55:15 -08002712 }
jiabine70bc7f2020-06-30 22:07:55 -07002713
2714 // Set haptic intensity for effect
2715 if (chain != nullptr) {
2716 chain->setHapticIntensity_l(track->id(), intensity);
2717 }
jiabin245cdd92018-12-07 17:55:15 -08002718 }
2719
Eric Laurent81784c32012-11-19 14:55:58 -08002720 track->mResetDone = false;
Andy Hung59de4262021-06-14 10:53:54 -07002721 track->resetPresentationComplete();
Eric Laurent81784c32012-11-19 14:55:58 -08002722 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002723 if (chain != 0) {
2724 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2725 track->sessionId());
2726 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002727 }
2728
Andy Hungc2b11cb2020-04-22 09:04:01 -07002729 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent81784c32012-11-19 14:55:58 -08002730 status = NO_ERROR;
2731 }
2732
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002733 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002734 return status;
2735}
2736
Eric Laurentbfb1b832013-01-07 09:53:42 -08002737bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002738{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002739 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002740 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002741 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2742 track->mState = TrackBase::STOPPED;
2743 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002744 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002745 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002746 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002747 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002748
2749 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002750}
2751
2752void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2753{
2754 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002755
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002756 String8 result;
2757 track->appendDump(result, false /* active */);
2758 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002759
Eric Laurent81784c32012-11-19 14:55:58 -08002760 mTracks.remove(track);
jiabin18a4b1c2020-09-17 11:40:42 -07002761 {
2762 Mutex::Autolock _atCbL(mAudioTrackCbLock);
2763 mAudioTrackCallbacks.erase(track);
2764 }
Eric Laurent81784c32012-11-19 14:55:58 -08002765 if (track->isFastTrack()) {
2766 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002767 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002768 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2769 mFastTrackAvailMask |= 1 << index;
2770 // redundant as track is about to be destroyed, for dumpsys only
2771 track->mFastIndex = -1;
2772 }
2773 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2774 if (chain != 0) {
2775 chain->decTrackCnt();
2776 }
2777}
2778
2779String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2780{
Eric Laurent81784c32012-11-19 14:55:58 -08002781 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002782 String8 out_s8;
2783 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2784 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002785 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002786 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002787}
2788
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002789status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2790 Mutex::Autolock _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08002791 if (!isStreamInitialized()) {
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002792 return NO_INIT;
2793 }
2794 return mOutput->stream->selectPresentation(presentationId, programId);
2795}
2796
Mikhail Naganov88536df2021-07-26 17:30:29 -07002797void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002798 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002799 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Mikhail Naganov88536df2021-07-26 17:30:29 -07002800 sp<AudioIoDescriptor> desc;
2801 const struct audio_patch patch = isMsdDevice() ? mDownStreamPatch : mPatch;
Eric Laurent81784c32012-11-19 14:55:58 -08002802 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002803 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002804 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002805 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002806 desc = sp<AudioIoDescriptor>::make(mId, patch, false /*isInput*/,
2807 mSampleRate, mFormat, mChannelMask,
2808 // FIXME AudioFlinger::frameCount(audio_io_handle_t) instead of mNormalFrameCount?
2809 mNormalFrameCount, mFrameCount, latency_l());
Eric Laurent81784c32012-11-19 14:55:58 -08002810 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002811 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002812 desc = sp<AudioIoDescriptor>::make(mId, patch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07002813 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002814 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002815 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07002816 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08002817 break;
2818 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002819 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002820}
2821
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002822void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002823{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002824 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002825}
2826
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002827void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002828{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002829 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002830}
2831
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002832void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002833{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002834 mCallbackThread->setAsyncError();
2835}
2836
jiabinf6eb4c32020-02-25 14:06:25 -08002837void AudioFlinger::PlaybackThread::onCodecFormatChanged(
2838 const std::basic_string<uint8_t>& metadataBs)
2839{
2840 std::thread([this, metadataBs]() {
2841 audio_utils::metadata::Data metadata =
2842 audio_utils::metadata::dataFromByteString(metadataBs);
2843 if (metadata.empty()) {
2844 ALOGW("Can not transform the buffer to audio metadata, %s, %d",
2845 reinterpret_cast<char*>(const_cast<uint8_t*>(metadataBs.data())),
2846 (int)metadataBs.size());
2847 return;
2848 }
2849
2850 audio_utils::metadata::ByteString metaDataStr =
2851 audio_utils::metadata::byteStringFromData(metadata);
2852 std::vector metadataVec(metaDataStr.begin(), metaDataStr.end());
2853 Mutex::Autolock _l(mAudioTrackCbLock);
jiabin18a4b1c2020-09-17 11:40:42 -07002854 for (const auto& callbackPair : mAudioTrackCallbacks) {
2855 callbackPair.second->onCodecFormatChanged(metadataVec);
jiabinf6eb4c32020-02-25 14:06:25 -08002856 }
2857 }).detach();
2858}
2859
Eric Laurent3b4529e2013-09-05 18:09:19 -07002860void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002861{
2862 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002863 // reject out of sequence requests
2864 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2865 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002866 mWaitWorkCV.signal();
2867 }
2868}
2869
Eric Laurent3b4529e2013-09-05 18:09:19 -07002870void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002871{
2872 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002873 // reject out of sequence requests
2874 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002875 // Register discontinuity when HW drain is completed because that can cause
2876 // the timestamp frame position to reset to 0 for direct and offload threads.
2877 // (Out of sequence requests are ignored, since the discontinuity would be handled
2878 // elsewhere, e.g. in flush).
Dean Wheatley12473e92021-03-18 23:00:55 +11002879 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002880 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002881 mWaitWorkCV.signal();
2882 }
2883}
2884
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002885void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002886{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002887 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Mikhail Naganov560637e2021-03-31 22:40:13 +00002888 const audio_config_base_t audioConfig = mOutput->getAudioProperties();
2889 mSampleRate = audioConfig.sample_rate;
2890 mChannelMask = audioConfig.channel_mask;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002891 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002892 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002893 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02002894 if (hasMixer() && !isValidPcmSinkChannelMask(mChannelMask)) {
Andy Hung9a592762014-07-21 21:56:01 -07002895 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2896 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002897 }
Eric Laurentf1f22e72021-07-13 14:04:14 +02002898
2899 if (mMixerChannelMask == AUDIO_CHANNEL_NONE) {
2900 mMixerChannelMask = mChannelMask;
2901 }
2902
Andy Hunge5412692014-05-16 11:25:07 -07002903 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002904 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002905
Eric Laurentf1f22e72021-07-13 14:04:14 +02002906 uint32_t mixerChannelCount = audio_channel_count_from_out_mask(mMixerChannelMask);
2907
Phil Burkca5e6142015-07-14 09:42:29 -07002908 // Get actual HAL format.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002909 status_t result = mOutput->stream->getAudioProperties(nullptr, nullptr, &mHALFormat);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002910 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002911 // Get format from the shim, which will be different than the HAL format
2912 // if playing compressed audio over HDMI passthrough.
Mikhail Naganov560637e2021-03-31 22:40:13 +00002913 mFormat = audioConfig.format;
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002914 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002915 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002916 }
Eric Laurentb3f315a2021-07-13 15:09:05 +02002917 if (hasMixer() && !isValidPcmSinkFormat(mFormat)) {
Andy Hung6146c082014-03-18 11:56:15 -07002918 LOG_FATAL("HAL format %#x not supported for mixed output",
2919 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002920 }
Phil Burk062e67a2015-02-11 13:40:50 -08002921 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002922 result = mOutput->stream->getBufferSize(&mBufferSize);
2923 LOG_ALWAYS_FATAL_IF(result != OK,
2924 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002925 mFrameCount = mBufferSize / mFrameSize;
Eric Laurentb3f315a2021-07-13 15:09:05 +02002926 if (hasMixer() && (mFrameCount & 15)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002927 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002928 mFrameCount);
2929 }
2930
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002931 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2932 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002933 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002934 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002935 }
2936 }
2937
Eric Laurentd1f69b02014-12-15 14:33:13 -08002938 mHwSupportsPause = false;
2939 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002940 bool supportsPause = false, supportsResume = false;
2941 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2942 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002943 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002944 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002945 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002946 } else if (supportsResume) {
2947 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002948 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002949 }
2950 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002951 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2952 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2953 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002954
Andy Hungfbfc3952015-01-15 13:33:51 -08002955 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2956 // For best precision, we use float instead of the associated output
2957 // device format (typically PCM 16 bit).
2958
2959 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2960 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2961 mBufferSize = mFrameSize * mFrameCount;
2962
2963 // TODO: We currently use the associated output device channel mask and sample rate.
2964 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2965 // (if a valid mask) to avoid premature downmix.
2966 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2967 // instead of the output device sample rate to avoid loss of high frequency information.
2968 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2969 }
2970
Andy Hung09a50072014-02-27 14:30:47 -08002971 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002972 double multiplier = 1.0;
2973 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2974 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002975 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2976 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002977
Eric Laurent81784c32012-11-19 14:55:58 -08002978 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2979 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2980 maxNormalFrameCount = maxNormalFrameCount & ~15;
2981 if (maxNormalFrameCount < minNormalFrameCount) {
2982 maxNormalFrameCount = minNormalFrameCount;
2983 }
2984 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2985 if (multiplier <= 1.0) {
2986 multiplier = 1.0;
2987 } else if (multiplier <= 2.0) {
2988 if (2 * mFrameCount <= maxNormalFrameCount) {
2989 multiplier = 2.0;
2990 } else {
2991 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2992 }
2993 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002994 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002995 }
2996 }
2997 mNormalFrameCount = multiplier * mFrameCount;
2998 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentb3f315a2021-07-13 15:09:05 +02002999 if (hasMixer()) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07003000 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
3001 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003002 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08003003 mNormalFrameCount);
3004
Andy Hung08fb1742015-05-31 23:22:10 -07003005 // Check if we want to throttle the processing to no more than 2x normal rate
3006 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07003007 mThreadThrottleTimeMs = 0;
3008 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07003009 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
3010
Andy Hung010a1a12014-03-13 13:57:33 -07003011 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
3012 // Originally this was int16_t[] array, need to remove legacy implications.
3013 free(mSinkBuffer);
3014 mSinkBuffer = NULL;
Eric Laurent39095982021-08-24 18:29:27 +02003015 free(mEffectToSinkBuffer);
3016 mEffectToSinkBuffer = nullptr;
3017
Andy Hung5b10a202014-03-13 13:59:29 -07003018 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
3019 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
3020 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07003021 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08003022
Eric Laurent39095982021-08-24 18:29:27 +02003023 if (mType == SPATIALIZER) {
3024 (void)posix_memalign(&mEffectToSinkBuffer, 32, sinkBufferSize);
3025 }
3026
Andy Hung69aed5f2014-02-25 17:24:40 -08003027 // We resize the mMixerBuffer according to the requirements of the sink buffer which
3028 // drives the output.
3029 free(mMixerBuffer);
3030 mMixerBuffer = NULL;
3031 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003032 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Eric Laurentf1f22e72021-07-13 14:04:14 +02003033 mMixerBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung69aed5f2014-02-25 17:24:40 -08003034 * audio_bytes_per_sample(mMixerBufferFormat);
3035 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
3036 }
Andy Hung98ef9782014-03-04 14:46:50 -08003037 free(mEffectBuffer);
3038 mEffectBuffer = NULL;
3039 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07003040 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003041 mEffectBufferSize = mNormalFrameCount * mixerChannelCount
Andy Hung98ef9782014-03-04 14:46:50 -08003042 * audio_bytes_per_sample(mEffectBufferFormat);
3043 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
3044 }
Andy Hung69aed5f2014-02-25 17:24:40 -08003045
Mikhail Naganov55773032020-10-01 15:08:13 -07003046 mHapticChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
3047 mChannelMask = static_cast<audio_channel_mask_t>(mChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003048 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
3049 mChannelCount -= mHapticChannelCount;
Eric Laurentf1f22e72021-07-13 14:04:14 +02003050 mMixerChannelMask = static_cast<audio_channel_mask_t>(mMixerChannelMask & ~mHapticChannelMask);
jiabin245cdd92018-12-07 17:55:15 -08003051
Eric Laurent81784c32012-11-19 14:55:58 -08003052 // force reconfiguration of effect chains and engines to take new buffer size and audio
3053 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08003054 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08003055 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
3056 // matter.
3057 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
3058 Vector< sp<EffectChain> > effectChains = mEffectChains;
3059 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent6c796322019-04-09 14:13:17 -07003060 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(),
3061 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08003062 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08003063
George Burgess IV5e4d86f2020-02-18 12:55:36 -08003064 audio_output_flags_t flags = mOutput->flags;
Andy Hungcf10d742020-04-28 15:38:24 -07003065 mediametrics::LogItem item(mThreadMetrics.getMetricsId()); // TODO: method in ThreadMetrics?
Andy Hungb68f5eb2019-12-03 16:49:17 -08003066 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
3067 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
3068 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
3069 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
3070 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
3071 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mNormalFrameCount)
3072 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
3073 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
3074 (int32_t)mHapticChannelMask)
3075 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
3076 (int32_t)mHapticChannelCount)
3077 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
3078 formatToString(mHALFormat).c_str())
3079 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
3080 (int32_t)mFrameCount) // sic - added HAL
3081 ;
3082 uint32_t latencyMs;
3083 if (mOutput->stream->getLatency(&latencyMs) == NO_ERROR) {
3084 item.set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_LATENCYMS, (double)latencyMs);
3085 }
3086 item.record();
Eric Laurent81784c32012-11-19 14:55:58 -08003087}
3088
Kevin Rocard069c2712018-03-29 19:09:14 -07003089void AudioFlinger::PlaybackThread::updateMetadata_l()
3090{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08003091 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
Kevin Rocard12381092018-04-11 09:19:59 -07003092 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07003093 }
3094 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07003095 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07003096 for (const sp<Track> &track : mActiveTracks) {
3097 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurentb9cc0ab2021-01-29 11:46:52 +01003098 // Do not forward metadata for PatchTrack with unspecified stream type
3099 if (track->streamType() != AUDIO_STREAM_PATCH) {
3100 track->copyMetadataTo(backInserter);
3101 }
Kevin Rocard069c2712018-03-29 19:09:14 -07003102 }
Kevin Rocard12381092018-04-11 09:19:59 -07003103 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00003104}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07003105
Kevin Rocard12381092018-04-11 09:19:59 -07003106void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
3107 const StreamOutHalInterface::SourceMetadata& metadata)
3108{
3109 mOutput->stream->updateSourceMetadata(metadata);
3110};
3111
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003112status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08003113{
3114 if (halFrames == NULL || dspFrames == NULL) {
3115 return BAD_VALUE;
3116 }
3117 Mutex::Autolock _l(mLock);
3118 if (initCheck() != NO_ERROR) {
3119 return INVALID_OPERATION;
3120 }
Andy Hung818e7a32016-02-16 18:08:07 -08003121 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08003122 *halFrames = framesWritten;
3123
3124 if (isSuspended()) {
3125 // return an estimation of rendered frames when the output is suspended
3126 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08003127 *dspFrames = (uint32_t)
3128 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08003129 return NO_ERROR;
3130 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003131 status_t status;
3132 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08003133 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00003134 *dspFrames = (size_t)frames;
3135 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08003136 }
3137}
3138
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003139product_strategy_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08003140{
3141 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
3142 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
3143 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003144 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003145 }
3146 for (size_t i = 0; i < mTracks.size(); i++) {
3147 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08003148 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02003149 return getStrategyForStream(track->streamType());
Eric Laurent81784c32012-11-19 14:55:58 -08003150 }
3151 }
Eric Laurentd66d7a12021-07-13 13:35:32 +02003152 return getStrategyForStream(AUDIO_STREAM_MUSIC);
Eric Laurent81784c32012-11-19 14:55:58 -08003153}
3154
3155
Phil Burk062e67a2015-02-11 13:40:50 -08003156AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08003157{
3158 Mutex::Autolock _l(mLock);
3159 return mOutput;
3160}
3161
Phil Burk062e67a2015-02-11 13:40:50 -08003162AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08003163{
3164 Mutex::Autolock _l(mLock);
3165 AudioStreamOut *output = mOutput;
3166 mOutput = NULL;
3167 // FIXME FastMixer might also have a raw ptr to mOutputSink;
3168 // must push a NULL and wait for ack
3169 mOutputSink.clear();
3170 mPipeSink.clear();
3171 mNormalSink.clear();
3172 return output;
3173}
3174
3175// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003176sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08003177{
3178 if (mOutput == NULL) {
3179 return NULL;
3180 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003181 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08003182}
3183
3184uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
3185{
3186 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
3187}
3188
3189status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
3190{
3191 if (!isValidSyncEvent(event)) {
3192 return BAD_VALUE;
3193 }
3194
3195 Mutex::Autolock _l(mLock);
3196
3197 for (size_t i = 0; i < mTracks.size(); ++i) {
3198 sp<Track> track = mTracks[i];
3199 if (event->triggerSession() == track->sessionId()) {
3200 (void) track->setSyncEvent(event);
3201 return NO_ERROR;
3202 }
3203 }
3204
3205 return NAME_NOT_FOUND;
3206}
3207
3208bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
3209{
3210 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
3211}
3212
3213void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
3214 const Vector< sp<Track> >& tracksToRemove)
3215{
Andy Hungfe726a62018-09-27 15:17:25 -07003216 // Miscellaneous track cleanup when removed from the active list,
3217 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08003218#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07003219 for (const auto& track : tracksToRemove) {
3220 if (track->isExternalTrack()) {
3221 // to track the speaker usage
3222 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08003223 }
3224 }
Andy Hungfe726a62018-09-27 15:17:25 -07003225#else
3226 (void)tracksToRemove; // suppress unused warning
3227#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003228}
3229
3230void AudioFlinger::PlaybackThread::checkSilentMode_l()
3231{
3232 if (!mMasterMute) {
3233 char value[PROPERTY_VALUE_MAX];
jiabin0a957d32020-04-29 10:56:20 -07003234 if (mOutDeviceTypeAddrs.empty()) {
3235 ALOGD("ro.audio.silent is ignored since no output device is set");
3236 return;
3237 }
jiabinc52b1ff2019-10-31 17:20:42 -07003238 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07003239 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
3240 return;
3241 }
Eric Laurent81784c32012-11-19 14:55:58 -08003242 if (property_get("ro.audio.silent", value, "0") > 0) {
3243 char *endptr;
3244 unsigned long ul = strtoul(value, &endptr, 0);
3245 if (*endptr == '\0' && ul != 0) {
3246 ALOGD("Silence is golden");
3247 // The setprop command will not allow a property to be changed after
3248 // the first time it is set, so we don't have to worry about un-muting.
3249 setMasterMute_l(true);
3250 }
3251 }
3252 }
3253}
3254
3255// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08003256ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08003257{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003258 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08003259 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003260 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07003261 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08003262
3263 // If an NBAIO sink is present, use it to write the normal mixer's submix
3264 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003265
Andy Hung010a1a12014-03-13 13:57:33 -07003266 const size_t count = mBytesRemaining / mFrameSize;
3267
Simon Wilson2d590962012-11-29 15:18:50 -08003268 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08003269 // update the setpoint when AudioFlinger::mScreenState changes
3270 uint32_t screenState = AudioFlinger::mScreenState;
3271 if (screenState != mScreenState) {
3272 mScreenState = screenState;
3273 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
3274 if (pipe != NULL) {
3275 pipe->setAvgFrames((mScreenState & 1) ?
3276 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
3277 }
3278 }
Andy Hung010a1a12014-03-13 13:57:33 -07003279 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08003280 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08003281 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07003282 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07003283#ifdef TEE_SINK
3284 mTee.write((char *)mSinkBuffer + offset, framesWritten);
3285#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003286 } else {
3287 bytesWritten = framesWritten;
3288 }
3289 // otherwise use the HAL / AudioStreamOut directly
3290 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003291 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07003292
Eric Laurentbfb1b832013-01-07 09:53:42 -08003293 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003294 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
3295 mWriteAckSequence += 2;
3296 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003297 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003298 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003299 }
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003300 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07003301 // FIXME We should have an implementation of timestamps for direct output threads.
3302 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08003303 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07003304 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08003305
Eric Laurentbfb1b832013-01-07 09:53:42 -08003306 if (mUseAsyncWrite &&
3307 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
3308 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07003309 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003310 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003311 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003312 }
Eric Laurent81784c32012-11-19 14:55:58 -08003313 }
3314
Eric Laurent81784c32012-11-19 14:55:58 -08003315 mNumWrites++;
3316 mInWrite = false;
Andy Hungcf10d742020-04-28 15:38:24 -07003317 if (mStandby) {
3318 mThreadMetrics.logBeginInterval();
3319 mStandby = false;
3320 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003321 return bytesWritten;
3322}
3323
3324void AudioFlinger::PlaybackThread::threadLoop_drain()
3325{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003326 bool supportsDrain = false;
3327 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003328 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3329 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003330 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3331 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003332 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003333 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003334 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003335 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003336 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003337 }
3338}
3339
3340void AudioFlinger::PlaybackThread::threadLoop_exit()
3341{
Eric Laurent275e8e92014-11-30 15:14:47 -08003342 {
3343 Mutex::Autolock _l(mLock);
3344 for (size_t i = 0; i < mTracks.size(); i++) {
3345 sp<Track> track = mTracks[i];
3346 track->invalidate();
3347 }
Andy Hungdae27702016-10-31 14:01:16 -07003348 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3349 // After we exit there are no more track changes sent to BatteryNotifier
3350 // because that requires an active threadLoop.
3351 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3352 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003353 }
Eric Laurent81784c32012-11-19 14:55:58 -08003354}
3355
3356/*
3357The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003358 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003359 - mActiveSleepTimeUs from activeSleepTimeUs()
3360 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003361 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3362 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003363 - maxPeriod from frame count and sample rate (MIXER only)
3364
3365The parameters that affect these derived values are:
3366 - frame count
3367 - frame size
3368 - sample rate
3369 - device type: A2DP or not
3370 - device latency
3371 - format: PCM or not
3372 - active sleep time
3373 - idle sleep time
3374*/
3375
3376void AudioFlinger::PlaybackThread::cacheParameters_l()
3377{
Andy Hung25c2dac2014-02-27 14:56:00 -08003378 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003379 mActiveSleepTimeUs = activeSleepTimeUs();
3380 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003381
3382 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3383 // truncating audio when going to standby.
3384 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
jiabinc52b1ff2019-10-31 17:20:42 -07003385 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003386 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3387 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3388 }
3389 }
Eric Laurent81784c32012-11-19 14:55:58 -08003390}
3391
Eric Laurent13084622016-05-17 10:51:49 -07003392bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003393{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003394 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003395 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003396 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003397 size_t size = mTracks.size();
3398 for (size_t i = 0; i < size; i++) {
3399 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003400 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003401 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003402 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003403 }
3404 }
Eric Laurent13084622016-05-17 10:51:49 -07003405 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003406}
3407
Haynes Mathew George05317d22016-05-03 16:34:26 -07003408void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3409{
3410 Mutex::Autolock _l(mLock);
3411 invalidateTracks_l(streamType);
3412}
3413
jiabinf042b9b2021-05-07 23:46:28 +00003414// getTrackById_l must be called with holding thread lock
3415AudioFlinger::PlaybackThread::Track* AudioFlinger::PlaybackThread::getTrackById_l(
3416 audio_port_handle_t trackPortId) {
3417 for (size_t i = 0; i < mTracks.size(); i++) {
3418 if (mTracks[i]->portId() == trackPortId) {
3419 return mTracks[i].get();
3420 }
3421 }
3422 return nullptr;
3423}
3424
Eric Laurent81784c32012-11-19 14:55:58 -08003425status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3426{
Glenn Kastend848eb42016-03-08 13:42:11 -08003427 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003428 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003429 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08003430 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3431 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3432 &halInBuffer);
3433 if (result != OK) return result;
3434 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003435 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003436 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003437 if (!audio_is_global_session(session)) {
Eric Laurent81784c32012-11-19 14:55:58 -08003438 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003439 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003440 if (mType != DIRECT) {
Eric Laurentf1f22e72021-07-13 14:04:14 +02003441 size_t numSamples = mNormalFrameCount
3442 * (audio_channel_count_from_out_mask(mMixerChannelMask) + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003443 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003444 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003445 &halInBuffer);
3446 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003447#ifdef FLOAT_EFFECT_CHAIN
3448 buffer = halInBuffer->audioBuffer()->f32;
3449#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003450 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003451#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003452 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3453 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003454 }
3455
3456 // Attach all tracks with same session ID to this chain.
3457 for (size_t i = 0; i < mTracks.size(); ++i) {
3458 sp<Track> track = mTracks[i];
3459 if (session == track->sessionId()) {
3460 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3461 buffer);
3462 track->setMainBuffer(buffer);
3463 chain->incTrackCnt();
3464 }
3465 }
3466
3467 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003468 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003469 if (session == track->sessionId()) {
3470 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3471 chain->incActiveTrackCnt();
3472 }
3473 }
3474 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003475 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003476 chain->setInBuffer(halInBuffer);
3477 chain->setOutBuffer(halOutBuffer);
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003478 // Effect chain for session AUDIO_SESSION_DEVICE is inserted at end of effect
3479 // chains list in order to be processed last as it contains output device effects.
3480 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted just before to apply post
3481 // processing effects specific to an output stream before effects applied to all streams
3482 // routed to a given device.
Eric Laurent81784c32012-11-19 14:55:58 -08003483 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3484 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003485 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003486 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003487 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003488 // Effect chain for other sessions are inserted at beginning of effect
3489 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003490 // sessions is not important.
3491 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
Eric Laurent3f75a5b2019-11-12 15:55:51 -08003492 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX &&
3493 AUDIO_SESSION_DEVICE < AUDIO_SESSION_OUTPUT_STAGE,
Glenn Kastend848eb42016-03-08 13:42:11 -08003494 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003495 size_t size = mEffectChains.size();
3496 size_t i = 0;
3497 for (i = 0; i < size; i++) {
3498 if (mEffectChains[i]->sessionId() < session) {
3499 break;
3500 }
3501 }
3502 mEffectChains.insertAt(chain, i);
3503 checkSuspendOnAddEffectChain_l(chain);
3504
3505 return NO_ERROR;
3506}
3507
3508size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3509{
Glenn Kastend848eb42016-03-08 13:42:11 -08003510 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003511
3512 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3513
3514 for (size_t i = 0; i < mEffectChains.size(); i++) {
3515 if (chain == mEffectChains[i]) {
3516 mEffectChains.removeAt(i);
3517 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003518 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003519 if (session == track->sessionId()) {
3520 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3521 chain.get(), session);
3522 chain->decActiveTrackCnt();
3523 }
3524 }
3525
3526 // detach all tracks with same session ID from this chain
3527 for (size_t i = 0; i < mTracks.size(); ++i) {
3528 sp<Track> track = mTracks[i];
3529 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003530 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003531 chain->decTrackCnt();
3532 }
3533 }
3534 break;
3535 }
3536 }
3537 return mEffectChains.size();
3538}
3539
3540status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003541 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003542{
3543 Mutex::Autolock _l(mLock);
3544 return attachAuxEffect_l(track, EffectId);
3545}
3546
3547status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003548 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003549{
3550 status_t status = NO_ERROR;
3551
3552 if (EffectId == 0) {
3553 track->setAuxBuffer(0, NULL);
3554 } else {
3555 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3556 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3557 if (effect != 0) {
3558 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3559 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3560 } else {
3561 status = INVALID_OPERATION;
3562 }
3563 } else {
3564 status = BAD_VALUE;
3565 }
3566 }
3567 return status;
3568}
3569
3570void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3571{
3572 for (size_t i = 0; i < mTracks.size(); ++i) {
3573 sp<Track> track = mTracks[i];
3574 if (track->auxEffectId() == effectId) {
3575 attachAuxEffect_l(track, 0);
3576 }
3577 }
3578}
3579
3580bool AudioFlinger::PlaybackThread::threadLoop()
3581{
Glenn Kasten388d5712017-04-07 14:38:41 -07003582 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003583
Eric Laurent81784c32012-11-19 14:55:58 -08003584 Vector< sp<Track> > tracksToRemove;
3585
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003586 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003587 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
Eric Laurent81784c32012-11-19 14:55:58 -08003588
3589 // MIXER
3590 nsecs_t lastWarning = 0;
3591
3592 // DUPLICATING
3593 // FIXME could this be made local to while loop?
3594 writeFrames = 0;
3595
3596 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003597 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003598
3599 if (mType == MIXER) {
3600 sleepTimeShift = 0;
3601 }
3602
3603 CpuStats cpuStats;
3604 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3605
3606 acquireWakeLock();
3607
Glenn Kasteneef598c2017-04-03 14:41:13 -07003608 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3609 // thread associated with this PlaybackThread.
3610 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3611 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003612 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3613 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003614 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003615 const char *logString = NULL;
3616
rago1bb90822017-05-02 18:31:48 -07003617 // Estimated time for next buffer to be written to hal. This is used only on
3618 // suspended mode (for now) to help schedule the wait time until next iteration.
3619 nsecs_t timeLoopNextNs = 0;
3620
Eric Laurent664539d2013-09-23 18:24:31 -07003621 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003622
Andy Hung2dbffc22018-08-08 18:50:41 -07003623 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003624
Eric Laurentb3f315a2021-07-13 15:09:05 +02003625 sendCheckOutputStageEffectsEvent();
3626
Andy Hung446f4df2019-02-21 12:26:41 -08003627 // loopCount is used for statistics and diagnostics.
3628 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003629 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003630 // Log merge requests are performed during AudioFlinger binder transactions, but
3631 // that does not cover audio playback. It's requested here for that reason.
3632 mAudioFlinger->requestLogMerge();
3633
Eric Laurent81784c32012-11-19 14:55:58 -08003634 cpuStats.sample(myName);
3635
3636 Vector< sp<EffectChain> > effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003637 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Andy Hungc1646382019-04-30 16:12:10 -07003638 std::vector<sp<Track>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003639
Andy Hung2dbffc22018-08-08 18:50:41 -07003640 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3641 //
jiabinc52b1ff2019-10-31 17:20:42 -07003642 // Note: we access outDeviceTypes() outside of mLock.
3643 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003644 // Here, we try for the AF lock, but do not block on it as the latency
3645 // is more informational.
3646 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3647 std::vector<PatchPanel::SoftwarePatch> swPatches;
3648 double latencyMs;
3649 status_t status = INVALID_OPERATION;
3650 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3651 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3652 && swPatches.size() > 0) {
3653 status = swPatches[0].getLatencyMs_l(&latencyMs);
3654 downstreamPatchHandle = swPatches[0].getPatchHandle();
3655 }
3656 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003657 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003658 lastDownstreamPatchHandle = downstreamPatchHandle;
3659 }
3660 if (status == OK) {
3661 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003662 // latency of 5 seconds).
3663 const double minLatency = 0., maxLatency = 5000.;
3664 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10003665 ALOGVV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003666 } else {
3667 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003668 if (latencyMs < minLatency) latencyMs = minLatency;
3669 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003670 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003671 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003672 }
3673 mAudioFlinger->mLock.unlock();
3674 }
3675 } else {
3676 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3677 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003678 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003679 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3680 }
3681 }
3682
Eric Laurentb3f315a2021-07-13 15:09:05 +02003683 if (mCheckOutputStageEffects.exchange(false)) {
3684 checkOutputStageEffects();
3685 }
3686
Eric Laurent81784c32012-11-19 14:55:58 -08003687 { // scope for mLock
3688
3689 Mutex::Autolock _l(mLock);
3690
Eric Laurent021cf962014-05-13 10:18:14 -07003691 processConfigEvents_l();
Eric Laurentb3f315a2021-07-13 15:09:05 +02003692 if (mCheckOutputStageEffects.load()) {
3693 continue;
3694 }
Eric Laurent10351942014-05-08 18:49:52 -07003695
Glenn Kasteneef598c2017-04-03 14:41:13 -07003696 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003697 if (logString != NULL) {
3698 mNBLogWriter->logTimestamp();
3699 mNBLogWriter->log(logString);
3700 logString = NULL;
3701 }
3702
Dean Wheatley12473e92021-03-18 23:00:55 +11003703 collectTimestamps_l();
Andy Hungc8fddf32018-08-08 18:32:37 -07003704
Eric Laurent81784c32012-11-19 14:55:58 -08003705 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003706 if (mSignalPending) {
3707 // A signal was raised while we were unlocked
3708 mSignalPending = false;
3709 } else if (waitingAsyncCallback_l()) {
3710 if (exitPending()) {
3711 break;
3712 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003713 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003714 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003715 releaseWakeLock_l();
3716 released = true;
3717 }
Andy Hung10cbff12017-02-21 17:30:14 -08003718
3719 const int64_t waitNs = computeWaitTimeNs_l();
3720 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3721 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3722 if (status == TIMED_OUT) {
3723 mSignalPending = true; // if timeout recheck everything
3724 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003725 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003726 if (released) {
3727 acquireWakeLock_l();
3728 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003729 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3730 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003731
3732 continue;
3733 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003734 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003735 isSuspended()) {
3736 // put audio hardware into standby after short delay
3737 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003738
3739 threadLoop_standby();
3740
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003741 // This is where we go into standby
3742 if (!mStandby) {
3743 LOG_AUDIO_STATE();
Andy Hungcf10d742020-04-28 15:38:24 -07003744 mThreadMetrics.logEndInterval();
3745 mStandby = true;
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003746 }
Andy Hungd0979812019-02-21 15:51:44 -08003747 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003748 }
3749
Eric Tan39ec8d62018-07-24 09:49:29 -07003750 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003751 // we're about to wait, flush the binder command buffer
3752 IPCThreadState::self()->flushCommands();
3753
3754 clearOutputTracks();
3755
3756 if (exitPending()) {
3757 break;
3758 }
3759
3760 releaseWakeLock_l();
3761 // wait until we have something to do...
3762 ALOGV("%s going to sleep", myName.string());
3763 mWaitWorkCV.wait(mLock);
3764 ALOGV("%s waking up", myName.string());
3765 acquireWakeLock_l();
3766
3767 mMixerStatus = MIXER_IDLE;
3768 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3769 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003770 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003771 checkSilentMode_l();
3772
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003773 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3774 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003775 if (mType == MIXER) {
3776 sleepTimeShift = 0;
3777 }
3778
3779 continue;
3780 }
3781 }
Eric Laurent81784c32012-11-19 14:55:58 -08003782 // mMixerStatusIgnoringFastTracks is also updated internally
3783 mMixerStatus = prepareTracks_l(&tracksToRemove);
3784
Andy Hungdae27702016-10-31 14:01:16 -07003785 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003786
Kevin Rocard069c2712018-03-29 19:09:14 -07003787 updateMetadata_l();
3788
Eric Laurent81784c32012-11-19 14:55:58 -08003789 // prevent any changes in effect chain list and in each effect chain
3790 // during mixing and effect process as the audio buffers could be deleted
3791 // or modified if an effect is created or deleted
3792 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07003793
3794 // Determine which session to pick up haptic data.
3795 // This must be done under the same lock as prepareTracks_l().
jiabineb3bda02020-06-30 14:07:03 -07003796 // The haptic data from the effect is at a higher priority than the one from track.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003797 // TODO: Write haptic data directly to sink buffer when mixing.
3798 if (mHapticChannelCount > 0 && effectChains.size() > 0) {
3799 for (const auto& track : mActiveTracks) {
jiabineb3bda02020-06-30 14:07:03 -07003800 sp<EffectChain> effectChain = getEffectChain_l(track->sessionId());
3801 if (effectChain != nullptr && effectChain->containsHapticGeneratingEffect_l()) {
3802 activeHapticSessionId = track->sessionId();
3803 break;
3804 }
Andy Hung6e6a2e62019-04-30 16:38:41 -07003805 if (track->getHapticPlaybackEnabled()) {
3806 activeHapticSessionId = track->sessionId();
3807 break;
3808 }
3809 }
3810 }
3811
Andy Hungc1646382019-04-30 16:12:10 -07003812 // Acquire a local copy of active tracks with lock (release w/o lock).
3813 //
3814 // Control methods on the track acquire the ThreadBase lock (e.g. start()
3815 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
3816 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
3817 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003818 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003819
Eric Laurentbfb1b832013-01-07 09:53:42 -08003820 if (mBytesRemaining == 0) {
3821 mCurrentWriteLength = 0;
3822 if (mMixerStatus == MIXER_TRACKS_READY) {
3823 // threadLoop_mix() sets mCurrentWriteLength
3824 threadLoop_mix();
3825 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3826 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003827 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003828 // must be written to HAL
3829 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003830 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003831 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07003832
3833 // Tally underrun frames as we are inserting 0s here.
3834 for (const auto& track : activeTracks) {
Andy Hunge2e830f2019-12-03 12:54:46 -08003835 if (track->mFillingUpStatus == Track::FS_ACTIVE
3836 && !track->isStopped()
3837 && !track->isPaused()
3838 && !track->isTerminated()) {
3839 ALOGV("%s: track(%d) %s underrun due to thread sleep of %zu frames",
3840 __func__, track->id(), track->getTrackStateAsString(),
3841 mNormalFrameCount);
Andy Hungc1646382019-04-30 16:12:10 -07003842 track->mAudioTrackServerProxy->tallyUnderrunFrames(mNormalFrameCount);
3843 }
3844 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003845 }
3846 }
Andy Hung98ef9782014-03-04 14:46:50 -08003847 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003848 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003849 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3850 // or mSinkBuffer (if there are no effects).
3851 //
3852 // This is done pre-effects computation; if effects change to
3853 // support higher precision, this needs to move.
3854 //
3855 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003856 // TODO use mSleepTimeUs == 0 as an additional condition.
Eric Laurent39095982021-08-24 18:29:27 +02003857 uint32_t mixerChannelCount = mEffectBufferValid ?
3858 audio_channel_count_from_out_mask(mMixerChannelMask) : mChannelCount;
Andy Hung98ef9782014-03-04 14:46:50 -08003859 if (mMixerBufferValid) {
3860 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3861 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3862
Andy Hung2ddee192015-12-18 17:34:44 -08003863 // mono blend occurs for mixer threads only (not direct or offloaded)
3864 // and is handled here if we're going directly to the sink.
3865 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003866 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3867 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003868 }
3869
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003870 if (!hasFastMixer()) {
3871 // Balance must take effect after mono conversion.
3872 // We do it here if there is no FastMixer.
3873 // mBalance detects zero balance within the class for speed (not needed here).
3874 mBalance.setBalance(mMasterBalance.load());
3875 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
3876 }
3877
Andy Hung98ef9782014-03-04 14:46:50 -08003878 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
Eric Laurent39095982021-08-24 18:29:27 +02003879 mNormalFrameCount * (mixerChannelCount + mHapticChannelCount));
jiabin245cdd92018-12-07 17:55:15 -08003880
3881 // If we're going directly to the sink and there are haptic channels,
3882 // we should adjust channels as the sample data is partially interleaved
3883 // in this case.
3884 if (!mEffectBufferValid && mHapticChannelCount > 0) {
3885 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
3886 mChannelCount + mHapticChannelCount,
3887 audio_bytes_per_sample(format),
3888 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
3889 }
Andy Hung98ef9782014-03-04 14:46:50 -08003890 }
3891
Eric Laurentbfb1b832013-01-07 09:53:42 -08003892 mBytesRemaining = mCurrentWriteLength;
3893 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003894 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3895 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3896 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3897 mBytesWritten += mBytesRemaining;
3898 mFramesWritten += framesRemaining;
3899 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003900 mBytesRemaining = 0;
3901 }
Eric Laurent81784c32012-11-19 14:55:58 -08003902
Eric Laurentbfb1b832013-01-07 09:53:42 -08003903 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003904 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003905 for (size_t i = 0; i < effectChains.size(); i ++) {
3906 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07003907 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003908 if (activeHapticSessionId != AUDIO_SESSION_NONE
3909 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07003910 // Haptic data is active in this case, copy it directly from
3911 // in buffer to out buffer.
Eric Laurent39095982021-08-24 18:29:27 +02003912 uint32_t channelCount =
3913 effectChains[i]->sessionId() == AUDIO_SESSION_OUTPUT_STAGE ?
3914 mixerChannelCount : mChannelCount;
jiabin47affe52019-04-04 18:02:07 -07003915 const size_t audioBufferSize = mNormalFrameCount
Eric Laurent39095982021-08-24 18:29:27 +02003916 * audio_bytes_per_frame(channelCount, EFFECT_BUFFER_FORMAT);
jiabin47affe52019-04-04 18:02:07 -07003917 memcpy_by_audio_format(
3918 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
3919 EFFECT_BUFFER_FORMAT,
3920 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
3921 EFFECT_BUFFER_FORMAT, mNormalFrameCount * mHapticChannelCount);
3922 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003923 }
Eric Laurent81784c32012-11-19 14:55:58 -08003924 }
3925 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003926 // Process effect chains for offloaded thread even if no audio
3927 // was read from audio track: process only updates effect state
3928 // and thus does have to be synchronized with audio writes but may have
3929 // to be called while waiting for async write callback
3930 if (mType == OFFLOAD) {
3931 for (size_t i = 0; i < effectChains.size(); i ++) {
3932 effectChains[i]->process_l();
3933 }
3934 }
Eric Laurent81784c32012-11-19 14:55:58 -08003935
Andy Hung98ef9782014-03-04 14:46:50 -08003936 // Only if the Effects buffer is enabled and there is data in the
3937 // Effects buffer (buffer valid), we need to
3938 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003939 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003940 if (mEffectBufferValid) {
3941 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003942
3943 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003944 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3945 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003946 }
3947
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003948 if (!hasFastMixer()) {
3949 // Balance must take effect after mono conversion.
3950 // We do it here if there is no FastMixer.
3951 // mBalance detects zero balance within the class for speed (not needed here).
3952 mBalance.setBalance(mMasterBalance.load());
3953 mBalance.process((float *)mEffectBuffer, mNormalFrameCount);
3954 }
3955
Eric Laurent39095982021-08-24 18:29:27 +02003956 if (mType == SPATIALIZER) {
3957 memcpy_by_audio_format(mEffectToSinkBuffer, mFormat, mEffectBuffer,
3958 mEffectBufferFormat,
3959 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3960 accumulate_by_audio_format(mSinkBuffer, mEffectToSinkBuffer, mFormat,
3961 mNormalFrameCount * mChannelCount);
3962 const size_t audioBufferSize = mNormalFrameCount
3963 * audio_bytes_per_frame(mChannelCount, mFormat);
3964 memcpy_by_audio_format(
3965 (uint8_t*)mSinkBuffer + audioBufferSize,
3966 mFormat,
3967 (uint8_t*)mEffectToSinkBuffer + audioBufferSize,
3968 mFormat, mNormalFrameCount * mHapticChannelCount);
3969 } else {
3970 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
3971 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3972 }
jiabin245cdd92018-12-07 17:55:15 -08003973 // The sample data is partially interleaved when haptic channels exist,
3974 // we need to adjust channels here.
3975 if (mHapticChannelCount > 0) {
3976 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
3977 mChannelCount + mHapticChannelCount,
3978 audio_bytes_per_sample(mFormat),
3979 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
3980 }
Andy Hung98ef9782014-03-04 14:46:50 -08003981 }
3982
Eric Laurent81784c32012-11-19 14:55:58 -08003983 // enable changes in effect chain
3984 unlockEffectChains(effectChains);
3985
Eric Laurentbfb1b832013-01-07 09:53:42 -08003986 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003987 // mSleepTimeUs == 0 means we must write to audio hardware
3988 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003989 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003990 // writePeriodNs is updated >= 0 when ret > 0.
3991 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003992 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003993 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08003994 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07003995 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08003996 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003997 if (ret < 0) {
3998 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003999 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08004000 mBytesWritten += ret;
4001 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08004002 const int64_t frames = ret / mFrameSize;
4003 mFramesWritten += frames;
4004
4005 writePeriodNs = lastIoEndNs - mLastIoEndNs;
4006 // process information relating to write time.
4007 if (audio_has_proportional_frames(mFormat)) {
4008 // we are in a continuous mixing cycle
4009 if (mMixerStatus == MIXER_TRACKS_READY &&
4010 loopCount == lastLoopCountWritten + 1) {
4011
4012 const double jitterMs =
4013 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
4014 {frames, writePeriodNs},
4015 {0, 0} /* lastTimestamp */, mSampleRate);
4016 const double processMs =
4017 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
4018
4019 Mutex::Autolock _l(mLock);
4020 mIoJitterMs.add(jitterMs);
4021 mProcessTimeMs.add(processMs);
Robert Wu06db0a32021-08-10 19:05:34 +00004022
4023 if (mPipeSink.get() != nullptr) {
4024 // Using the Monopipe availableToWrite, we estimate the current
4025 // buffer size.
4026 MonoPipe* monoPipe = static_cast<MonoPipe*>(mPipeSink.get());
4027 const ssize_t
4028 availableToWrite = mPipeSink->availableToWrite();
4029 const size_t pipeFrames = monoPipe->maxFrames();
4030 const size_t
4031 remainingFrames = pipeFrames - max(availableToWrite, 0);
4032 mMonopipePipeDepthStats.add(remainingFrames);
4033 }
Andy Hung446f4df2019-02-21 12:26:41 -08004034 }
4035
4036 // write blocked detection
4037 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
4038 if (mType == MIXER && deltaWriteNs > maxPeriod) {
4039 mNumDelayedWrites++;
4040 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
4041 ATRACE_NAME("underrun");
4042 ALOGW("write blocked for %lld msecs, "
4043 "%d delayed writes, thread %d",
4044 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
4045 mNumDelayedWrites, mId);
4046 lastWarning = lastIoEndNs;
4047 }
4048 }
4049 }
4050 // update timing info.
4051 mLastIoBeginNs = lastIoBeginNs;
4052 mLastIoEndNs = lastIoEndNs;
4053 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004054 }
4055 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
4056 (mMixerStatus == MIXER_DRAIN_ALL)) {
4057 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08004058 }
Andy Hung08fb1742015-05-31 23:22:10 -07004059 if (mType == MIXER && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07004060
4061 if (mThreadThrottle
4062 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08004063 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07004064 // Limit MixerThread data processing to no more than twice the
4065 // expected processing rate.
4066 //
4067 // This helps prevent underruns with NuPlayer and other applications
4068 // which may set up buffers that are close to the minimum size, or use
4069 // deep buffers, and rely on a double-buffering sleep strategy to fill.
4070 //
4071 // The throttle smooths out sudden large data drains from the device,
4072 // e.g. when it comes out of standby, which often causes problems with
4073 // (1) mixer threads without a fast mixer (which has its own warm-up)
4074 // (2) minimum buffer sized tracks (even if the track is full,
4075 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07004076 //
4077 // Total time spent in last processing cycle equals time spent in
4078 // 1. threadLoop_write, as well as time spent in
4079 // 2. threadLoop_mix (significant for heavy mixing, especially
4080 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07004081
Andy Hung446f4df2019-02-21 12:26:41 -08004082 // it's OK if deltaMs is an overestimate.
4083
4084 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07004085
Ivan Lozanoea04d392017-11-07 14:37:07 -08004086 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07004087 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
Andy Hungcf10d742020-04-28 15:38:24 -07004088 mThreadMetrics.logThrottleMs((double)throttleMs);
Andy Hungb68f5eb2019-12-03 16:49:17 -08004089
Andy Hung08fb1742015-05-31 23:22:10 -07004090 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07004091 // notify of throttle start on verbose log
4092 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
4093 "mixer(%p) throttle begin:"
4094 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07004095 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07004096 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07004097 // Throttle must be attributed to the previous mixer loop's write time
4098 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08004099 // This also ensures proper timing statistics.
4100 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07004101 } else {
4102 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
4103 if (diff > 0) {
4104 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07004105 // but prevent spamming for bluetooth
jiabinc52b1ff2019-10-31 17:20:42 -07004106 ALOGD_IF(!isSingleDeviceType(
4107 outDeviceTypes(), audio_is_a2dp_out_device) &&
4108 !isSingleDeviceType(
4109 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07004110 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07004111 mThreadThrottleEndMs = mThreadThrottleTimeMs;
4112 }
Andy Hung08fb1742015-05-31 23:22:10 -07004113 }
4114 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004115 }
Eric Laurent81784c32012-11-19 14:55:58 -08004116
Eric Laurentbfb1b832013-01-07 09:53:42 -08004117 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07004118 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07004119 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07004120 // suspended requires accurate metering of sleep time.
4121 if (isSuspended()) {
4122 // advance by expected sleepTime
4123 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
4124 const nsecs_t nowNs = systemTime();
4125
4126 // compute expected next time vs current time.
4127 // (negative deltas are treated as delays).
4128 nsecs_t deltaNs = timeLoopNextNs - nowNs;
4129 if (deltaNs < -kMaxNextBufferDelayNs) {
4130 // Delays longer than the max allowed trigger a reset.
4131 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
4132 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
4133 timeLoopNextNs = nowNs + deltaNs;
4134 } else if (deltaNs < 0) {
4135 // Delays within the max delay allowed: zero the delta/sleepTime
4136 // to help the system catch up in the next iteration(s)
4137 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
4138 deltaNs = 0;
4139 }
4140 // update sleep time (which is >= 0)
4141 mSleepTimeUs = deltaNs / 1000;
4142 }
Eric Laurente93cc032016-05-05 10:15:10 -07004143 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
4144 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08004145 }
Glenn Kastene7754022014-10-31 12:11:26 -07004146 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004147 }
Eric Laurent81784c32012-11-19 14:55:58 -08004148 }
4149
4150 // Finally let go of removed track(s), without the lock held
4151 // since we can't guarantee the destructors won't acquire that
4152 // same lock. This will also mutate and push a new fast mixer state.
4153 threadLoop_removeTracks(tracksToRemove);
4154 tracksToRemove.clear();
4155
4156 // FIXME I don't understand the need for this here;
4157 // it was in the original code but maybe the
4158 // assignment in saveOutputTracks() makes this unnecessary?
4159 clearOutputTracks();
4160
4161 // Effect chains will be actually deleted here if they were removed from
4162 // mEffectChains list during mixing or effects processing
4163 effectChains.clear();
4164
4165 // FIXME Note that the above .clear() is no longer necessary since effectChains
4166 // is now local to this block, but will keep it for now (at least until merge done).
4167 }
4168
Eric Laurentbfb1b832013-01-07 09:53:42 -08004169 threadLoop_exit();
4170
Eric Laurentcf817a22014-08-04 20:36:31 -07004171 if (!mStandby) {
4172 threadLoop_standby();
4173 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004174 }
4175
4176 releaseWakeLock();
4177
4178 ALOGV("Thread %p type %d exiting", this, mType);
4179 return false;
4180}
4181
Dean Wheatley12473e92021-03-18 23:00:55 +11004182void AudioFlinger::PlaybackThread::collectTimestamps_l()
4183{
4184 // Collect timestamp statistics for the Playback Thread types that support it.
4185 if (mType != MIXER
4186 && mType != DUPLICATING
4187 && mType != DIRECT
4188 && mType != OFFLOAD) {
4189 return;
4190 }
4191 if (mStandby) {
4192 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
4193 return;
4194 } else if (mHwPaused) {
4195 mTimestampVerifier.discontinuity(mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS);
4196 return;
4197 }
4198
4199 // Gather the framesReleased counters for all active tracks,
4200 // and associate with the sink frames written out. We need
4201 // this to convert the sink timestamp to the track timestamp.
4202 bool kernelLocationUpdate = false;
4203 ExtendedTimestamp timestamp; // use private copy to fetch
4204
4205 // Always query HAL timestamp and update timestamp verifier. In standby or pause,
4206 // HAL may be draining some small duration buffered data for fade out.
4207 if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
4208 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
4209 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4210 mSampleRate);
4211
4212 if (isTimestampCorrectionEnabled()) {
4213 ALOGVV("TS_BEFORE: %d %lld %lld", id(),
4214 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4215 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4216 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
4217 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4218 = correctedTimestamp.mFrames;
4219 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
4220 = correctedTimestamp.mTimeNs;
4221 ALOGVV("TS_AFTER: %d %lld %lld", id(),
4222 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
4223 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
4224
4225 // Note: Downstream latency only added if timestamp correction enabled.
4226 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
4227 const int64_t newPosition =
4228 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4229 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
4230 // prevent retrograde
4231 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
4232 newPosition,
4233 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4234 - mSuspendedFrames));
4235 }
4236 }
4237
4238 // We always fetch the timestamp here because often the downstream
4239 // sink will block while writing.
4240
4241 // We keep track of the last valid kernel position in case we are in underrun
4242 // and the normal mixer period is the same as the fast mixer period, or there
4243 // is some error from the HAL.
4244 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4245 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4246 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4247 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
4248 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4249
4250 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4251 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
4252 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
4253 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
4254 }
4255
4256 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
4257 kernelLocationUpdate = true;
4258 } else {
4259 ALOGVV("getTimestamp error - no valid kernel position");
4260 }
4261
4262 // copy over kernel info
4263 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
4264 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
4265 + mSuspendedFrames; // add frames discarded when suspended
4266 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
4267 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4268 } else {
4269 mTimestampVerifier.error();
4270 }
4271
4272 // mFramesWritten for non-offloaded tracks are contiguous
4273 // even after standby() is called. This is useful for the track frame
4274 // to sink frame mapping.
4275 bool serverLocationUpdate = false;
4276 if (mFramesWritten != mLastFramesWritten) {
4277 serverLocationUpdate = true;
4278 mLastFramesWritten = mFramesWritten;
4279 }
4280 // Only update timestamps if there is a meaningful change.
4281 // Either the kernel timestamp must be valid or we have written something.
4282 if (kernelLocationUpdate || serverLocationUpdate) {
4283 if (serverLocationUpdate) {
4284 // use the time before we called the HAL write - it is a bit more accurate
4285 // to when the server last read data than the current time here.
4286 //
4287 // If we haven't written anything, mLastIoBeginNs will be -1
4288 // and we use systemTime().
4289 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
4290 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
4291 ? systemTime() : mLastIoBeginNs;
4292 }
4293
4294 for (const sp<Track> &t : mActiveTracks) {
4295 if (!t->isFastTrack()) {
4296 t->updateTrackFrameInfo(
4297 t->mAudioTrackServerProxy->framesReleased(),
4298 mFramesWritten,
4299 mSampleRate,
4300 mTimestamp);
4301 }
4302 }
4303 }
4304
4305 if (audio_has_proportional_frames(mFormat)) {
4306 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
4307 if (latencyMs != 0.) { // note 0. means timestamp is empty.
4308 mLatencyMs.add(latencyMs);
4309 }
4310 }
4311#if 0
4312 // logFormat example
4313 if (z % 100 == 0) {
4314 timespec ts;
4315 clock_gettime(CLOCK_MONOTONIC, &ts);
4316 LOGT("This is an integer %d, this is a float %f, this is my "
4317 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
4318 LOGT("A deceptive null-terminated string %\0");
4319 }
4320 ++z;
4321#endif
4322}
4323
Eric Laurentbfb1b832013-01-07 09:53:42 -08004324// removeTracks_l() must be called with ThreadBase::mLock held
4325void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
4326{
Andy Hungfe726a62018-09-27 15:17:25 -07004327 for (const auto& track : tracksToRemove) {
4328 mActiveTracks.remove(track);
4329 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
4330 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
4331 if (chain != 0) {
4332 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
4333 __func__, track->id(), chain.get(), track->sessionId());
4334 chain->decActiveTrackCnt();
4335 }
4336 // If an external client track, inform APM we're no longer active, and remove if needed.
4337 // We do this under lock so that the state is consistent if the Track is destroyed.
4338 if (track->isExternalTrack()) {
4339 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004340 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07004341 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08004342 }
4343 }
Andy Hungfe726a62018-09-27 15:17:25 -07004344 if (track->isTerminated()) {
4345 // remove from our tracks vector
4346 removeTrack_l(track);
4347 }
jiabineb3bda02020-06-30 14:07:03 -07004348 if (mHapticChannelCount > 0 &&
4349 ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
4350 || (chain != nullptr && chain->containsHapticGeneratingEffect_l()))) {
jiabin57303cc2018-12-18 15:45:57 -08004351 mLock.unlock();
4352 // Unlock due to VibratorService will lock for this call and will
4353 // call Tracks.mute/unmute which also require thread's lock.
4354 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
4355 mLock.lock();
jiabine70bc7f2020-06-30 22:07:55 -07004356
4357 // When the track is stop, set the haptic intensity as MUTE
4358 // for the HapticGenerator effect.
4359 if (chain != nullptr) {
4360 chain->setHapticIntensity_l(track->id(), static_cast<int>(os::HapticScale::MUTE));
4361 }
jiabin245cdd92018-12-07 17:55:15 -08004362 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004363 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004364}
Eric Laurent81784c32012-11-19 14:55:58 -08004365
Eric Laurentaccc1472013-09-20 09:36:34 -07004366status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
4367{
4368 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08004369 ExtendedTimestamp ets;
4370 status_t status = mNormalSink->getTimestamp(ets);
4371 if (status == NO_ERROR) {
4372 status = ets.getBestTimestamp(&timestamp);
4373 }
4374 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07004375 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004376 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Dean Wheatley12473e92021-03-18 23:00:55 +11004377 collectTimestamps_l();
4378 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] <= 0) {
4379 return INVALID_OPERATION;
Eric Laurentaccc1472013-09-20 09:36:34 -07004380 }
Dean Wheatley12473e92021-03-18 23:00:55 +11004381 timestamp.mPosition = mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
4382 const int64_t timeNs = mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
4383 timestamp.mTime.tv_sec = timeNs / NANOS_PER_SECOND;
4384 timestamp.mTime.tv_nsec = timeNs - (timestamp.mTime.tv_sec * NANOS_PER_SECOND);
4385 return NO_ERROR;
Eric Laurentaccc1472013-09-20 09:36:34 -07004386 }
4387 return INVALID_OPERATION;
4388}
Eric Laurent1c333e22014-05-20 10:48:17 -07004389
Eric Laurenteab90452019-06-24 15:17:46 -07004390// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
4391// still applied by the mixer.
4392// All tracks attached to a mixer with flag VOIP_RX are tied to the same
4393// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
4394// if more than one track are active
4395status_t AudioFlinger::PlaybackThread::handleVoipVolume_l(float *volume)
4396{
4397 status_t result = NO_ERROR;
4398 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
4399 if (*volume != mLeftVolFloat) {
4400 result = mOutput->stream->setVolume(*volume, *volume);
4401 ALOGE_IF(result != OK,
4402 "Error when setting output stream volume: %d", result);
4403 if (result == NO_ERROR) {
4404 mLeftVolFloat = *volume;
4405 }
4406 }
4407 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4408 // remove stream volume contribution from software volume.
4409 if (mLeftVolFloat == *volume) {
4410 *volume = 1.0f;
4411 }
4412 }
4413 return result;
4414}
4415
Eric Laurent054d9d32015-04-24 08:48:48 -07004416status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
4417 audio_patch_handle_t *handle)
4418{
Andy Hungf60abce2016-08-26 11:37:54 -07004419 status_t status;
4420 if (property_get_bool("af.patch_park", false /* default_value */)) {
4421 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4422 // or if HAL does not properly lock against access.
4423 AutoPark<FastMixer> park(mFastMixer);
4424 status = PlaybackThread::createAudioPatch_l(patch, handle);
4425 } else {
4426 status = PlaybackThread::createAudioPatch_l(patch, handle);
4427 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004428 return status;
4429}
4430
Eric Laurent1c333e22014-05-20 10:48:17 -07004431status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
4432 audio_patch_handle_t *handle)
4433{
4434 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004435
4436 // store new device and send to effects
4437 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabinc52b1ff2019-10-31 17:20:42 -07004438 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004439 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07004440 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4441 && !mOutput->audioHwDev->supportsAudioPatches(),
4442 "Enumerated device type(%#x) must not be used "
4443 "as it does not support audio patches",
4444 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07004445 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07004446 deviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
4447 patch->sinks[i].ext.device.address));
Eric Laurent054d9d32015-04-24 08:48:48 -07004448 }
4449
François Gaffie0c280aa2018-07-25 10:02:15 +02004450 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004451#ifdef ADD_BATTERY_DATA
4452 // when changing the audio output device, call addBatteryData to notify
4453 // the change
jiabinc52b1ff2019-10-31 17:20:42 -07004454 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004455 uint32_t params = 0;
4456 // check whether speaker is on
jiabinc52b1ff2019-10-31 17:20:42 -07004457 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004458 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004459 }
4460
Eric Laurent054d9d32015-04-24 08:48:48 -07004461 // check if any other device (except speaker) is on
jiabinc52b1ff2019-10-31 17:20:42 -07004462 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004463 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4464 }
4465
4466 if (params != 0) {
4467 addBatteryData(params);
4468 }
4469 }
4470#endif
4471
4472 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08004473 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004474 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004475
jiabinc52b1ff2019-10-31 17:20:42 -07004476 // mPatch.num_sinks is not set when the thread is created so that
4477 // the first patch creation triggers an ioConfigChanged callback
4478 bool configChanged = (mPatch.num_sinks == 0) ||
4479 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004480 mPatch = *patch;
jiabinc52b1ff2019-10-31 17:20:42 -07004481 mOutDeviceTypeAddrs = deviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07004482 checkSilentMode_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07004483
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004484 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004485 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4486 status = hwDevice->createAudioPatch(patch->num_sources,
4487 patch->sources,
4488 patch->num_sinks,
4489 patch->sinks,
4490 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004491 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004492 char *address;
4493 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
4494 //FIXME: we only support address on first sink with HAL version < 3.0
4495 address = audio_device_address_to_parameter(
4496 patch->sinks[0].ext.device.type,
4497 patch->sinks[0].ext.device.address);
4498 } else {
4499 address = (char *)calloc(1, 1);
4500 }
4501 AudioParameter param = AudioParameter(String8(address));
4502 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07004503 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004504 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07004505 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004506 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07004507 const std::string patchSinksAsString = patchSinksToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07004508
4509 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07004510 mThreadMetrics.logCreatePatch(/* inDevices */ {}, patchSinksAsString);
Andy Hungcf10d742020-04-28 15:38:24 -07004511 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07004512 // also dispatch to active AudioTracks for MediaMetrics
4513 for (const auto &track : mActiveTracks) {
4514 track->logEndInterval();
4515 track->logBeginInterval(patchSinksAsString);
4516 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08004517
Eric Laurente8726fe2015-06-26 09:39:24 -07004518 if (configChanged) {
4519 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4520 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004521 return status;
4522}
4523
Eric Laurent054d9d32015-04-24 08:48:48 -07004524status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4525{
Andy Hungf60abce2016-08-26 11:37:54 -07004526 status_t status;
4527 if (property_get_bool("af.patch_park", false /* default_value */)) {
4528 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4529 // or if HAL does not properly lock against access.
4530 AutoPark<FastMixer> park(mFastMixer);
4531 status = PlaybackThread::releaseAudioPatch_l(handle);
4532 } else {
4533 status = PlaybackThread::releaseAudioPatch_l(handle);
4534 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004535 return status;
4536}
4537
Eric Laurent1c333e22014-05-20 10:48:17 -07004538status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4539{
4540 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004541
jiabinc52b1ff2019-10-31 17:20:42 -07004542 mPatch = audio_patch{};
4543 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004544
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004545 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004546 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4547 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004548 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004549 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07004550 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004551 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07004552 }
4553 return status;
4554}
4555
Eric Laurent83b88082014-06-20 18:31:16 -07004556void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
4557{
4558 Mutex::Autolock _l(mLock);
4559 mTracks.add(track);
4560}
4561
4562void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
4563{
4564 Mutex::Autolock _l(mLock);
4565 destroyTrack_l(track);
4566}
4567
Mikhail Naganovdc769682018-05-04 15:34:08 -07004568void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07004569{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004570 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004571 config->role = AUDIO_PORT_ROLE_SOURCE;
4572 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4573 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004574 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4575 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4576 config->flags.output = mOutput->flags;
4577 }
Eric Laurent83b88082014-06-20 18:31:16 -07004578}
4579
Eric Laurent81784c32012-11-19 14:55:58 -08004580// ----------------------------------------------------------------------------
4581
4582AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
Eric Laurentf1f22e72021-07-13 14:04:14 +02004583 audio_io_handle_t id, bool systemReady, type_t type, audio_config_base_t *mixerConfig)
4584 : PlaybackThread(audioFlinger, output, id, type, systemReady, mixerConfig),
Eric Laurent81784c32012-11-19 14:55:58 -08004585 // mAudioMixer below
4586 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004587 mFastMixerFutex(0),
4588 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004589 // mOutputSink below
4590 // mPipeSink below
4591 // mNormalSink below
4592{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004593 setMasterBalance(audioFlinger->getMasterBalance_l());
jiabinc52b1ff2019-10-31 17:20:42 -07004594 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004595 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004596 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004597 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4598 mNormalFrameCount);
4599 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4600
Andy Hungfbfc3952015-01-15 13:33:51 -08004601 if (type == DUPLICATING) {
4602 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4603 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4604 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4605 return;
4606 }
Eric Laurent81784c32012-11-19 14:55:58 -08004607 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004608 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004609 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004610 const NBAIO_Format offers[1] = {Format_from_SR_C(
4611 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004612#if !LOG_NDEBUG
4613 ssize_t index =
4614#else
4615 (void)
4616#endif
4617 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004618 ALOG_ASSERT(index == 0);
4619
4620 // initialize fast mixer depending on configuration
4621 bool initFastMixer;
4622 switch (kUseFastMixer) {
4623 case FastMixer_Never:
4624 initFastMixer = false;
4625 break;
4626 case FastMixer_Always:
4627 initFastMixer = true;
4628 break;
4629 case FastMixer_Static:
4630 case FastMixer_Dynamic:
Robert Wu7be8c902021-08-06 22:37:54 +00004631 initFastMixer = mFrameCount < mNormalFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004632 break;
4633 }
Eric Laurent39095982021-08-24 18:29:27 +02004634 ALOG_ASSERT(initFastMixer && mType == SPATIALIZER);
Andy Hungfda69402017-02-15 14:33:12 -08004635 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4636 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4637 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004638 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004639 audio_format_t fastMixerFormat;
4640 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4641 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4642 } else {
4643 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4644 }
4645 if (mFormat != fastMixerFormat) {
4646 // change our Sink format to accept our intermediate precision
4647 mFormat = fastMixerFormat;
4648 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004649 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004650 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4651 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4652 }
Eric Laurent81784c32012-11-19 14:55:58 -08004653
4654 // create a MonoPipe to connect our submix to FastMixer
4655 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004656
Andy Hung1258c1a2014-05-23 21:22:17 -07004657 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004658 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004659 format.mFormat = fastMixerFormat;
4660 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4661
Eric Laurent81784c32012-11-19 14:55:58 -08004662 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4663 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4664 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4665 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4666 const NBAIO_Format offers[1] = {format};
4667 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004668#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004669 ssize_t index =
4670#else
4671 (void)
4672#endif
4673 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004674 ALOG_ASSERT(index == 0);
4675 monoPipe->setAvgFrames((mScreenState & 1) ?
4676 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4677 mPipeSink = monoPipe;
4678
Eric Laurent81784c32012-11-19 14:55:58 -08004679 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004680 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004681 FastMixerStateQueue *sq = mFastMixer->sq();
4682#ifdef STATE_QUEUE_DUMP
4683 sq->setObserverDump(&mStateQueueObserverDump);
4684 sq->setMutatorDump(&mStateQueueMutatorDump);
4685#endif
4686 FastMixerState *state = sq->begin();
4687 FastTrack *fastTrack = &state->mFastTracks[0];
4688 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4689 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4690 fastTrack->mVolumeProvider = NULL;
Mikhail Naganov55773032020-10-01 15:08:13 -07004691 fastTrack->mChannelMask = static_cast<audio_channel_mask_t>(
4692 mChannelMask | mHapticChannelMask); // mPipeSink channel mask for
4693 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004694 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004695 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabine70bc7f2020-06-30 22:07:55 -07004696 fastTrack->mHapticIntensity = os::HapticScale::NONE;
Lais Andradebc3f37a2021-07-02 00:13:19 +01004697 fastTrack->mHapticMaxAmplitude = NAN;
Eric Laurent81784c32012-11-19 14:55:58 -08004698 fastTrack->mGeneration++;
4699 state->mFastTracksGen++;
4700 state->mTrackMask = 1;
4701 // fast mixer will use the HAL output sink
4702 state->mOutputSink = mOutputSink.get();
4703 state->mOutputSinkGen++;
4704 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004705 // specify sink channel mask when haptic channel mask present as it can not
4706 // be calculated directly from channel count
4707 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
Mikhail Naganov55773032020-10-01 15:08:13 -07004708 ? AUDIO_CHANNEL_NONE
4709 : static_cast<audio_channel_mask_t>(mChannelMask | mHapticChannelMask);
Eric Laurent81784c32012-11-19 14:55:58 -08004710 state->mCommand = FastMixerState::COLD_IDLE;
4711 // already done in constructor initialization list
4712 //mFastMixerFutex = 0;
4713 state->mColdFutexAddr = &mFastMixerFutex;
4714 state->mColdGen++;
4715 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004716 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4717 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004718 sq->end();
4719 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4720
Eric Tan0513b5d2018-09-17 10:32:48 -07004721 NBLog::thread_info_t info;
4722 info.id = mId;
4723 info.type = NBLog::FASTMIXER;
4724 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4725
Eric Laurent81784c32012-11-19 14:55:58 -08004726 // start the fast mixer
4727 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4728 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004729 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004730 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004731
4732#ifdef AUDIO_WATCHDOG
4733 // create and start the watchdog
4734 mAudioWatchdog = new AudioWatchdog();
4735 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4736 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4737 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004738 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004739#endif
Andy Hung8946a282018-04-19 20:04:56 -07004740 } else {
4741#ifdef TEE_SINK
4742 // Only use the MixerThread tee if there is no FastMixer.
4743 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4744 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4745#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004746 }
4747
4748 switch (kUseFastMixer) {
4749 case FastMixer_Never:
4750 case FastMixer_Dynamic:
4751 mNormalSink = mOutputSink;
4752 break;
4753 case FastMixer_Always:
4754 mNormalSink = mPipeSink;
4755 break;
4756 case FastMixer_Static:
4757 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4758 break;
4759 }
4760}
4761
4762AudioFlinger::MixerThread::~MixerThread()
4763{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004764 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004765 FastMixerStateQueue *sq = mFastMixer->sq();
4766 FastMixerState *state = sq->begin();
4767 if (state->mCommand == FastMixerState::COLD_IDLE) {
4768 int32_t old = android_atomic_inc(&mFastMixerFutex);
4769 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004770 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004771 }
4772 }
4773 state->mCommand = FastMixerState::EXIT;
4774 sq->end();
4775 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4776 mFastMixer->join();
4777 // Though the fast mixer thread has exited, it's state queue is still valid.
4778 // We'll use that extract the final state which contains one remaining fast track
4779 // corresponding to our sub-mix.
4780 state = sq->begin();
4781 ALOG_ASSERT(state->mTrackMask == 1);
4782 FastTrack *fastTrack = &state->mFastTracks[0];
4783 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4784 delete fastTrack->mBufferProvider;
4785 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004786 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004787#ifdef AUDIO_WATCHDOG
4788 if (mAudioWatchdog != 0) {
4789 mAudioWatchdog->requestExit();
4790 mAudioWatchdog->requestExitAndWait();
4791 mAudioWatchdog.clear();
4792 }
4793#endif
4794 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004795 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004796 delete mAudioMixer;
4797}
4798
4799
4800uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4801{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004802 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004803 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4804 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4805 }
4806 return latency;
4807}
4808
Eric Laurentbfb1b832013-01-07 09:53:42 -08004809ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004810{
4811 // FIXME we should only do one push per cycle; confirm this is true
4812 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004813 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004814 FastMixerStateQueue *sq = mFastMixer->sq();
4815 FastMixerState *state = sq->begin();
4816 if (state->mCommand != FastMixerState::MIX_WRITE &&
4817 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4818 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004819
4820 // FIXME workaround for first HAL write being CPU bound on some devices
4821 ATRACE_BEGIN("write");
4822 mOutput->write((char *)mSinkBuffer, 0);
4823 ATRACE_END();
4824
Eric Laurent81784c32012-11-19 14:55:58 -08004825 int32_t old = android_atomic_inc(&mFastMixerFutex);
4826 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004827 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004828 }
4829#ifdef AUDIO_WATCHDOG
4830 if (mAudioWatchdog != 0) {
4831 mAudioWatchdog->resume();
4832 }
4833#endif
4834 }
4835 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004836#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004837 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004838 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004839#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004840 sq->end();
4841 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4842 if (kUseFastMixer == FastMixer_Dynamic) {
4843 mNormalSink = mPipeSink;
4844 }
4845 } else {
4846 sq->end(false /*didModify*/);
4847 }
4848 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004849 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004850}
4851
4852void AudioFlinger::MixerThread::threadLoop_standby()
4853{
4854 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004855 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004856 FastMixerStateQueue *sq = mFastMixer->sq();
4857 FastMixerState *state = sq->begin();
4858 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004859 // Report any frames trapped in the Monopipe
4860 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4861 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4862 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4863 "monoPipeWritten:%lld monoPipeLeft:%lld",
4864 (long long)mFramesWritten, (long long)mSuspendedFrames,
4865 (long long)mPipeSink->framesWritten(), pipeFrames);
4866 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4867
Eric Laurent81784c32012-11-19 14:55:58 -08004868 state->mCommand = FastMixerState::COLD_IDLE;
4869 state->mColdFutexAddr = &mFastMixerFutex;
4870 state->mColdGen++;
4871 mFastMixerFutex = 0;
4872 sq->end();
4873 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4874 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4875 if (kUseFastMixer == FastMixer_Dynamic) {
4876 mNormalSink = mOutputSink;
4877 }
4878#ifdef AUDIO_WATCHDOG
4879 if (mAudioWatchdog != 0) {
4880 mAudioWatchdog->pause();
4881 }
4882#endif
4883 } else {
4884 sq->end(false /*didModify*/);
4885 }
4886 }
4887 PlaybackThread::threadLoop_standby();
4888}
4889
Eric Laurentbfb1b832013-01-07 09:53:42 -08004890bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4891{
4892 return false;
4893}
4894
4895bool AudioFlinger::PlaybackThread::shouldStandby_l()
4896{
4897 return !mStandby;
4898}
4899
4900bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4901{
4902 Mutex::Autolock _l(mLock);
4903 return waitingAsyncCallback_l();
4904}
4905
Eric Laurent81784c32012-11-19 14:55:58 -08004906// shared by MIXER and DIRECT, overridden by DUPLICATING
4907void AudioFlinger::PlaybackThread::threadLoop_standby()
4908{
4909 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004910 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004911 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004912 // discard any pending drain or write ack by incrementing sequence
4913 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4914 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004915 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004916 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4917 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004918 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004919 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004920}
4921
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004922void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4923{
4924 ALOGV("signal playback thread");
4925 broadcast_l();
4926}
4927
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004928void AudioFlinger::PlaybackThread::onAsyncError()
4929{
4930 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4931 invalidateTracks((audio_stream_type_t)i);
4932 }
4933}
4934
Eric Laurent81784c32012-11-19 14:55:58 -08004935void AudioFlinger::MixerThread::threadLoop_mix()
4936{
Eric Laurent81784c32012-11-19 14:55:58 -08004937 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004938 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004939 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004940 // increase sleep time progressively when application underrun condition clears.
4941 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4942 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4943 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004944 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004945 sleepTimeShift--;
4946 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004947 mSleepTimeUs = 0;
4948 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004949 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004950
Eric Laurent81784c32012-11-19 14:55:58 -08004951}
4952
4953void AudioFlinger::MixerThread::threadLoop_sleepTime()
4954{
4955 // If no tracks are ready, sleep once for the duration of an output
4956 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004957 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004958 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004959 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4960 // Using the Monopipe availableToWrite, we estimate the
4961 // sleep time to retry for more data (before we underrun).
4962 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4963 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4964 const size_t pipeFrames = monoPipe->maxFrames();
4965 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4966 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4967 const size_t framesDelay = std::min(
4968 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4969 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4970 pipeFrames, framesLeft, framesDelay);
4971 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4972 } else {
4973 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4974 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4975 mSleepTimeUs = kMinThreadSleepTimeUs;
4976 }
4977 // reduce sleep time in case of consecutive application underruns to avoid
4978 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4979 // duration we would end up writing less data than needed by the audio HAL if
4980 // the condition persists.
4981 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4982 sleepTimeShift++;
4983 }
Eric Laurent81784c32012-11-19 14:55:58 -08004984 }
4985 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004986 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004987 }
4988 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004989 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4990 // before effects processing or output.
4991 if (mMixerBufferValid) {
4992 memset(mMixerBuffer, 0, mMixerBufferSize);
Eric Laurent39095982021-08-24 18:29:27 +02004993 if (mType == SPATIALIZER) {
4994 memset(mSinkBuffer, 0, mSinkBufferSize);
4995 }
Andy Hung98ef9782014-03-04 14:46:50 -08004996 } else {
4997 memset(mSinkBuffer, 0, mSinkBufferSize);
4998 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004999 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005000 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
5001 "anticipated start");
5002 }
5003 // TODO add standby time extension fct of effect tail
5004}
5005
5006// prepareTracks_l() must be called with ThreadBase::mLock held
5007AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
5008 Vector< sp<Track> > *tracksToRemove)
5009{
Andy Hungc0691382018-09-12 18:01:57 -07005010 // clean up deleted track ids in AudioMixer before allocating new tracks
5011 (void)mTracks.processDeletedTrackIds([this](int trackId) {
5012 // for each trackId, destroy it in the AudioMixer
5013 if (mAudioMixer->exists(trackId)) {
5014 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005015 }
5016 });
Andy Hungc0691382018-09-12 18:01:57 -07005017 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08005018
5019 mixer_state mixerStatus = MIXER_IDLE;
5020 // find out which tracks need to be processed
5021 size_t count = mActiveTracks.size();
5022 size_t mixedTracks = 0;
5023 size_t tracksWithEffect = 0;
5024 // counts only _active_ fast tracks
5025 size_t fastTracks = 0;
5026 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
5027
5028 float masterVolume = mMasterVolume;
5029 bool masterMute = mMasterMute;
5030
5031 if (masterMute) {
5032 masterVolume = 0;
5033 }
5034 // Delegate master volume control to effect in output mix effect chain if needed
5035 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
5036 if (chain != 0) {
5037 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
5038 chain->setVolume_l(&v, &v);
5039 masterVolume = (float)((v + (1 << 23)) >> 24);
5040 chain.clear();
5041 }
5042
5043 // prepare a new state to push
5044 FastMixerStateQueue *sq = NULL;
5045 FastMixerState *state = NULL;
5046 bool didModify = false;
5047 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08005048 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07005049 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005050 sq = mFastMixer->sq();
5051 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08005052 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08005053 }
5054
Andy Hung69aed5f2014-02-25 17:24:40 -08005055 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08005056 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08005057
Andy Hungbd3b2b02018-05-21 10:53:11 -07005058 // DeferredOperations handles statistics after setting mixerStatus.
5059 class DeferredOperations {
5060 public:
Andy Hungea840382020-05-05 21:50:17 -07005061 DeferredOperations(mixer_state *mixerStatus, ThreadMetrics *threadMetrics)
5062 : mMixerStatus(mixerStatus)
5063 , mThreadMetrics(threadMetrics) {}
Andy Hungbd3b2b02018-05-21 10:53:11 -07005064
5065 // when leaving scope, tally frames properly.
5066 ~DeferredOperations() {
5067 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
5068 // because that is when the underrun occurs.
5069 // We do not distinguish between FastTracks and NormalTracks here.
Andy Hungea840382020-05-05 21:50:17 -07005070 size_t maxUnderrunFrames = 0;
Andy Hungb68f5eb2019-12-03 16:49:17 -08005071 if (*mMixerStatus == MIXER_TRACKS_READY && mUnderrunFrames.size() > 0) {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005072 for (const auto &underrun : mUnderrunFrames) {
Andy Hungc2b11cb2020-04-22 09:04:01 -07005073 underrun.first->tallyUnderrunFrames(underrun.second);
Andy Hungea840382020-05-05 21:50:17 -07005074 maxUnderrunFrames = max(underrun.second, maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005075 }
5076 }
Andy Hungea840382020-05-05 21:50:17 -07005077 // send the max underrun frames for this mixer period
5078 mThreadMetrics->logUnderrunFrames(maxUnderrunFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005079 }
5080
5081 // tallyUnderrunFrames() is called to update the track counters
5082 // with the number of underrun frames for a particular mixer period.
5083 // We defer tallying until we know the final mixer status.
5084 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
5085 mUnderrunFrames.emplace_back(track, underrunFrames);
5086 }
5087
5088 private:
5089 const mixer_state * const mMixerStatus;
Andy Hungea840382020-05-05 21:50:17 -07005090 ThreadMetrics * const mThreadMetrics;
Andy Hungbd3b2b02018-05-21 10:53:11 -07005091 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
Andy Hungea840382020-05-05 21:50:17 -07005092 } deferredOperations(&mixerStatus, &mThreadMetrics);
Andy Hungb68f5eb2019-12-03 16:49:17 -08005093 // implicit nested scope for variable capture
Andy Hungbd3b2b02018-05-21 10:53:11 -07005094
jiabin245cdd92018-12-07 17:55:15 -08005095 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005096 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07005097 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005098
5099 // this const just means the local variable doesn't change
5100 Track* const track = t.get();
5101
5102 // process fast tracks
5103 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07005104 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
5105 "%s(%d): FastTrack(%d) present without FastMixer",
5106 __func__, id(), track->id());
5107
jiabin245cdd92018-12-07 17:55:15 -08005108 if (track->getHapticPlaybackEnabled()) {
5109 noFastHapticTrack = false;
5110 }
Eric Laurent81784c32012-11-19 14:55:58 -08005111
5112 // It's theoretically possible (though unlikely) for a fast track to be created
5113 // and then removed within the same normal mix cycle. This is not a problem, as
5114 // the track never becomes active so it's fast mixer slot is never touched.
5115 // The converse, of removing an (active) track and then creating a new track
5116 // at the identical fast mixer slot within the same normal mix cycle,
5117 // is impossible because the slot isn't marked available until the end of each cycle.
5118 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07005119 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08005120 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
5121 FastTrack *fastTrack = &state->mFastTracks[j];
5122
5123 // Determine whether the track is currently in underrun condition,
5124 // and whether it had a recent underrun.
5125 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
5126 FastTrackUnderruns underruns = ftDump->mUnderruns;
5127 uint32_t recentFull = (underruns.mBitFields.mFull -
5128 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
5129 uint32_t recentPartial = (underruns.mBitFields.mPartial -
5130 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
5131 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
5132 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
5133 uint32_t recentUnderruns = recentPartial + recentEmpty;
5134 track->mObservedUnderruns = underruns;
5135 // don't count underruns that occur while stopping or pausing
5136 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07005137 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07005138 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
5139 recentUnderruns > 0) {
5140 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07005141 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08005142 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005143 // Immediately account for FastTrack underruns.
5144 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08005145
5146 // This is similar to the state machine for normal tracks,
5147 // with a few modifications for fast tracks.
5148 bool isActive = true;
5149 switch (track->mState) {
5150 case TrackBase::STOPPING_1:
5151 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08005152 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005153 track->mState = TrackBase::STOPPING_2;
5154 }
5155 break;
5156 case TrackBase::PAUSING:
5157 // ramp down is not yet implemented
5158 track->setPaused();
5159 break;
5160 case TrackBase::RESUMING:
5161 // ramp up is not yet implemented
5162 track->mState = TrackBase::ACTIVE;
5163 break;
5164 case TrackBase::ACTIVE:
5165 if (recentFull > 0 || recentPartial > 0) {
5166 // track has provided at least some frames recently: reset retry count
5167 track->mRetryCount = kMaxTrackRetries;
5168 }
5169 if (recentUnderruns == 0) {
5170 // no recent underruns: stay active
5171 break;
5172 }
5173 // there has recently been an underrun of some kind
5174 if (track->sharedBuffer() == 0) {
5175 // were any of the recent underruns "empty" (no frames available)?
5176 if (recentEmpty == 0) {
5177 // no, then ignore the partial underruns as they are allowed indefinitely
5178 break;
5179 }
5180 // there has recently been an "empty" underrun: decrement the retry counter
5181 if (--(track->mRetryCount) > 0) {
5182 break;
5183 }
5184 // indicate to client process that the track was disabled because of underrun;
5185 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005186 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005187 // remove from active list, but state remains ACTIVE [confusing but true]
5188 isActive = false;
5189 break;
5190 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07005191 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08005192 case TrackBase::STOPPING_2:
5193 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08005194 case TrackBase::STOPPED:
5195 case TrackBase::FLUSHED: // flush() while active
5196 // Check for presentation complete if track is inactive
5197 // We have consumed all the buffers of this track.
5198 // This would be incomplete if we auto-paused on underrun
5199 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005200 uint32_t latency = 0;
5201 status_t result = mOutput->stream->getLatency(&latency);
5202 ALOGE_IF(result != OK,
5203 "Error when retrieving output stream latency: %d", result);
5204 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005205 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005206 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
5207 // track stays in active list until presentation is complete
5208 break;
5209 }
5210 }
5211 if (track->isStopping_2()) {
5212 track->mState = TrackBase::STOPPED;
5213 }
5214 if (track->isStopped()) {
5215 // Can't reset directly, as fast mixer is still polling this track
5216 // track->reset();
5217 // So instead mark this track as needing to be reset after push with ack
5218 resetMask |= 1 << i;
5219 }
5220 isActive = false;
5221 break;
5222 case TrackBase::IDLE:
5223 default:
Andy Hung959b5b82021-09-24 10:46:20 -07005224 LOG_ALWAYS_FATAL("unexpected track state %d", (int)track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08005225 }
5226
5227 if (isActive) {
5228 // was it previously inactive?
5229 if (!(state->mTrackMask & (1 << j))) {
5230 ExtendedAudioBufferProvider *eabp = track;
5231 VolumeProvider *vp = track;
5232 fastTrack->mBufferProvider = eabp;
5233 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08005234 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07005235 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08005236 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08005237 fastTrack->mHapticIntensity = track->getHapticIntensity();
Lais Andradebc3f37a2021-07-02 00:13:19 +01005238 fastTrack->mHapticMaxAmplitude = track->getHapticMaxAmplitude();
Eric Laurent81784c32012-11-19 14:55:58 -08005239 fastTrack->mGeneration++;
5240 state->mTrackMask |= 1 << j;
5241 didModify = true;
5242 // no acknowledgement required for newly active tracks
5243 }
Kevin Rocard12381092018-04-11 09:19:59 -07005244 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurenteab90452019-06-24 15:17:46 -07005245 float volume;
5246 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
5247 volume = 0.f;
5248 } else {
5249 volume = masterVolume * mStreamTypes[track->streamType()].volume;
5250 }
5251
5252 handleVoipVolume_l(&volume);
5253
Eric Laurent81784c32012-11-19 14:55:58 -08005254 // cache the combined master volume and stream type volume for fast mixer; this
5255 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005256 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07005257 proxy->framesReleased()).first;
5258 volume *= vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07005259 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07005260 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5261 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
5262 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07005263
Kevin Rocard12381092018-04-11 09:19:59 -07005264 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08005265 ++fastTracks;
5266 } else {
5267 // was it previously active?
5268 if (state->mTrackMask & (1 << j)) {
5269 fastTrack->mBufferProvider = NULL;
5270 fastTrack->mGeneration++;
5271 state->mTrackMask &= ~(1 << j);
5272 didModify = true;
5273 // If any fast tracks were removed, we must wait for acknowledgement
5274 // because we're about to decrement the last sp<> on those tracks.
5275 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5276 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08005277 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
5278 // AudioTrack may start (which may not be with a start() but with a write()
5279 // after underrun) and immediately paused or released. In that case the
5280 // FastTrack state hasn't had time to update.
5281 // TODO Remove the ALOGW when this theory is confirmed.
5282 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005283 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
Andy Hung959b5b82021-09-24 10:46:20 -07005284 j, (int)track->mState, state->mTrackMask, recentUnderruns,
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08005285 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08005286 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08005287 }
5288 tracksToRemove->add(track);
5289 // Avoids a misleading display in dumpsys
5290 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
5291 }
jiabin245cdd92018-12-07 17:55:15 -08005292 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
5293 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
5294 didModify = true;
5295 }
Eric Laurent81784c32012-11-19 14:55:58 -08005296 continue;
5297 }
5298
5299 { // local variable scope to avoid goto warning
5300
5301 audio_track_cblk_t* cblk = track->cblk();
5302
5303 // The first time a track is added we wait
5304 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07005305 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005306
5307 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07005308 // use the trackId as the AudioMixer name.
5309 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005310 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005311 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005312 track->mChannelMask,
5313 track->mFormat,
5314 track->mSessionId);
5315 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07005316 ALOGW("%s(): AudioMixer cannot create track(%d)"
5317 " mask %#x, format %#x, sessionId %d",
5318 __func__, trackId,
5319 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005320 tracksToRemove->add(track);
5321 track->invalidate(); // consider it dead.
5322 continue;
5323 }
5324 }
5325
Eric Laurent81784c32012-11-19 14:55:58 -08005326 // make sure that we have enough frames to mix one full buffer.
5327 // enforce this condition only once to enable draining the buffer in case the client
5328 // app does not call stop() and relies on underrun to stop:
5329 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
5330 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005331 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07005332 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005333 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005334
5335 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005336 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005337 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
5338 // add frames already consumed but not yet released by the resampler
5339 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07005340 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005341
Eric Laurent81784c32012-11-19 14:55:58 -08005342 uint32_t minFrames = 1;
5343 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
5344 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005345 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08005346 }
Eric Laurent13e4c962013-12-20 17:36:01 -08005347
5348 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07005349 if (ATRACE_ENABLED()) {
5350 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08005351 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07005352 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08005353 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07005354 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005355 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08005356 !track->isPaused() && !track->isTerminated())
5357 {
Andy Hungc0691382018-09-12 18:01:57 -07005358 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005359
5360 mixedTracks++;
5361
Andy Hung69aed5f2014-02-25 17:24:40 -08005362 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
5363 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08005364 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08005365 if (track->mainBuffer() != mSinkBuffer &&
5366 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08005367 if (mEffectBufferEnabled) {
5368 mEffectBufferValid = true; // Later can set directly.
5369 }
Eric Laurent81784c32012-11-19 14:55:58 -08005370 chain = getEffectChain_l(track->sessionId());
5371 // Delegate volume control to effect in track effect chain if needed
5372 if (chain != 0) {
5373 tracksWithEffect++;
5374 } else {
Andy Hungc0691382018-09-12 18:01:57 -07005375 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08005376 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07005377 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08005378 }
5379 }
5380
5381
5382 int param = AudioMixer::VOLUME;
5383 if (track->mFillingUpStatus == Track::FS_FILLED) {
5384 // no ramp for the first volume setting
5385 track->mFillingUpStatus = Track::FS_ACTIVE;
5386 if (track->mState == TrackBase::RESUMING) {
5387 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08005388 // If a new track is paused immediately after start, do not ramp on resume.
5389 if (cblk->mServer != 0) {
5390 param = AudioMixer::RAMP_VOLUME;
5391 }
Eric Laurent81784c32012-11-19 14:55:58 -08005392 }
Andy Hungc0691382018-09-12 18:01:57 -07005393 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07005394 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07005395 // FIXME should not make a decision based on mServer
5396 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005397 // If the track is stopped before the first frame was mixed,
5398 // do not apply ramp
5399 param = AudioMixer::RAMP_VOLUME;
5400 }
5401
5402 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07005403 uint32_t vl, vr; // in U8.24 integer format
5404 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07005405 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07005406 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005407 // Always fetch volumeshaper volume to ensure state is updated.
5408 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5409 const float vh = track->getVolumeHandler()->getVolume(
5410 track->mAudioTrackServerProxy->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07005411
Eric Laurenteab90452019-06-24 15:17:46 -07005412 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
5413 v = 0;
5414 }
5415
5416 handleVoipVolume_l(&v);
5417
5418 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07005419 vl = vr = 0;
5420 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005421 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005422 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005423 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005424 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5425 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005426 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005427 if (vlf > GAIN_FLOAT_UNITY) {
5428 ALOGV("Track left volume out of range: %.3g", vlf);
5429 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005430 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005431 if (vrf > GAIN_FLOAT_UNITY) {
5432 ALOGV("Track right volume out of range: %.3g", vrf);
5433 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005434 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005435 // now apply the master volume and stream type volume and shaper volume
5436 vlf *= v * vh;
5437 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005438 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005439 // then derive vl and vr as U8.24 versions for the effect chain
5440 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5441 vl = (uint32_t) (scaleto8_24 * vlf);
5442 vr = (uint32_t) (scaleto8_24 * vrf);
5443 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005444 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005445 // send level comes from shared memory and so may be corrupt
5446 if (sendLevel > MAX_GAIN_INT) {
5447 ALOGV("Track send level out of range: %04X", sendLevel);
5448 sendLevel = MAX_GAIN_INT;
5449 }
Andy Hung6be49402014-05-30 10:42:03 -07005450 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5451 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005452 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005453
Kevin Rocard12381092018-04-11 09:19:59 -07005454 track->setFinalVolume((vrf + vlf) / 2.f);
5455
Eric Laurent81784c32012-11-19 14:55:58 -08005456 // Delegate volume control to effect in track effect chain if needed
5457 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5458 // Do not ramp volume if volume is controlled by effect
5459 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005460 // Update remaining floating point volume levels
5461 vlf = (float)vl / (1 << 24);
5462 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08005463 track->mHasVolumeController = true;
5464 } else {
5465 // force no volume ramp when volume controller was just disabled or removed
5466 // from effect chain to avoid volume spike
5467 if (track->mHasVolumeController) {
5468 param = AudioMixer::VOLUME;
5469 }
5470 track->mHasVolumeController = false;
5471 }
5472
Eric Laurent81784c32012-11-19 14:55:58 -08005473 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07005474 mAudioMixer->setBufferProvider(trackId, track);
5475 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005476
Andy Hungc0691382018-09-12 18:01:57 -07005477 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5478 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5479 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005480 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005481 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005482 AudioMixer::TRACK,
5483 AudioMixer::FORMAT, (void *)track->format());
5484 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005485 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005486 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005487 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Eric Laurent39095982021-08-24 18:29:27 +02005488
5489 if (mType == SPATIALIZER && !track->canBeSpatialized()) {
5490 mAudioMixer->setParameter(
5491 trackId,
5492 AudioMixer::TRACK,
5493 AudioMixer::MIXER_CHANNEL_MASK,
5494 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
5495 } else {
5496 mAudioMixer->setParameter(
5497 trackId,
5498 AudioMixer::TRACK,
5499 AudioMixer::MIXER_CHANNEL_MASK,
5500 (void *)(uintptr_t)(mMixerChannelMask | mHapticChannelMask));
5501 }
5502
Glenn Kastene3aa6592012-12-04 12:22:46 -08005503 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005504 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005505 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005506 if (reqSampleRate == 0) {
5507 reqSampleRate = mSampleRate;
5508 } else if (reqSampleRate > maxSampleRate) {
5509 reqSampleRate = maxSampleRate;
5510 }
Eric Laurent81784c32012-11-19 14:55:58 -08005511 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005512 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005513 AudioMixer::RESAMPLE,
5514 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005515 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005516
Andy Hung333ab962019-05-28 20:23:35 -07005517 AudioPlaybackRate playbackRate = proxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005518 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005519 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005520 AudioMixer::TIMESTRETCH,
5521 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005522 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005523
Andy Hung69aed5f2014-02-25 17:24:40 -08005524 /*
5525 * Select the appropriate output buffer for the track.
5526 *
Andy Hung98ef9782014-03-04 14:46:50 -08005527 * Tracks with effects go into their own effects chain buffer
5528 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005529 *
5530 * Other tracks can use mMixerBuffer for higher precision
5531 * channel accumulation. If this buffer is enabled
5532 * (mMixerBufferEnabled true), then selected tracks will accumulate
5533 * into it.
5534 *
5535 */
5536 if (mMixerBufferEnabled
5537 && (track->mainBuffer() == mSinkBuffer
5538 || track->mainBuffer() == mMixerBuffer)) {
Eric Laurent39095982021-08-24 18:29:27 +02005539 if (mType == SPATIALIZER && !track->canBeSpatialized()) {
5540 mAudioMixer->setParameter(
5541 trackId,
5542 AudioMixer::TRACK,
5543 AudioMixer::MIXER_FORMAT, (void *)mFormat);
5544 mAudioMixer->setParameter(
5545 trackId,
5546 AudioMixer::TRACK,
5547 AudioMixer::MAIN_BUFFER, (void *)mSinkBuffer);
5548 } else {
5549 mAudioMixer->setParameter(
5550 trackId,
5551 AudioMixer::TRACK,
5552 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
5553 mAudioMixer->setParameter(
5554 trackId,
5555 AudioMixer::TRACK,
5556 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5557 // TODO: override track->mainBuffer()?
5558 mMixerBufferValid = true;
5559 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005560 } else {
5561 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005562 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005563 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07005564 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005565 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005566 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005567 AudioMixer::TRACK,
5568 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5569 }
Eric Laurent81784c32012-11-19 14:55:58 -08005570 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005571 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005572 AudioMixer::TRACK,
5573 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005574 mAudioMixer->setParameter(
5575 trackId,
5576 AudioMixer::TRACK,
5577 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005578 mAudioMixer->setParameter(
5579 trackId,
5580 AudioMixer::TRACK,
5581 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Lais Andradebc3f37a2021-07-02 00:13:19 +01005582 mAudioMixer->setParameter(
5583 trackId,
5584 AudioMixer::TRACK,
5585 AudioMixer::HAPTIC_MAX_AMPLITUDE, (void *)(&(track->mHapticMaxAmplitude)));
Eric Laurent81784c32012-11-19 14:55:58 -08005586
5587 // reset retry count
5588 track->mRetryCount = kMaxTrackRetries;
5589
5590 // If one track is ready, set the mixer ready if:
5591 // - the mixer was not ready during previous round OR
5592 // - no other track is not ready
5593 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5594 mixerStatus != MIXER_TRACKS_ENABLED) {
5595 mixerStatus = MIXER_TRACKS_READY;
5596 }
Andy Hungb68f5eb2019-12-03 16:49:17 -08005597
5598 // Enable the next few lines to instrument a test for underrun log handling.
5599 // TODO: Remove when we have a better way of testing the underrun log.
5600#if 0
5601 static int i;
5602 if ((++i & 0xf) == 0) {
5603 deferredOperations.tallyUnderrunFrames(track, 10 /* underrunFrames */);
5604 }
5605#endif
Eric Laurent81784c32012-11-19 14:55:58 -08005606 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005607 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005608 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungb68f5eb2019-12-03 16:49:17 -08005609 ALOGV("track(%d) underrun, track state %s framesReady(%zu) < framesDesired(%zd)",
5610 trackId, track->getTrackStateAsString(), framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005611 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005612 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005613 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005614
Eric Laurent81784c32012-11-19 14:55:58 -08005615 // clear effect chain input buffer if an active track underruns to avoid sending
5616 // previous audio buffer again to effects
5617 chain = getEffectChain_l(track->sessionId());
5618 if (chain != 0) {
5619 chain->clearInputBuffer();
5620 }
5621
Andy Hungc0691382018-09-12 18:01:57 -07005622 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005623 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5624 track->isStopped() || track->isPaused()) {
5625 // We have consumed all the buffers of this track.
5626 // Remove it from the list of active tracks.
5627 // TODO: use actual buffer filling status instead of latency when available from
5628 // audio HAL
5629 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005630 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005631 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5632 if (track->isStopped()) {
5633 track->reset();
5634 }
5635 tracksToRemove->add(track);
5636 }
5637 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005638 // No buffers for this track. Give it a few chances to
5639 // fill a buffer, then remove it from active list.
5640 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005641 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5642 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005643 tracksToRemove->add(track);
5644 // indicate to client process that the track was disabled because of underrun;
5645 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005646 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005647 // If one track is not ready, mark the mixer also not ready if:
5648 // - the mixer was ready during previous round OR
5649 // - no other track is ready
5650 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5651 mixerStatus != MIXER_TRACKS_READY) {
5652 mixerStatus = MIXER_TRACKS_ENABLED;
5653 }
5654 }
Andy Hungc0691382018-09-12 18:01:57 -07005655 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005656 }
5657
5658 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005659
5660 }
5661
jiabin245cdd92018-12-07 17:55:15 -08005662 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5663 // When there is no fast track playing haptic and FastMixer exists,
5664 // enabling the first FastTrack, which provides mixed data from normal
5665 // tracks, to play haptic data.
5666 FastTrack *fastTrack = &state->mFastTracks[0];
5667 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5668 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5669 didModify = true;
5670 }
5671 }
5672
Eric Laurent81784c32012-11-19 14:55:58 -08005673 // Push the new FastMixer state if necessary
5674 bool pauseAudioWatchdog = false;
5675 if (didModify) {
5676 state->mFastTracksGen++;
5677 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5678 if (kUseFastMixer == FastMixer_Dynamic &&
5679 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5680 state->mCommand = FastMixerState::COLD_IDLE;
5681 state->mColdFutexAddr = &mFastMixerFutex;
5682 state->mColdGen++;
5683 mFastMixerFutex = 0;
5684 if (kUseFastMixer == FastMixer_Dynamic) {
5685 mNormalSink = mOutputSink;
5686 }
5687 // If we go into cold idle, need to wait for acknowledgement
5688 // so that fast mixer stops doing I/O.
5689 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5690 pauseAudioWatchdog = true;
5691 }
Eric Laurent81784c32012-11-19 14:55:58 -08005692 }
5693 if (sq != NULL) {
5694 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005695 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5696 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5697 // when bringing the output sink into standby.)
5698 //
5699 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5700 //
5701 // This occurs with BT suspend when we idle the FastMixer with
5702 // active tracks, which may be added or removed.
5703 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005704 }
5705#ifdef AUDIO_WATCHDOG
5706 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5707 mAudioWatchdog->pause();
5708 }
5709#endif
5710
5711 // Now perform the deferred reset on fast tracks that have stopped
5712 while (resetMask != 0) {
5713 size_t i = __builtin_ctz(resetMask);
5714 ALOG_ASSERT(i < count);
5715 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005716 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005717 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5718 track->reset();
5719 }
5720
Andy Hung80d03d22018-04-10 10:32:11 -07005721 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5722 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5723 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5724 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5725 // See also the implementation of destroyTrack_l().
5726 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005727 const int trackId = track->id();
5728 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5729 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005730 }
5731 }
5732
Eric Laurent81784c32012-11-19 14:55:58 -08005733 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005734 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005735
Eric Laurentb3f315a2021-07-13 15:09:05 +02005736 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0 ||
5737 getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE) != 0) {
Eric Laurent97d547d2014-09-02 14:45:53 -07005738 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005739 }
5740
5741 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005742 // as long as there are effects we should clear the effects buffer, to avoid
5743 // passing a non-clean buffer to the effect chain
5744 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07005745 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005746 // sink or mix buffer must be cleared if all tracks are connected to an
5747 // effect chain as in this case the mixer will not write to the sink or mix buffer
5748 // and track effects will accumulate into it
Eric Laurent39095982021-08-24 18:29:27 +02005749 // always clear sink buffer for spatializer output as the output of the spatializer
5750 // effect will be accumulated into it
5751 if ((mBytesRemaining == 0) && (((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5752 (mixedTracks == 0 && fastTracks > 0)) || (mType == SPATIALIZER))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005753 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005754 if (mMixerBufferValid) {
5755 memset(mMixerBuffer, 0, mMixerBufferSize);
5756 // TODO: In testing, mSinkBuffer below need not be cleared because
5757 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5758 // after mixing.
5759 //
5760 // To enforce this guarantee:
5761 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5762 // (mixedTracks == 0 && fastTracks > 0))
5763 // must imply MIXER_TRACKS_READY.
5764 // Later, we may clear buffers regardless, and skip much of this logic.
5765 }
Andy Hung98ef9782014-03-04 14:46:50 -08005766 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005767 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005768 }
5769
5770 // if any fast tracks, then status is ready
5771 mMixerStatusIgnoringFastTracks = mixerStatus;
5772 if (fastTracks > 0) {
5773 mixerStatus = MIXER_TRACKS_READY;
5774 }
5775 return mixerStatus;
5776}
5777
Eric Laurentad7dd962016-09-22 12:38:37 -07005778// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005779uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005780{
5781 uint32_t trackCount = 0;
5782 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005783 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005784 trackCount++;
5785 }
5786 }
5787 return trackCount;
5788}
5789
Andy Hung1bc088a2018-02-09 15:57:31 -08005790// isTrackAllowed_l() must be called with ThreadBase::mLock held
5791bool AudioFlinger::MixerThread::isTrackAllowed_l(
5792 audio_channel_mask_t channelMask, audio_format_t format,
5793 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005794{
Andy Hung1bc088a2018-02-09 15:57:31 -08005795 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5796 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005797 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005798 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005799 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005800 ALOGW("%s: invalid format: %#x", __func__, format);
5801 return false;
5802 }
Mikhail Naganov7ad7a252019-07-30 14:42:32 -07005803 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005804 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5805 return false;
5806 }
5807 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005808}
5809
Eric Laurent10351942014-05-08 18:49:52 -07005810// checkForNewParameter_l() must be called with ThreadBase::mLock held
5811bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5812 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005813{
Eric Laurent81784c32012-11-19 14:55:58 -08005814 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07005815 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005816
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005817 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005818
Eric Laurent10351942014-05-08 18:49:52 -07005819 AudioParameter param = AudioParameter(keyValuePair);
5820 int value;
5821 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5822 reconfig = true;
5823 }
5824 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005825 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005826 status = BAD_VALUE;
5827 } else {
5828 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005829 reconfig = true;
5830 }
Eric Laurent10351942014-05-08 18:49:52 -07005831 }
5832 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005833 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005834 status = BAD_VALUE;
5835 } else {
5836 // no need to save value, since it's constant
5837 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005838 }
Eric Laurent10351942014-05-08 18:49:52 -07005839 }
5840 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5841 // do not accept frame count changes if tracks are open as the track buffer
5842 // size depends on frame count and correct behavior would not be guaranteed
5843 // if frame count is changed after track creation
5844 if (!mTracks.isEmpty()) {
5845 status = INVALID_OPERATION;
5846 } else {
5847 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005848 }
Eric Laurent10351942014-05-08 18:49:52 -07005849 }
5850 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07005851 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07005852 }
Eric Laurent81784c32012-11-19 14:55:58 -08005853
Eric Laurent10351942014-05-08 18:49:52 -07005854 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005855 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005856 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005857 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07005858 if (!mStandby) {
5859 mThreadMetrics.logEndInterval();
5860 mStandby = true;
5861 }
Eric Laurent10351942014-05-08 18:49:52 -07005862 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005863 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005864 }
Eric Laurent10351942014-05-08 18:49:52 -07005865 if (status == NO_ERROR && reconfig) {
5866 readOutputParameters_l();
5867 delete mAudioMixer;
5868 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005869 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07005870 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005871 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005872 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005873 track->mChannelMask,
5874 track->mFormat,
5875 track->mSessionId);
5876 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07005877 "%s(): AudioMixer cannot create track(%d)"
5878 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08005879 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07005880 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005881 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005882 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005883 }
Eric Laurent81784c32012-11-19 14:55:58 -08005884 }
5885
Dean Wheatley68918102021-03-19 22:09:19 +11005886 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08005887}
5888
5889
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005890void AudioFlinger::MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08005891{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005892 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005893 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005894 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005895 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005896 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
5897 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
5898 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005899 if (hasFastMixer()) {
5900 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5901
5902 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5903 // while we are dumping it. It may be inconsistent, but it won't mutate!
5904 // This is a large object so we place it on the heap.
5905 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07005906 const std::unique_ptr<FastMixerDumpState> copy =
5907 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005908 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005909
5910#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005911 // Similar for state queue
5912 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5913 observerCopy.dump(fd);
5914 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5915 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005916#endif
5917
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005918#ifdef AUDIO_WATCHDOG
5919 if (mAudioWatchdog != 0) {
5920 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5921 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5922 wdCopy.dump(fd);
5923 }
5924#endif
5925
5926 } else {
5927 dprintf(fd, " No FastMixer\n");
5928 }
Eric Laurent81784c32012-11-19 14:55:58 -08005929}
5930
5931uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5932{
5933 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5934}
5935
5936uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5937{
5938 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5939}
5940
5941void AudioFlinger::MixerThread::cacheParameters_l()
5942{
5943 PlaybackThread::cacheParameters_l();
5944
5945 // FIXME: Relaxed timing because of a certain device that can't meet latency
5946 // Should be reduced to 2x after the vendor fixes the driver issue
5947 // increase threshold again due to low power audio mode. The way this warning
5948 // threshold is calculated and its usefulness should be reconsidered anyway.
5949 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5950}
5951
5952// ----------------------------------------------------------------------------
5953
5954AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07005955 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady)
5956 : PlaybackThread(audioFlinger, output, id, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005957{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005958 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005959}
5960
Eric Laurent81784c32012-11-19 14:55:58 -08005961AudioFlinger::DirectOutputThread::~DirectOutputThread()
5962{
5963}
5964
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005965void AudioFlinger::DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005966{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005967 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005968 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
5969 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
5970}
5971
5972void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
5973{
5974 Mutex::Autolock _l(mLock);
5975 if (mMasterBalance != balance) {
5976 mMasterBalance.store(balance);
5977 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
5978 broadcast_l();
5979 }
5980}
5981
Eric Laurent5850c4c2016-11-10 13:04:31 -08005982void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005983{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005984 float left, right;
5985
Andy Hung333ab962019-05-28 20:23:35 -07005986 // Ensure volumeshaper state always advances even when muted.
5987 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5988 const auto [shaperVolume, shaperActive] = track->getVolumeHandler()->getVolume(
5989 proxy->framesReleased());
5990 mVolumeShaperActive = shaperActive;
5991
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08005992 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005993 left = right = 0;
5994 } else {
5995 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005996 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005997
Glenn Kastenc56f3422014-03-21 17:53:17 -07005998 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5999 left = float_from_gain(gain_minifloat_unpack_left(vlr));
6000 if (left > GAIN_FLOAT_UNITY) {
6001 left = GAIN_FLOAT_UNITY;
6002 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006003 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07006004 right = float_from_gain(gain_minifloat_unpack_right(vlr));
6005 if (right > GAIN_FLOAT_UNITY) {
6006 right = GAIN_FLOAT_UNITY;
6007 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01006008 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006009 }
6010
6011 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07006012 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006013 if (left != mLeftVolFloat || right != mRightVolFloat) {
6014 mLeftVolFloat = left;
6015 mRightVolFloat = right;
6016
Eric Laurentbfb1b832013-01-07 09:53:42 -08006017 // Delegate volume control to effect in track effect chain if needed
6018 // only one effect chain can be present on DirectOutputThread, so if
6019 // there is one, the track is connected to it
6020 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09006021 // if effect chain exists, volume is handled by it.
6022 // Convert volumes from float to 8.24
6023 uint32_t vl = (uint32_t)(left * (1 << 24));
6024 uint32_t vr = (uint32_t)(right * (1 << 24));
6025 // Direct/Offload effect chains set output volume in setVolume_l().
6026 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
6027 } else {
6028 // otherwise we directly set the volume.
6029 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006030 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006031 }
6032 }
6033}
6034
Phil Burk43b4dcc2015-06-09 16:53:44 -07006035void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
6036{
6037 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07006038 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006039
Eric Laurent0f0631e2015-07-06 18:01:25 -07006040 if (previousTrack != 0 && latestTrack != 0) {
6041 if (mType == DIRECT) {
6042 if (previousTrack.get() != latestTrack.get()) {
6043 mFlushPending = true;
6044 }
6045 } else /* mType == OFFLOAD */ {
6046 if (previousTrack->sessionId() != latestTrack->sessionId()) {
6047 mFlushPending = true;
6048 }
6049 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08006050 } else if (previousTrack == 0) {
6051 // there could be an old track added back during track transition for direct
6052 // output, so always issues flush to flush data of the previous track if it
6053 // was already destroyed with HAL paused, then flush can resume the playback
6054 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006055 }
6056 PlaybackThread::onAddNewTrack_l();
6057}
Eric Laurentbfb1b832013-01-07 09:53:42 -08006058
Eric Laurent81784c32012-11-19 14:55:58 -08006059AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
6060 Vector< sp<Track> > *tracksToRemove
6061)
6062{
Eric Laurentd595b7c2013-04-03 17:27:56 -07006063 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08006064 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006065 bool doHwPause = false;
6066 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08006067
6068 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006069 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006070 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006071 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08006072 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07006073 continue;
6074 }
6075
Eric Laurent5850c4c2016-11-10 13:04:31 -08006076 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006077#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08006078 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006079#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006080 // Only consider last track started for volume and mixer state control.
6081 // In theory an older track could underrun and restart after the new one starts
6082 // but as we only care about the transition phase between two tracks on a
6083 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006084 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006085 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08006086
Kuowei Li23666472021-01-20 10:23:25 +08006087 if (track->isPausePending()) {
6088 track->pauseAck();
6089 // It is possible a track might have been flushed or stopped.
6090 // Other operations such as flush pending might occur on the next prepare.
6091 if (track->isPausing()) {
6092 track->setPaused();
6093 }
6094 // Always perform pause, as an immediate flush will change
6095 // the pause state to be no longer isPausing().
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006096 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006097 doHwPause = true;
6098 mHwPaused = true;
6099 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006100 } else if (track->isFlushPending()) {
6101 track->flushAck();
6102 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006103 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006104 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07006105 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006106 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07006107 if (last) {
6108 mLeftVolFloat = mRightVolFloat = -1.0;
6109 if (mHwPaused) {
6110 doHwResume = true;
6111 mHwPaused = false;
6112 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006113 }
6114 }
6115
Eric Laurent81784c32012-11-19 14:55:58 -08006116 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08006117 // for all its buffers to be filled before processing it.
6118 // Allow draining the buffer in case the client
6119 // app does not call stop() and relies on underrun to stop:
6120 // hence the test on (track->mRetryCount > 1).
Andy Hung455982f2021-04-27 17:46:12 -07006121 // If track->mRetryCount <= 1 then track is about to be disabled, paused, removed,
6122 // so we accept any nonzero amount of data delivered by the AudioTrack (which will
6123 // reset the retry counter).
Phil Burkca5e6142015-07-14 09:42:29 -07006124 // Do not use a high threshold for compressed audio.
Andy Hung455982f2021-04-27 17:46:12 -07006125
6126 // target retry count that we will use is based on the time we wait for retries.
6127 const int32_t targetRetryCount = kMaxTrackRetriesDirectMs * 1000 / mActiveSleepTimeUs;
6128 // the retry threshold is when we accept any size for PCM data. This is slightly
6129 // smaller than the retry count so we can push small bits of data without a glitch.
6130 const int32_t retryThreshold = targetRetryCount > 2 ? targetRetryCount - 1 : 1;
Eric Laurent81784c32012-11-19 14:55:58 -08006131 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08006132 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Andy Hung455982f2021-04-27 17:46:12 -07006133 && (track->mRetryCount > retryThreshold) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006134 minFrames = mNormalFrameCount;
6135 } else {
6136 minFrames = 1;
6137 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006138
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006139 const size_t framesReady = track->framesReady();
6140 const int trackId = track->id();
6141 if (ATRACE_ENABLED()) {
6142 std::string traceName("nRdy");
6143 traceName += std::to_string(trackId);
6144 ATRACE_INT(traceName.c_str(), framesReady);
6145 }
6146 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07006147 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08006148 {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006149 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08006150
6151 if (track->mFillingUpStatus == Track::FS_FILLED) {
6152 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006153 if (last) {
6154 // make sure processVolume_l() will apply new volume even if 0
6155 mLeftVolFloat = mRightVolFloat = -1.0;
6156 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08006157 if (!mHwSupportsPause) {
6158 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08006159 }
6160 }
6161
6162 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08006163 processVolume_l(track, last);
6164 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07006165 sp<Track> previousTrack = mPreviousTrack.promote();
6166 if (previousTrack != 0) {
6167 if (track != previousTrack.get()) {
6168 // Flush any data still being written from last track
6169 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07006170 // Invalidate previous track to force a seek when resuming.
6171 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006172 }
6173 }
6174 mPreviousTrack = track;
6175
Eric Laurentd595b7c2013-04-03 17:27:56 -07006176 // reset retry count
Andy Hung455982f2021-04-27 17:46:12 -07006177 track->mRetryCount = targetRetryCount;
Eric Laurent5850c4c2016-11-10 13:04:31 -08006178 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07006179 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07006180 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006181 doHwResume = true;
6182 mHwPaused = false;
6183 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006184 }
Eric Laurent81784c32012-11-19 14:55:58 -08006185 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07006186 // clear effect chain input buffer if the last active track started underruns
6187 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07006188 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08006189 mEffectChains[0]->clearInputBuffer();
6190 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006191 if (track->isStopping_1()) {
6192 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07006193 if (last && mHwPaused) {
6194 doHwResume = true;
6195 mHwPaused = false;
6196 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07006197 }
6198 if ((track->sharedBuffer() != 0) || track->isStopped() ||
6199 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08006200 // We have consumed all the buffers of this track.
6201 // Remove it from the list of active tracks.
Eric Laurentfd477972013-10-25 18:10:40 -07006202 if (mStandby || !last ||
Andy Hung59de4262021-06-14 10:53:54 -07006203 track->presentationComplete(latency_l()) ||
Jindong32dc26e2019-11-11 18:10:01 +08006204 track->isPaused() || mHwPaused) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07006205 if (track->isStopping_2()) {
6206 track->mState = TrackBase::STOPPED;
6207 }
Eric Laurent81784c32012-11-19 14:55:58 -08006208 if (track->isStopped()) {
6209 track->reset();
6210 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07006211 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08006212 }
6213 } else {
6214 // No buffers for this track. Give it a few chances to
6215 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07006216 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08006217 if (--(track->mRetryCount) <= 0) {
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006218 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
Eric Laurentd595b7c2013-04-03 17:27:56 -07006219 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08006220 // indicate to client process that the track was disabled because of underrun;
6221 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08006222 track->disable();
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006223 // only do hw pause when track is going to be removed due to BUFFER TIMEOUT.
6224 // unlike mixerthread, HAL can be paused for direct output
Phil Burkca5e6142015-07-14 09:42:29 -07006225 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
6226 "minFrames = %u, mFormat = %#x",
Mikhail Naganovddb07bc2019-08-15 20:18:47 -07006227 framesReady, minFrames, mFormat);
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006228 if (last && mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006229 doHwPause = true;
6230 mHwPaused = true;
6231 }
Haynes Mathew George5c6daae2017-01-24 20:06:05 -08006232 } else if (last) {
6233 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent81784c32012-11-19 14:55:58 -08006234 }
6235 }
6236 }
6237 }
6238
Eric Laurentd1f69b02014-12-15 14:33:13 -08006239 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07006240 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006241 for (size_t i = 0; i < mTracks.size(); i++) {
6242 if (mTracks[i]->isFlushPending()) {
6243 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006244 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006245 }
6246 }
6247 }
6248
6249 // make sure the pause/flush/resume sequence is executed in the right order.
6250 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6251 // before flush and then resume HW. This can happen in case of pause/flush/resume
6252 // if resume is received before pause is executed.
6253 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07006254 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006255 status_t result = mOutput->stream->pause();
6256 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006257 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006258 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006259 flushHw_l();
6260 }
6261 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006262 status_t result = mOutput->stream->resume();
6263 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006264 }
Eric Laurent81784c32012-11-19 14:55:58 -08006265 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08006266 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08006267
6268 return mixerStatus;
6269}
6270
6271void AudioFlinger::DirectOutputThread::threadLoop_mix()
6272{
Eric Laurent81784c32012-11-19 14:55:58 -08006273 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08006274 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006275 // output audio to hardware
6276 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07006277 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08006278 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08006279 status_t status = mActiveTrack->getNextBuffer(&buffer);
6280 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08006281 // no need to pad with 0 for compressed audio
6282 if (audio_has_proportional_frames(mFormat)) {
6283 memset(curBuf, 0, frameCount * mFrameSize);
6284 }
Eric Laurent81784c32012-11-19 14:55:58 -08006285 break;
6286 }
6287 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
6288 frameCount -= buffer.frameCount;
6289 curBuf += buffer.frameCount * mFrameSize;
6290 mActiveTrack->releaseBuffer(&buffer);
6291 }
Andy Hung2098f272014-02-27 14:00:06 -08006292 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006293 mSleepTimeUs = 0;
6294 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006295 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08006296}
6297
6298void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
6299{
Eric Laurentd1f69b02014-12-15 14:33:13 -08006300 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08006301 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006302 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006303 return;
6304 }
Andy Hung85ba3332021-04-27 17:40:26 -07006305 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6306 mSleepTimeUs = mActiveSleepTimeUs;
6307 } else {
6308 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006309 }
Andy Hung85ba3332021-04-27 17:40:26 -07006310 // Note: In S or later, we do not write zeroes for
6311 // linear or proportional PCM direct tracks in underrun.
Eric Laurent81784c32012-11-19 14:55:58 -08006312}
6313
Eric Laurentd1f69b02014-12-15 14:33:13 -08006314void AudioFlinger::DirectOutputThread::threadLoop_exit()
6315{
6316 {
6317 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08006318 for (size_t i = 0; i < mTracks.size(); i++) {
6319 if (mTracks[i]->isFlushPending()) {
6320 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07006321 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006322 }
6323 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07006324 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08006325 flushHw_l();
6326 }
6327 }
6328 PlaybackThread::threadLoop_exit();
6329}
6330
6331// must be called with thread mutex locked
6332bool AudioFlinger::DirectOutputThread::shouldStandby_l()
6333{
6334 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07006335 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006336
6337 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
6338 // after a timeout and we will enter standby then.
6339 if (mTracks.size() > 0) {
6340 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07006341 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
6342 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08006343 }
6344
Eric Laurent5cff4032015-05-26 13:49:58 -07006345 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08006346}
6347
Eric Laurent10351942014-05-08 18:49:52 -07006348// checkForNewParameter_l() must be called with ThreadBase::mLock held
6349bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
6350 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08006351{
6352 bool reconfig = false;
Eric Laurent10351942014-05-08 18:49:52 -07006353 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08006354
Eric Laurent10351942014-05-08 18:49:52 -07006355 AudioParameter param = AudioParameter(keyValuePair);
6356 int value;
6357 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07006358 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08006359 }
Eric Laurent10351942014-05-08 18:49:52 -07006360 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
6361 // do not accept frame count changes if tracks are open as the track buffer
6362 // size depends on frame count and correct behavior would not be garantied
6363 // if frame count is changed after track creation
6364 if (!mTracks.isEmpty()) {
6365 status = INVALID_OPERATION;
6366 } else {
6367 reconfig = true;
6368 }
6369 }
6370 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006371 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006372 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08006373 mOutput->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07006374 if (!mStandby) {
6375 mThreadMetrics.logEndInterval();
6376 mStandby = true;
6377 }
Eric Laurent10351942014-05-08 18:49:52 -07006378 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006379 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07006380 }
6381 if (status == NO_ERROR && reconfig) {
6382 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07006383 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07006384 }
6385 }
6386
Dean Wheatley68918102021-03-19 22:09:19 +11006387 return reconfig;
Eric Laurent81784c32012-11-19 14:55:58 -08006388}
6389
6390uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
6391{
6392 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006393 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006394 time = PlaybackThread::activeSleepTimeUs();
6395 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006396 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006397 }
6398 return time;
6399}
6400
6401uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
6402{
6403 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006404 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006405 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
6406 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006407 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006408 }
6409 return time;
6410}
6411
6412uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
6413{
6414 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08006415 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08006416 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
6417 } else {
Eric Laurent51716182016-02-29 18:00:56 -08006418 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006419 }
6420 return time;
6421}
6422
6423void AudioFlinger::DirectOutputThread::cacheParameters_l()
6424{
6425 PlaybackThread::cacheParameters_l();
6426
6427 // use shorter standby delay as on normal output to release
6428 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07006429 // no delay on outputs with HW A/V sync
6430 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006431 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08006432 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006433 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07006434 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006435 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07006436 }
Eric Laurent81784c32012-11-19 14:55:58 -08006437}
6438
Eric Laurente659ef42014-09-29 13:06:46 -07006439void AudioFlinger::DirectOutputThread::flushHw_l()
6440{
Phil Burk062e67a2015-02-11 13:40:50 -08006441 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08006442 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07006443 mFlushPending = false;
Dean Wheatley12473e92021-03-18 23:00:55 +11006444 mTimestampVerifier.discontinuity(discontinuityForStandbyOrFlush());
Sampath Shetty999f0e82020-01-15 10:19:06 +11006445 mTimestamp.clear();
Eric Laurente659ef42014-09-29 13:06:46 -07006446}
6447
Andy Hung10cbff12017-02-21 17:30:14 -08006448int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
6449 // If a VolumeShaper is active, we must wake up periodically to update volume.
6450 const int64_t NS_PER_MS = 1000000;
6451 return mVolumeShaperActive ?
6452 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
6453}
6454
Eric Laurent81784c32012-11-19 14:55:58 -08006455// ----------------------------------------------------------------------------
6456
Eric Laurentbfb1b832013-01-07 09:53:42 -08006457AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07006458 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006459 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07006460 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07006461 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006462 mDrainSequence(0),
6463 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006464{
6465}
6466
6467AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
6468{
6469}
6470
6471void AudioFlinger::AsyncCallbackThread::onFirstRef()
6472{
6473 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6474}
6475
6476bool AudioFlinger::AsyncCallbackThread::threadLoop()
6477{
6478 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006479 uint32_t writeAckSequence;
6480 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006481 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006482
6483 {
6484 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006485 while (!((mWriteAckSequence & 1) ||
6486 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006487 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006488 exitPending())) {
6489 mWaitWorkCV.wait(mLock);
6490 }
6491
Eric Laurentbfb1b832013-01-07 09:53:42 -08006492 if (exitPending()) {
6493 break;
6494 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006495 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
6496 mWriteAckSequence, mDrainSequence);
6497 writeAckSequence = mWriteAckSequence;
6498 mWriteAckSequence &= ~1;
6499 drainSequence = mDrainSequence;
6500 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006501 asyncError = mAsyncError;
6502 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006503 }
6504 {
Eric Laurent4de95592013-09-26 15:28:21 -07006505 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6506 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006507 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006508 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006509 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006510 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006511 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006512 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006513 if (asyncError) {
6514 playbackThread->onAsyncError();
6515 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006516 }
6517 }
6518 }
6519 return false;
6520}
6521
6522void AudioFlinger::AsyncCallbackThread::exit()
6523{
6524 ALOGV("AsyncCallbackThread::exit");
6525 Mutex::Autolock _l(mLock);
6526 requestExit();
6527 mWaitWorkCV.broadcast();
6528}
6529
Eric Laurent3b4529e2013-09-05 18:09:19 -07006530void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006531{
6532 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006533 // bit 0 is cleared
6534 mWriteAckSequence = sequence << 1;
6535}
6536
6537void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6538{
6539 Mutex::Autolock _l(mLock);
6540 // ignore unexpected callbacks
6541 if (mWriteAckSequence & 2) {
6542 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006543 mWaitWorkCV.signal();
6544 }
6545}
6546
Eric Laurent3b4529e2013-09-05 18:09:19 -07006547void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006548{
6549 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006550 // bit 0 is cleared
6551 mDrainSequence = sequence << 1;
6552}
6553
6554void AudioFlinger::AsyncCallbackThread::resetDraining()
6555{
6556 Mutex::Autolock _l(mLock);
6557 // ignore unexpected callbacks
6558 if (mDrainSequence & 2) {
6559 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006560 mWaitWorkCV.signal();
6561 }
6562}
6563
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006564void AudioFlinger::AsyncCallbackThread::setAsyncError()
6565{
6566 Mutex::Autolock _l(mLock);
6567 mAsyncError = true;
6568 mWaitWorkCV.signal();
6569}
6570
Eric Laurentbfb1b832013-01-07 09:53:42 -08006571
6572// ----------------------------------------------------------------------------
6573AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
jiabinc52b1ff2019-10-31 17:20:42 -07006574 AudioStreamOut* output, audio_io_handle_t id, bool systemReady)
6575 : DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07006576 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
6577 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006578{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07006579 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07006580 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07006581 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006582}
6583
Eric Laurentbfb1b832013-01-07 09:53:42 -08006584void AudioFlinger::OffloadThread::threadLoop_exit()
6585{
6586 if (mFlushPending || mHwPaused) {
6587 // If a flush is pending or track was paused, just discard buffered data
6588 flushHw_l();
6589 } else {
6590 mMixerStatus = MIXER_DRAIN_ALL;
6591 threadLoop_drain();
6592 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006593 if (mUseAsyncWrite) {
6594 ALOG_ASSERT(mCallbackThread != 0);
6595 mCallbackThread->exit();
6596 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006597 PlaybackThread::threadLoop_exit();
6598}
6599
6600AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6601 Vector< sp<Track> > *tracksToRemove
6602)
6603{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006604 size_t count = mActiveTracks.size();
6605
6606 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006607 bool doHwPause = false;
6608 bool doHwResume = false;
6609
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006610 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006611
Eric Laurentbfb1b832013-01-07 09:53:42 -08006612 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006613 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006614 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006615#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006616 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006617#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006618 // Only consider last track started for volume and mixer state control.
6619 // In theory an older track could underrun and restart after the new one starts
6620 // but as we only care about the transition phase between two tracks on a
6621 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006622 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006623 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006624
Haynes Mathew George7844f672014-01-15 12:32:55 -08006625 if (track->isInvalid()) {
6626 ALOGW("An invalidated track shouldn't be in active list");
6627 tracksToRemove->add(track);
6628 continue;
6629 }
6630
6631 if (track->mState == TrackBase::IDLE) {
6632 ALOGW("An idle track shouldn't be in active list");
6633 continue;
6634 }
6635
Kuowei Li23666472021-01-20 10:23:25 +08006636 if (track->isPausePending()) {
6637 track->pauseAck();
6638 // It is possible a track might have been flushed or stopped.
6639 // Other operations such as flush pending might occur on the next prepare.
6640 if (track->isPausing()) {
6641 track->setPaused();
6642 }
6643 // Always perform pause if last, as an immediate flush will change
6644 // the pause state to be no longer isPausing().
Eric Laurentbfb1b832013-01-07 09:53:42 -08006645 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006646 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006647 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006648 mHwPaused = true;
6649 }
6650 // If we were part way through writing the mixbuffer to
6651 // the HAL we must save this until we resume
6652 // BUG - this will be wrong if a different track is made active,
6653 // in that case we want to discard the pending data in the
6654 // mixbuffer and tell the client to present it again when the
6655 // track is resumed
6656 mPausedWriteLength = mCurrentWriteLength;
6657 mPausedBytesRemaining = mBytesRemaining;
6658 mBytesRemaining = 0; // stop writing
6659 }
6660 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006661 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006662 if (track->isStopping_1()) {
6663 track->mRetryCount = kMaxTrackStopRetriesOffload;
6664 } else {
6665 track->mRetryCount = kMaxTrackRetriesOffload;
6666 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006667 track->flushAck();
6668 if (last) {
6669 mFlushPending = true;
6670 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006671 } else if (track->isResumePending()){
6672 track->resumeAck();
6673 if (last) {
6674 if (mPausedBytesRemaining) {
6675 // Need to continue write that was interrupted
6676 mCurrentWriteLength = mPausedWriteLength;
6677 mBytesRemaining = mPausedBytesRemaining;
6678 mPausedBytesRemaining = 0;
6679 }
6680 if (mHwPaused) {
6681 doHwResume = true;
6682 mHwPaused = false;
6683 // threadLoop_mix() will handle the case that we need to
6684 // resume an interrupted write
6685 }
6686 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006687 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006688
Eric Laurent3df841a2016-07-15 15:15:40 -07006689 mLeftVolFloat = mRightVolFloat = -1.0;
6690
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006691 // Do not handle new data in this iteration even if track->framesReady()
6692 mixerStatus = MIXER_TRACKS_ENABLED;
6693 }
6694 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006695 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006696 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006697 if (track->mFillingUpStatus == Track::FS_FILLED) {
6698 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006699 if (last) {
6700 // make sure processVolume_l() will apply new volume even if 0
6701 mLeftVolFloat = mRightVolFloat = -1.0;
6702 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006703 }
6704
6705 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006706 sp<Track> previousTrack = mPreviousTrack.promote();
6707 if (previousTrack != 0) {
6708 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006709 // Flush any data still being written from last track
6710 mBytesRemaining = 0;
6711 if (mPausedBytesRemaining) {
6712 // Last track was paused so we also need to flush saved
6713 // mixbuffer state and invalidate track so that it will
6714 // re-submit that unwritten data when it is next resumed
6715 mPausedBytesRemaining = 0;
6716 // Invalidate is a bit drastic - would be more efficient
6717 // to have a flag to tell client that some of the
6718 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006719 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006720 }
6721 // flush data already sent to the DSP if changing audio session as audio
6722 // comes from a different source. Also invalidate previous track to force a
6723 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006724 if (previousTrack->sessionId() != track->sessionId()) {
6725 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006726 }
6727 }
6728 }
6729 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006730 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006731 if (track->isStopping_1()) {
6732 track->mRetryCount = kMaxTrackStopRetriesOffload;
6733 } else {
6734 track->mRetryCount = kMaxTrackRetriesOffload;
6735 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006736 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006737 mixerStatus = MIXER_TRACKS_READY;
6738 }
6739 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006740 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006741 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006742 if (--(track->mRetryCount) <= 0) {
6743 // Hardware buffer can hold a large amount of audio so we must
6744 // wait for all current track's data to drain before we say
6745 // that the track is stopped.
6746 if (mBytesRemaining == 0) {
6747 // Only start draining when all data in mixbuffer
6748 // has been written
6749 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6750 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6751 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6752 if (last && !mStandby) {
6753 // do not modify drain sequence if we are already draining. This happens
6754 // when resuming from pause after drain.
6755 if ((mDrainSequence & 1) == 0) {
6756 mSleepTimeUs = 0;
6757 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6758 mixerStatus = MIXER_DRAIN_TRACK;
6759 mDrainSequence += 2;
6760 }
6761 if (mHwPaused) {
6762 // It is possible to move from PAUSED to STOPPING_1 without
6763 // a resume so we must ensure hardware is running
6764 doHwResume = true;
6765 mHwPaused = false;
6766 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006767 }
6768 }
Eric Laurente93cc032016-05-05 10:15:10 -07006769 } else if (last) {
6770 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6771 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006772 }
6773 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006774 // Drain has completed or we are in standby, signal presentation complete
6775 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006776 track->mState = TrackBase::STOPPED;
Andy Hung59de4262021-06-14 10:53:54 -07006777 track->presentationComplete(latency_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08006778 track->reset();
6779 tracksToRemove->add(track);
Dean Wheatley12473e92021-03-18 23:00:55 +11006780 // OFFLOADED stop resets frame counts.
Andy Hungf3234512018-07-03 14:51:47 -07006781 if (!mUseAsyncWrite) {
6782 // If we don't get explicit drain notification we must
6783 // register discontinuity regardless of whether this is
6784 // the previous (!last) or the upcoming (last) track
6785 // to avoid skipping the discontinuity.
Dean Wheatley12473e92021-03-18 23:00:55 +11006786 mTimestampVerifier.discontinuity(
6787 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Andy Hungf3234512018-07-03 14:51:47 -07006788 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006789 }
6790 } else {
6791 // No buffers for this track. Give it a few chances to
6792 // fill a buffer, then remove it from active list.
6793 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07006794 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006795 uint64_t position = 0;
6796 struct timespec unused;
6797 // The running check restarts the retry counter at least once.
6798 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6799 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6800 running = true;
6801 mOffloadUnderrunPosition = position;
6802 }
6803 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07006804 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6805 (long long)position, (long long)mOffloadUnderrunPosition);
6806 }
6807 if (running) { // still running, give us more time.
6808 track->mRetryCount = kMaxTrackRetriesOffload;
6809 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006810 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6811 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07006812 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006813 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006814 // it will then automatically call start() when data is available
6815 track->disable();
6816 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006817 } else if (last){
6818 mixerStatus = MIXER_TRACKS_ENABLED;
6819 }
6820 }
6821 }
6822 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08006823 if (track->isReady()) { // check ready to prevent premature start.
6824 processVolume_l(track, last);
6825 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006826 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006827
Eric Laurentea0fade2013-10-04 16:23:48 -07006828 // make sure the pause/flush/resume sequence is executed in the right order.
6829 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6830 // before flush and then resume HW. This can happen in case of pause/flush/resume
6831 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006832 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006833 status_t result = mOutput->stream->pause();
6834 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006835 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006836 if (mFlushPending) {
6837 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006838 }
Eric Laurentfd477972013-10-25 18:10:40 -07006839 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006840 status_t result = mOutput->stream->resume();
6841 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006842 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006843
Eric Laurentbfb1b832013-01-07 09:53:42 -08006844 // remove all the tracks that need to be...
6845 removeTracks_l(*tracksToRemove);
6846
6847 return mixerStatus;
6848}
6849
Eric Laurentbfb1b832013-01-07 09:53:42 -08006850// must be called with thread mutex locked
6851bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6852{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006853 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6854 mWriteAckSequence, mDrainSequence);
6855 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006856 return true;
6857 }
6858 return false;
6859}
6860
Eric Laurentbfb1b832013-01-07 09:53:42 -08006861bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6862{
6863 Mutex::Autolock _l(mLock);
6864 return waitingAsyncCallback_l();
6865}
6866
6867void AudioFlinger::OffloadThread::flushHw_l()
6868{
Eric Laurente659ef42014-09-29 13:06:46 -07006869 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006870 // Flush anything still waiting in the mixbuffer
6871 mCurrentWriteLength = 0;
6872 mBytesRemaining = 0;
6873 mPausedWriteLength = 0;
6874 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006875 // reset bytes written count to reflect that DSP buffers are empty after flush.
6876 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006877 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006878
Eric Laurentbfb1b832013-01-07 09:53:42 -08006879 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006880 // discard any pending drain or write ack by incrementing sequence
6881 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6882 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006883 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006884 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6885 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006886 }
6887}
6888
Haynes Mathew George05317d22016-05-03 16:34:26 -07006889void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6890{
6891 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006892 if (PlaybackThread::invalidateTracks_l(streamType)) {
6893 mFlushPending = true;
6894 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006895}
6896
Eric Laurentbfb1b832013-01-07 09:53:42 -08006897// ----------------------------------------------------------------------------
6898
Eric Laurent81784c32012-11-19 14:55:58 -08006899AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006900 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
jiabinc52b1ff2019-10-31 17:20:42 -07006901 : MixerThread(audioFlinger, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006902 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006903 mWaitTimeMs(UINT_MAX)
6904{
6905 addOutputTrack(mainThread);
6906}
6907
6908AudioFlinger::DuplicatingThread::~DuplicatingThread()
6909{
6910 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6911 mOutputTracks[i]->destroy();
6912 }
6913}
6914
6915void AudioFlinger::DuplicatingThread::threadLoop_mix()
6916{
6917 // mix buffers...
6918 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006919 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006920 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006921 if (mMixerBufferValid) {
6922 memset(mMixerBuffer, 0, mMixerBufferSize);
6923 } else {
6924 memset(mSinkBuffer, 0, mSinkBufferSize);
6925 }
Eric Laurent81784c32012-11-19 14:55:58 -08006926 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006927 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006928 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006929 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006930 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006931}
6932
6933void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6934{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006935 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006936 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006937 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006938 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006939 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006940 }
6941 } else if (mBytesWritten != 0) {
6942 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6943 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006944 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006945 } else {
6946 // flush remaining overflow buffers in output tracks
6947 writeFrames = 0;
6948 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006949 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006950 }
6951}
6952
Eric Laurentbfb1b832013-01-07 09:53:42 -08006953ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006954{
6955 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006956 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6957
6958 // Consider the first OutputTrack for timestamp and frame counting.
6959
6960 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6961 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6962 // we always claim success.
6963 if (i == 0) {
6964 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6965 ALOGD_IF(correction != 0 && writeFrames != 0,
6966 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6967 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6968 mFramesWritten -= correction;
6969 }
6970
6971 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006972 }
Andy Hungcf10d742020-04-28 15:38:24 -07006973 if (mStandby) {
6974 mThreadMetrics.logBeginInterval();
6975 mStandby = false;
6976 }
Andy Hung25c2dac2014-02-27 14:56:00 -08006977 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006978}
6979
6980void AudioFlinger::DuplicatingThread::threadLoop_standby()
6981{
6982 // DuplicatingThread implements standby by stopping all tracks
6983 for (size_t i = 0; i < outputTracks.size(); i++) {
6984 outputTracks[i]->stop();
6985 }
6986}
6987
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006988void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Andy Hung1bc088a2018-02-09 15:57:31 -08006989{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006990 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08006991
6992 std::stringstream ss;
6993 const size_t numTracks = mOutputTracks.size();
6994 ss << " " << numTracks << " OutputTracks";
6995 if (numTracks > 0) {
6996 ss << ":";
6997 for (const auto &track : mOutputTracks) {
6998 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07006999 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08007000 if (thread.get() != nullptr) {
7001 ss << thread.get() << ", " << thread->id();
7002 } else {
7003 ss << "null";
7004 }
7005 ss << ")";
7006 }
7007 }
7008 ss << "\n";
7009 std::string result = ss.str();
7010 write(fd, result.c_str(), result.size());
7011}
7012
Eric Laurent81784c32012-11-19 14:55:58 -08007013void AudioFlinger::DuplicatingThread::saveOutputTracks()
7014{
7015 outputTracks = mOutputTracks;
7016}
7017
7018void AudioFlinger::DuplicatingThread::clearOutputTracks()
7019{
7020 outputTracks.clear();
7021}
7022
7023void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
7024{
7025 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08007026 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
7027 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
7028 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
7029 const size_t frameCount =
7030 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
7031 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
7032 // from different OutputTracks and their associated MixerThreads (e.g. one may
7033 // nearly empty and the other may be dropping data).
7034
Svet Ganov33761132021-05-13 22:51:08 +00007035 // TODO b/182392769: use attribution source util, move to server edge
7036 AttributionSourceState attributionSource = AttributionSourceState();
7037 attributionSource.uid = VALUE_OR_FATAL(legacy2aidl_uid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007038 IPCThreadState::self()->getCallingUid()));
Svet Ganov33761132021-05-13 22:51:08 +00007039 attributionSource.pid = VALUE_OR_FATAL(legacy2aidl_pid_t_int32_t(
Philip P. Moltmannbda45752020-07-17 16:41:18 -07007040 IPCThreadState::self()->getCallingPid()));
Svet Ganov33761132021-05-13 22:51:08 +00007041 attributionSource.token = sp<BBinder>::make();
Andy Hungc25b84a2015-01-14 19:04:10 -08007042 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08007043 this,
7044 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08007045 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08007046 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08007047 frameCount,
Svet Ganov33761132021-05-13 22:51:08 +00007048 attributionSource);
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007049 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
7050 if (status != NO_ERROR) {
7051 ALOGE("addOutputTrack() initCheck failed %d", status);
7052 return;
Eric Laurent81784c32012-11-19 14:55:58 -08007053 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07007054 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
7055 mOutputTracks.add(outputTrack);
7056 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
7057 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08007058}
7059
7060void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
7061{
7062 Mutex::Autolock _l(mLock);
7063 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7064 if (mOutputTracks[i]->thread() == thread) {
7065 mOutputTracks[i]->destroy();
7066 mOutputTracks.removeAt(i);
7067 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07007068 if (thread->getOutput() == mOutput) {
7069 mOutput = NULL;
7070 }
Eric Laurent81784c32012-11-19 14:55:58 -08007071 return;
7072 }
7073 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07007074 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08007075}
7076
7077// caller must hold mLock
7078void AudioFlinger::DuplicatingThread::updateWaitTime_l()
7079{
7080 mWaitTimeMs = UINT_MAX;
7081 for (size_t i = 0; i < mOutputTracks.size(); i++) {
7082 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
7083 if (strong != 0) {
7084 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
7085 if (waitTimeMs < mWaitTimeMs) {
7086 mWaitTimeMs = waitTimeMs;
7087 }
7088 }
7089 }
7090}
7091
7092
7093bool AudioFlinger::DuplicatingThread::outputsReady(
7094 const SortedVector< sp<OutputTrack> > &outputTracks)
7095{
7096 for (size_t i = 0; i < outputTracks.size(); i++) {
7097 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
7098 if (thread == 0) {
7099 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
7100 outputTracks[i].get());
7101 return false;
7102 }
7103 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
7104 // see note at standby() declaration
7105 if (playbackThread->standby() && !playbackThread->isSuspended()) {
7106 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
7107 thread.get());
7108 return false;
7109 }
7110 }
7111 return true;
7112}
7113
Kevin Rocard12381092018-04-11 09:19:59 -07007114void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
7115 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07007116{
Kevin Rocard12381092018-04-11 09:19:59 -07007117 for (auto& outputTrack : outputTracks) { // not mOutputTracks
7118 outputTrack->setMetadatas(metadata.tracks);
7119 }
Kevin Rocard069c2712018-03-29 19:09:14 -07007120}
7121
Eric Laurent81784c32012-11-19 14:55:58 -08007122uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
7123{
7124 return (mWaitTimeMs * 1000) / 2;
7125}
7126
7127void AudioFlinger::DuplicatingThread::cacheParameters_l()
7128{
7129 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
7130 updateWaitTime_l();
7131
7132 MixerThread::cacheParameters_l();
7133}
7134
Eric Laurentb3f315a2021-07-13 15:09:05 +02007135// ----------------------------------------------------------------------------
7136
Eric Laurentfa0f6742021-08-17 18:39:44 +02007137AudioFlinger::SpatializerThread::SpatializerThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurentb3f315a2021-07-13 15:09:05 +02007138 AudioStreamOut* output,
7139 audio_io_handle_t id,
7140 bool systemReady,
7141 audio_config_base_t *mixerConfig)
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007142 : MixerThread(audioFlinger, output, id, systemReady, SPATIALIZER, mixerConfig)
Eric Laurentb3f315a2021-07-13 15:09:05 +02007143{
7144}
7145
Eric Laurentfa0f6742021-08-17 18:39:44 +02007146void AudioFlinger::SpatializerThread::checkOutputStageEffects()
Eric Laurentb3f315a2021-07-13 15:09:05 +02007147{
7148 bool hasVirtualizer = false;
7149 bool hasDownMixer = false;
7150 sp<EffectHandle> finalDownMixer;
7151 {
7152 Mutex::Autolock _l(mLock);
7153 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_STAGE);
7154 if (chain != 0) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02007155 hasVirtualizer = chain->getEffectFromType_l(FX_IID_SPATIALIZER) != nullptr;
Eric Laurentb3f315a2021-07-13 15:09:05 +02007156 hasDownMixer = chain->getEffectFromType_l(EFFECT_UIID_DOWNMIX) != nullptr;
7157 }
7158
7159 finalDownMixer = mFinalDownMixer;
7160 mFinalDownMixer.clear();
7161 }
7162
7163 if (hasVirtualizer) {
7164 if (finalDownMixer != nullptr) {
7165 int32_t ret;
7166 finalDownMixer->disable(&ret);
7167 }
7168 finalDownMixer.clear();
7169 } else if (!hasDownMixer) {
7170 std::vector<effect_descriptor_t> descriptors;
7171 status_t status = mAudioFlinger->mEffectsFactoryHal->getDescriptors(
7172 EFFECT_UIID_DOWNMIX, &descriptors);
7173 if (status != NO_ERROR) {
7174 return;
7175 }
7176 ALOG_ASSERT(!descriptors.empty(),
7177 "%s getDescriptors() returned no error but empty list", __func__);
7178
7179 finalDownMixer = createEffect_l(nullptr /*client*/, nullptr /*effectClient*/,
7180 0 /*priority*/, AUDIO_SESSION_OUTPUT_STAGE, &descriptors[0], nullptr /*enabled*/,
Eric Laurentde8caf42021-08-11 17:19:25 +02007181 &status, false /*pinned*/, false /*probe*/, false /*notifyFramesProcessed*/);
Eric Laurentb3f315a2021-07-13 15:09:05 +02007182
7183 if (finalDownMixer == nullptr || (status != NO_ERROR && status != ALREADY_EXISTS)) {
7184 ALOGW("%s error creating downmixer %d", __func__, status);
7185 finalDownMixer.clear();
7186 } else {
7187 int32_t ret;
7188 finalDownMixer->enable(&ret);
7189 }
7190 }
7191
7192 {
7193 Mutex::Autolock _l(mLock);
7194 mFinalDownMixer = finalDownMixer;
7195 }
7196}
7197
Eric Laurent6acd1d42017-01-04 14:23:29 -08007198
Eric Laurent81784c32012-11-19 14:55:58 -08007199// ----------------------------------------------------------------------------
7200// Record
7201// ----------------------------------------------------------------------------
7202
7203AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
7204 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08007205 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07007206 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08007207 ) :
Andy Hungcf10d742020-04-28 15:38:24 -07007208 ThreadBase(audioFlinger, id, RECORD, systemReady, false /* isOut */),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007209 mInput(input),
Mikhail Naganov2534b382019-09-25 13:05:02 -07007210 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007211 mActiveTracks(&this->mLocalLog),
7212 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07007213 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007214 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07007215 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
7216 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007217 // mFastCapture below
7218 , mFastCaptureFutex(0)
7219 // mInputSource
7220 // mPipeSink
7221 // mPipeSource
7222 , mPipeFramesP2(0)
7223 // mPipeMemory
7224 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007225 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07007226 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08007227{
Glenn Kastend7dca052015-03-05 16:05:54 -08007228 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
7229 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08007230
George Burgess IVa8f90c12020-05-14 11:27:19 -07007231 if (mInput->audioHwDev != nullptr) {
Andy Hungc8fddf32018-08-08 18:32:37 -07007232 mIsMsdDevice = strcmp(
7233 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
7234 }
7235
Glenn Kastendeca2ae2014-02-07 10:25:56 -08007236 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007237
Andy Hungc8fddf32018-08-08 18:32:37 -07007238 // TODO: We may also match on address as well as device type for
7239 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabinc52b1ff2019-10-31 17:20:42 -07007240 // TODO: This property should be ensure that only contains one single device type.
7241 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
7242 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07007243 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
7244 : AUDIO_DEVICE_NONE));
7245
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007246 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07007247 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007248 size_t numCounterOffers = 0;
7249 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07007250#if !LOG_NDEBUG
7251 ssize_t index =
7252#else
7253 (void)
7254#endif
7255 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007256 ALOG_ASSERT(index == 0);
7257
7258 // initialize fast capture depending on configuration
7259 bool initFastCapture;
7260 switch (kUseFastCapture) {
7261 case FastCapture_Never:
7262 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007263 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007264 break;
7265 case FastCapture_Always:
7266 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007267 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007268 break;
7269 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07007270 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007271 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
7272 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
7273 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007274 break;
7275 // case FastCapture_Dynamic:
7276 }
7277
7278 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07007279 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007280 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07007281 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
7282 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007283 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007284 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007285 const sp<MemoryDealer> roHeap(readOnlyHeap());
7286 sp<IMemory> pipeMemory;
7287 if ((roHeap == 0) ||
7288 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Ytai Ben-Tsvi7dd39722019-09-05 15:14:30 -07007289 (pipeBuffer = pipeMemory->unsecurePointer()) == nullptr) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007290 ALOGE("not enough memory for pipe buffer size=%zu; "
7291 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
7292 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
7293 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007294 goto failed;
7295 }
7296 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
7297 memset(pipeBuffer, 0, pipeSize);
7298 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
7299 const NBAIO_Format offers[1] = {format};
7300 size_t numCounterOffers = 0;
7301 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
7302 ALOG_ASSERT(index == 0);
7303 mPipeSink = pipe;
7304 PipeReader *pipeReader = new PipeReader(*pipe);
7305 numCounterOffers = 0;
7306 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
7307 ALOG_ASSERT(index == 0);
7308 mPipeSource = pipeReader;
7309 mPipeFramesP2 = pipeFramesP2;
7310 mPipeMemory = pipeMemory;
7311
7312 // create fast capture
7313 mFastCapture = new FastCapture();
7314 FastCaptureStateQueue *sq = mFastCapture->sq();
7315#ifdef STATE_QUEUE_DUMP
7316 // FIXME
7317#endif
7318 FastCaptureState *state = sq->begin();
7319 state->mCblk = NULL;
7320 state->mInputSource = mInputSource.get();
7321 state->mInputSourceGen++;
7322 state->mPipeSink = pipe;
7323 state->mPipeSinkGen++;
7324 state->mFrameCount = mFrameCount;
7325 state->mCommand = FastCaptureState::COLD_IDLE;
7326 // already done in constructor initialization list
7327 //mFastCaptureFutex = 0;
7328 state->mColdFutexAddr = &mFastCaptureFutex;
7329 state->mColdGen++;
7330 state->mDumpState = &mFastCaptureDumpState;
7331#ifdef TEE_SINK
7332 // FIXME
7333#endif
7334 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
7335 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
7336 sq->end();
7337 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7338
7339 // start the fast capture
7340 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
7341 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07007342 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08007343 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007344#ifdef AUDIO_WATCHDOG
7345 // FIXME
7346#endif
7347
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007348 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007349 }
Andy Hung8946a282018-04-19 20:04:56 -07007350#ifdef TEE_SINK
7351 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
7352 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
7353#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007354failed: ;
7355
7356 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08007357}
7358
Eric Laurent81784c32012-11-19 14:55:58 -08007359AudioFlinger::RecordThread::~RecordThread()
7360{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007361 if (mFastCapture != 0) {
7362 FastCaptureStateQueue *sq = mFastCapture->sq();
7363 FastCaptureState *state = sq->begin();
7364 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7365 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7366 if (old == -1) {
7367 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7368 }
7369 }
7370 state->mCommand = FastCaptureState::EXIT;
7371 sq->end();
7372 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
7373 mFastCapture->join();
7374 mFastCapture.clear();
7375 }
7376 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07007377 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07007378 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08007379}
7380
7381void AudioFlinger::RecordThread::onFirstRef()
7382{
Glenn Kastend7dca052015-03-05 16:05:54 -08007383 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08007384}
7385
Eric Laurent555530a2017-02-07 18:17:24 -08007386void AudioFlinger::RecordThread::preExit()
7387{
7388 ALOGV(" preExit()");
7389 Mutex::Autolock _l(mLock);
7390 for (size_t i = 0; i < mTracks.size(); i++) {
7391 sp<RecordTrack> track = mTracks[i];
7392 track->invalidate();
7393 }
7394 mActiveTracks.clear();
7395 mStartStopCond.broadcast();
7396}
7397
Eric Laurent81784c32012-11-19 14:55:58 -08007398bool AudioFlinger::RecordThread::threadLoop()
7399{
Eric Laurent81784c32012-11-19 14:55:58 -08007400 nsecs_t lastWarning = 0;
7401
7402 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08007403
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007404reacquire_wakelock:
7405 sp<RecordTrack> activeTrack;
7406 {
7407 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07007408 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007409 }
7410
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007411 // used to request a deferred sleep, to be executed later while mutex is unlocked
7412 uint32_t sleepUs = 0;
7413
Andy Hung446f4df2019-02-21 12:26:41 -08007414 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
7415
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007416 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08007417 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007418 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07007419
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007420 // activeTracks accumulates a copy of a subset of mActiveTracks
7421 Vector< sp<RecordTrack> > activeTracks;
7422
Glenn Kasten735f45f2014-08-18 15:51:59 -07007423 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007424 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07007425
Glenn Kasten735f45f2014-08-18 15:51:59 -07007426 // reference to a fast track which is about to be removed
7427 sp<RecordTrack> fastTrackToRemove;
7428
Eric Laurent33403f02020-05-29 18:35:06 -07007429 bool silenceFastCapture = false;
7430
Eric Laurent81784c32012-11-19 14:55:58 -08007431 { // scope for mLock
7432 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08007433
Eric Laurent021cf962014-05-13 10:18:14 -07007434 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007435
Eric Laurent000a4192014-01-29 15:17:32 -08007436 // check exitPending here because checkForNewParameters_l() and
7437 // checkForNewParameters_l() can temporarily release mLock
7438 if (exitPending()) {
7439 break;
7440 }
7441
Eric Laurent5c25d562016-07-13 17:17:45 -07007442 // sleep with mutex unlocked
7443 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07007444 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07007445 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
7446 ATRACE_END();
7447 sleepUs = 0;
7448 continue;
7449 }
7450
Glenn Kasten2b806402013-11-20 16:37:38 -08007451 // if no active track(s), then standby and release wakelock
7452 size_t size = mActiveTracks.size();
7453 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07007454 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07007455 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08007456 releaseWakeLock_l();
7457 ALOGV("RecordThread: loop stopping");
7458 // go to sleep
7459 mWaitWorkCV.wait(mLock);
7460 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007461 goto reacquire_wakelock;
7462 }
7463
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007464 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07007465 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007466 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07007467
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007468 activeTrack = mActiveTracks[i];
7469 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07007470 if (activeTrack->isFastTrack()) {
7471 ALOG_ASSERT(fastTrackToRemove == 0);
7472 fastTrackToRemove = activeTrack;
7473 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007474 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08007475 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007476 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07007477 continue;
7478 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007479
7480 TrackBase::track_state activeTrackState = activeTrack->mState;
7481 switch (activeTrackState) {
7482
7483 case TrackBase::PAUSING:
7484 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07007485 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007486 doBroadcast = true;
7487 size--;
7488 continue;
7489
7490 case TrackBase::STARTING_1:
7491 sleepUs = 10000;
7492 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07007493 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007494 continue;
7495
7496 case TrackBase::STARTING_2:
7497 doBroadcast = true;
Andy Hungcf10d742020-04-28 15:38:24 -07007498 if (mStandby) {
7499 mThreadMetrics.logBeginInterval();
7500 mStandby = false;
7501 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007502 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07007503 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007504 break;
7505
7506 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07007507 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007508 break;
7509
Andy Hungce685402018-10-05 17:23:27 -07007510 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
7511 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
7512 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007513 default:
Andy Hungce685402018-10-05 17:23:27 -07007514 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
7515 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07007516 }
Glenn Kasten9e982352013-08-14 14:39:50 -07007517
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007518 if (activeTrack->isFastTrack()) {
7519 ALOG_ASSERT(!mFastTrackAvail);
7520 ALOG_ASSERT(fastTrack == 0);
Eric Laurent33403f02020-05-29 18:35:06 -07007521 // if the active fast track is silenced either:
7522 // 1) silence the whole capture from fast capture buffer if this is
7523 // the only active track
7524 // 2) invalidate this track: this will cause the client to reconnect and possibly
7525 // be invalidated again until unsilenced
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007526 bool invalidate = false;
Eric Laurent33403f02020-05-29 18:35:06 -07007527 if (activeTrack->isSilenced()) {
7528 if (size > 1) {
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007529 invalidate = true;
Eric Laurent33403f02020-05-29 18:35:06 -07007530 } else {
7531 silenceFastCapture = true;
7532 }
7533 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02007534 // Invalidate fast tracks if access to audio history is required as this is not
7535 // possible with fast tracks. Once the fast track has been invalidated, no new
7536 // fast track will be created until mMaxSharedAudioHistoryMs is cleared.
7537 if (mMaxSharedAudioHistoryMs != 0) {
7538 invalidate = true;
7539 }
7540 if (invalidate) {
7541 activeTrack->invalidate();
7542 ALOG_ASSERT(fastTrackToRemove == 0);
7543 fastTrackToRemove = activeTrack;
7544 removeTrack_l(activeTrack);
7545 mActiveTracks.remove(activeTrack);
7546 size--;
7547 continue;
7548 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007549 fastTrack = activeTrack;
7550 }
Eric Laurent33403f02020-05-29 18:35:06 -07007551
7552 activeTracks.add(activeTrack);
7553 i++;
7554
Glenn Kasten9e982352013-08-14 14:39:50 -07007555 }
Eric Laurent5c25d562016-07-13 17:17:45 -07007556
Andy Hungdae27702016-10-31 14:01:16 -07007557 mActiveTracks.updatePowerState(this);
7558
Kevin Rocard069c2712018-03-29 19:09:14 -07007559 updateMetadata_l();
7560
Eric Laurent5c25d562016-07-13 17:17:45 -07007561 if (allStopped) {
7562 standbyIfNotAlreadyInStandby();
7563 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007564 if (doBroadcast) {
7565 mStartStopCond.broadcast();
7566 }
7567
7568 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07007569 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007570 if (sleepUs == 0) {
7571 sleepUs = kRecordThreadSleepUs;
7572 }
7573 continue;
7574 }
7575 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07007576
Eric Laurent81784c32012-11-19 14:55:58 -08007577 lockEffectChains_l(effectChains);
7578 }
7579
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007580 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07007581
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007582 size_t size = effectChains.size();
7583 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007584 // thread mutex is not locked, but effect chain is locked
7585 effectChains[i]->process_l();
7586 }
7587
Glenn Kasten735f45f2014-08-18 15:51:59 -07007588 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007589 if (mFastCapture != 0) {
7590 FastCaptureStateQueue *sq = mFastCapture->sq();
7591 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07007592 bool didModify = false;
7593 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007594 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
7595 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
7596 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7597 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7598 if (old == -1) {
7599 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7600 }
7601 }
7602 state->mCommand = FastCaptureState::READ_WRITE;
7603#if 0 // FIXME
7604 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08007605 FastThreadDumpState::kSamplingNforLowRamDevice :
7606 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007607#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07007608 didModify = true;
7609 }
7610 audio_track_cblk_t *cblkOld = state->mCblk;
7611 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
7612 if (cblkNew != cblkOld) {
7613 state->mCblk = cblkNew;
7614 // block until acked if removing a fast track
7615 if (cblkOld != NULL) {
7616 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7617 }
7618 didModify = true;
7619 }
jiabin01c8f562018-07-19 17:47:28 -07007620 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7621 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7622 if (state->mFastPatchRecordBufferProvider != abp) {
7623 state->mFastPatchRecordBufferProvider = abp;
7624 state->mFastPatchRecordFormat = fastTrack == 0 ?
7625 AUDIO_FORMAT_INVALID : fastTrack->format();
7626 didModify = true;
7627 }
Eric Laurent33403f02020-05-29 18:35:06 -07007628 if (state->mSilenceCapture != silenceFastCapture) {
7629 state->mSilenceCapture = silenceFastCapture;
7630 didModify = true;
7631 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07007632 sq->end(didModify);
7633 if (didModify) {
7634 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007635#if 0
7636 if (kUseFastCapture == FastCapture_Dynamic) {
7637 mNormalSource = mPipeSource;
7638 }
7639#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007640 }
7641 }
7642
Glenn Kasten735f45f2014-08-18 15:51:59 -07007643 // now run the fast track destructor with thread mutex unlocked
7644 fastTrackToRemove.clear();
7645
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007646 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7647 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7648 // slow, then this RecordThread will overrun by not calling HAL read often enough.
7649 // If destination is non-contiguous, first read past the nominal end of buffer, then
7650 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007651
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007652 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007653 ssize_t framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007654 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007655
7656 // If an NBAIO source is present, use it to read the normal capture's data
7657 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07007658 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07007659
7660 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7661 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
7662 // we immediately retry the read() to get data and prevent another overflow.
7663 for (int retries = 0; retries <= 2; ++retries) {
7664 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
7665 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
7666 framesToRead);
7667 if (framesRead != OVERRUN) break;
7668 }
7669
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007670 const ssize_t availableToRead = mPipeSource->availableToRead();
7671 if (availableToRead >= 0) {
Robert Wu06db0a32021-08-10 19:05:34 +00007672 mMonopipePipeDepthStats.add(availableToRead);
Glenn Kastena2f59b32020-08-03 16:37:24 -07007673 // PipeSource is the primary clock. It is up to the AudioRecord client to keep up.
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007674 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
7675 "more frames to read than fifo size, %zd > %zu",
7676 availableToRead, mPipeFramesP2);
7677 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
7678 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
7679 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
7680 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07007681 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
7682 }
7683 if (framesRead < 0) {
7684 status_t status = (status_t) framesRead;
7685 switch (status) {
7686 case OVERRUN:
7687 ALOGW("overrun on read from pipe");
7688 framesRead = 0;
7689 break;
7690 case NEGOTIATE:
7691 ALOGE("re-negotiation is needed");
7692 framesRead = -1; // Will cause an attempt to recover.
7693 break;
7694 default:
7695 ALOGE("unknown error %d on read from pipe", status);
7696 break;
7697 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007698 }
7699 // otherwise use the HAL / AudioStreamIn directly
7700 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07007701 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007702 size_t bytesRead;
Mikhail Naganov2534b382019-09-25 13:05:02 -07007703 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007704 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07007705 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007706 if (result < 0) {
7707 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007708 } else {
7709 framesRead = bytesRead / mFrameSize;
7710 }
7711 }
7712
Andy Hung446f4df2019-02-21 12:26:41 -08007713 const int64_t lastIoEndNs = systemTime(); // end IO timing
7714
Andy Hung3f0c9022016-01-15 17:49:46 -08007715 // Update server timestamp with server stats
7716 // systemTime() is optional if the hardware supports timestamps.
Andy Hung743f6402020-06-03 13:17:04 -07007717 if (framesRead >= 0) {
7718 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
7719 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
7720 }
Andy Hung3f0c9022016-01-15 17:49:46 -08007721
7722 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007723 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08007724 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007725 if (mStandby) {
Dean Wheatley12473e92021-03-18 23:00:55 +11007726 mTimestampVerifier.discontinuity(audio_is_linear_pcm(mFormat) ?
7727 mTimestampVerifier.DISCONTINUITY_MODE_CONTINUOUS :
7728 mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
Mikhail Naganov2534b382019-09-25 13:05:02 -07007729 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07007730 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
7731
7732 mTimestampVerifier.add(position, time, mSampleRate);
7733
7734 // Correct timestamps
7735 if (isTimestampCorrectionEnabled()) {
Dean Wheatley56a583e2020-05-08 15:12:17 +10007736 ALOGVV("TS_BEFORE: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007737 id(), (long long)time, (long long)position);
7738 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
7739 position = correctedTimestamp.mFrames;
7740 time = correctedTimestamp.mTimeNs;
Dean Wheatley56a583e2020-05-08 15:12:17 +10007741 ALOGVV("TS_AFTER: %d %lld %lld",
Andy Hungc8fddf32018-08-08 18:32:37 -07007742 id(), (long long)time, (long long)position);
7743 }
7744
Andy Hung3f0c9022016-01-15 17:49:46 -08007745 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
7746 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
7747 // Note: In general record buffers should tend to be empty in
7748 // a properly running pipeline.
7749 //
7750 // Also, it is not advantageous to call get_presentation_position during the read
7751 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007752 } else {
7753 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08007754 }
7755 }
Andy Hunge6c37112019-02-26 17:38:10 -08007756
7757 // From the timestamp, input read latency is negative output write latency.
7758 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
7759 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
7760 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
7761 if (latencyMs != 0.) { // note 0. means timestamp is empty.
7762 mLatencyMs.add(latencyMs);
7763 }
7764
Andy Hung3f0c9022016-01-15 17:49:46 -08007765 // Use this to track timestamp information
7766 // ALOGD("%s", mTimestamp.toString().c_str());
7767
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007768 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007769 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007770 // Force input into standby so that it tries to recover at next read attempt
7771 inputStandBy();
7772 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007773 }
7774 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007775 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007776 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007777 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07007778 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007779
Andy Hung8946a282018-04-19 20:04:56 -07007780#ifdef TEE_SINK
7781 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
7782#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007783 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007784 {
7785 size_t part1 = mRsmpInFramesP2 - rear;
7786 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07007787 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007788 (framesRead - part1) * mFrameSize);
7789 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007790 }
Dean Wheatleyfd56e812020-11-06 22:32:21 +11007791 mRsmpInRear = audio_utils::safe_add_overflow(mRsmpInRear, (int32_t)framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007792
7793 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007794
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007795 // loop over each active track
7796 for (size_t i = 0; i < size; i++) {
7797 activeTrack = activeTracks[i];
7798
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007799 // skip fast tracks, as those are handled directly by FastCapture
7800 if (activeTrack->isFastTrack()) {
7801 continue;
7802 }
7803
Andy Hung73c02e42015-03-29 01:13:58 -07007804 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07007805 // TODO: Update the activeTrack buffer converter in case of reconfigure.
7806
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007807 enum {
7808 OVERRUN_UNKNOWN,
7809 OVERRUN_TRUE,
7810 OVERRUN_FALSE
7811 } overrun = OVERRUN_UNKNOWN;
7812
7813 // loop over getNextBuffer to handle circular sink
7814 for (;;) {
7815
7816 activeTrack->mSink.frameCount = ~0;
7817 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
7818 size_t framesOut = activeTrack->mSink.frameCount;
7819 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
7820
Andy Hung73c02e42015-03-29 01:13:58 -07007821 // check available frames and handle overrun conditions
7822 // if the record track isn't draining fast enough.
7823 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007824 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07007825 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
7826 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007827 overrun = OVERRUN_TRUE;
7828 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007829 if (framesOut == 0 || framesIn == 0) {
7830 break;
7831 }
7832
Andy Hung6770c6f2015-04-07 13:43:36 -07007833 // Don't allow framesOut to be larger than what is possible with resampling
7834 // from framesIn.
7835 // This isn't strictly necessary but helps limit buffer resizing in
7836 // RecordBufferConverter. TODO: remove when no longer needed.
7837 framesOut = min(framesOut,
7838 destinationFramesPossible(
7839 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007840
7841 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007842 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007843 // straight from RecordThread buffer to RecordTrack buffer.
7844 AudioBufferProvider::Buffer buffer;
7845 buffer.frameCount = framesOut;
7846 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
7847 if (status == OK && buffer.frameCount != 0) {
7848 ALOGV_IF(buffer.frameCount != framesOut,
7849 "%s() read less than expected (%zu vs %zu)",
7850 __func__, buffer.frameCount, framesOut);
7851 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007852 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007853 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
7854 } else {
7855 framesOut = 0;
7856 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
7857 __func__, status, buffer.frameCount);
7858 }
7859 } else {
7860 // process frames from the RecordThread buffer provider to the RecordTrack
7861 // buffer
7862 framesOut = activeTrack->mRecordBufferConverter->convert(
7863 activeTrack->mSink.raw,
7864 activeTrack->mResamplerBufferProvider,
7865 framesOut);
7866 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007867
7868 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
7869 overrun = OVERRUN_FALSE;
7870 }
7871
7872 if (activeTrack->mFramesToDrop == 0) {
7873 if (framesOut > 0) {
7874 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007875 // Sanitize before releasing if the track has no access to the source data
7876 // An idle UID receives silence from non virtual devices until active
7877 if (activeTrack->isSilenced()) {
Jean-Michel Trividdf87ef2019-08-20 15:42:04 -07007878 memset(activeTrack->mSink.raw, 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007879 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007880 activeTrack->releaseBuffer(&activeTrack->mSink);
7881 }
7882 } else {
7883 // FIXME could do a partial drop of framesOut
7884 if (activeTrack->mFramesToDrop > 0) {
Mikhail Naganov6d91ba52019-03-26 14:35:28 -07007885 activeTrack->mFramesToDrop -= (ssize_t)framesOut;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007886 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007887 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007888 }
7889 } else {
7890 activeTrack->mFramesToDrop += framesOut;
7891 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
7892 activeTrack->mSyncStartEvent->isCancelled()) {
7893 ALOGW("Synced record %s, session %d, trigger session %d",
7894 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
7895 activeTrack->sessionId(),
7896 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08007897 activeTrack->mSyncStartEvent->triggerSession() :
7898 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007899 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007900 }
7901 }
7902 }
7903
7904 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007905 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007906 }
7907 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007908
7909 switch (overrun) {
7910 case OVERRUN_TRUE:
7911 // client isn't retrieving buffers fast enough
7912 if (!activeTrack->setOverflow()) {
7913 nsecs_t now = systemTime();
7914 // FIXME should lastWarning per track?
7915 if ((now - lastWarning) > kWarningThrottleNs) {
7916 ALOGW("RecordThread: buffer overflow");
7917 lastWarning = now;
7918 }
7919 }
7920 break;
7921 case OVERRUN_FALSE:
7922 activeTrack->clearOverflow();
7923 break;
7924 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007925 break;
7926 }
7927
Andy Hung3f0c9022016-01-15 17:49:46 -08007928 // update frame information and push timestamp out
7929 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08007930 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08007931 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
7932 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007933 }
7934
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007935unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08007936 // enable changes in effect chain
7937 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007938 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07007939 if (audio_has_proportional_frames(mFormat)
7940 && loopCount == lastLoopCountRead + 1) {
7941 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
7942 const double jitterMs =
7943 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
7944 {framesRead, readPeriodNs},
7945 {0, 0} /* lastTimestamp */, mSampleRate);
7946 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
7947
7948 Mutex::Autolock _l(mLock);
7949 mIoJitterMs.add(jitterMs);
7950 mProcessTimeMs.add(processMs);
7951 }
7952 // update timing info.
7953 mLastIoBeginNs = lastIoBeginNs;
7954 mLastIoEndNs = lastIoEndNs;
7955 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007956 }
7957
Glenn Kasten93e471f2013-08-19 08:40:07 -07007958 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08007959
7960 {
7961 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07007962 for (size_t i = 0; i < mTracks.size(); i++) {
7963 sp<RecordTrack> track = mTracks[i];
7964 track->invalidate();
7965 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007966 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007967 mStartStopCond.broadcast();
7968 }
7969
7970 releaseWakeLock();
7971
7972 ALOGV("RecordThread %p exiting", this);
7973 return false;
7974}
7975
Glenn Kasten93e471f2013-08-19 08:40:07 -07007976void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08007977{
7978 if (!mStandby) {
7979 inputStandBy();
Andy Hungcf10d742020-04-28 15:38:24 -07007980 mThreadMetrics.logEndInterval();
Eric Laurent81784c32012-11-19 14:55:58 -08007981 mStandby = true;
7982 }
7983}
7984
7985void AudioFlinger::RecordThread::inputStandBy()
7986{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007987 // Idle the fast capture if it's currently running
7988 if (mFastCapture != 0) {
7989 FastCaptureStateQueue *sq = mFastCapture->sq();
7990 FastCaptureState *state = sq->begin();
7991 if (!(state->mCommand & FastCaptureState::IDLE)) {
7992 state->mCommand = FastCaptureState::COLD_IDLE;
7993 state->mColdFutexAddr = &mFastCaptureFutex;
7994 state->mColdGen++;
7995 mFastCaptureFutex = 0;
7996 sq->end();
7997 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7998 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7999#if 0
8000 if (kUseFastCapture == FastCapture_Dynamic) {
8001 // FIXME
8002 }
8003#endif
8004#ifdef AUDIO_WATCHDOG
8005 // FIXME
8006#endif
8007 } else {
8008 sq->end(false /*didModify*/);
8009 }
8010 }
Mikhail Naganov2534b382019-09-25 13:05:02 -07008011 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008012 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07008013
8014 // If going into standby, flush the pipe source.
8015 if (mPipeSource.get() != nullptr) {
8016 const ssize_t flushed = mPipeSource->flush();
8017 if (flushed > 0) {
8018 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
8019 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
8020 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
8021 }
8022 }
Eric Laurent81784c32012-11-19 14:55:58 -08008023}
8024
Glenn Kasten05997e22014-03-13 15:08:33 -07008025// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07008026sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08008027 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008028 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008029 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08008030 audio_format_t format,
8031 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08008032 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08008033 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08008034 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008035 pid_t creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008036 const AttributionSourceState& attributionSource,
Eric Laurent05067782016-06-01 18:27:28 -07008037 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08008038 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08008039 status_t *status,
Eric Laurentec376dc2021-04-08 20:41:22 +02008040 audio_port_handle_t portId,
8041 int32_t maxSharedAudioHistoryMs)
Eric Laurent81784c32012-11-19 14:55:58 -08008042{
Glenn Kasten74935e42013-12-19 08:56:45 -08008043 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008044 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008045 sp<RecordTrack> track;
8046 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07008047 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008048 audio_input_flags_t requestedFlags = *flags;
8049 uint32_t sampleRate;
Svet Ganov33761132021-05-13 22:51:08 +00008050 AttributionSourceState checkedAttributionSource = AudioFlinger::checkAttributionSourcePackage(
8051 attributionSource);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008052
8053 lStatus = initCheck();
8054 if (lStatus != NO_ERROR) {
8055 ALOGE("createRecordTrack_l() audio driver not initialized");
8056 goto Exit;
8057 }
8058
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008059 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
8060 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
8061 lStatus = BAD_VALUE;
8062 goto Exit;
8063 }
8064
Eric Laurentec376dc2021-04-08 20:41:22 +02008065 if (maxSharedAudioHistoryMs != 0) {
Svet Ganov33761132021-05-13 22:51:08 +00008066 if (!captureHotwordAllowed(checkedAttributionSource)) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008067 lStatus = PERMISSION_DENIED;
8068 goto Exit;
8069 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008070 if (maxSharedAudioHistoryMs < 0
8071 || maxSharedAudioHistoryMs > AudioFlinger::kMaxSharedAudioHistoryMs) {
8072 lStatus = BAD_VALUE;
8073 goto Exit;
8074 }
8075 }
Eric Laurentf14db3c2017-12-08 14:20:36 -08008076 if (*pSampleRate == 0) {
8077 *pSampleRate = mSampleRate;
8078 }
8079 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07008080
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008081 // special case for FAST flag considered OK if fast capture is present and access to
8082 // audio history is not required
8083 if (hasFastCapture() && mMaxSharedAudioHistoryMs == 0) {
Eric Laurent05067782016-06-01 18:27:28 -07008084 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
8085 }
8086
Eric Laurentf14db3c2017-12-08 14:20:36 -08008087 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07008088 if ((*flags & inputFlags) != *flags) {
8089 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
8090 " input flags (%08x)",
8091 *flags, inputFlags);
8092 *flags = (audio_input_flags_t)(*flags & inputFlags);
8093 }
Eric Laurent81784c32012-11-19 14:55:58 -08008094
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008095 // client expresses a preference for FAST and no access to audio history,
8096 // but we get the final say
8097 if (*flags & AUDIO_INPUT_FLAG_FAST && maxSharedAudioHistoryMs == 0) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008098 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008099 // we formerly checked for a callback handler (non-0 tid),
8100 // but that is no longer required for TRANSFER_OBTAIN mode
jiabinb00edc32021-08-16 16:27:54 +00008101 // No need to match hardware format, format conversion will be done in client side.
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07008102 //
Phil Burk7ed66a12019-04-18 13:20:30 -07008103 // Frame count is not specified (0), or is less than or equal the pipe depth.
8104 // It is OK to provide a higher capacity than requested.
8105 // We will force it to mPipeFramesP2 below.
8106 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008107 // PCM data
8108 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008109 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008110 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08008111 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07008112 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07008113 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008114 hasFastCapture() &&
8115 // there are sufficient fast track slots available
8116 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07008117 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07008118 // check compatibility with audio effects.
8119 Mutex::Autolock _l(mLock);
8120 // Do not accept FAST flag if the session has software effects
8121 sp<EffectChain> chain = getEffectChain_l(sessionId);
8122 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07008123 audio_input_flags_t old = *flags;
8124 chain->checkInputFlagCompatibility(flags);
8125 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008126 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
8127 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07008128 }
8129 }
Eric Laurent122f7e72016-06-29 11:53:29 -07008130 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008131 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
8132 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008133 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008134 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
8135 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008136 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008137 this, frameCount, mFrameCount, mPipeFramesP2,
8138 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07008139 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07008140 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07008141 }
8142 }
8143
Eric Laurentf14db3c2017-12-08 14:20:36 -08008144 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
8145 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
8146 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
8147 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
8148 lStatus = BAD_TYPE;
8149 goto Exit;
8150 }
8151
Glenn Kasten74105912014-07-03 12:28:53 -07008152 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07008153 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07008154 // fast track: frame count is exactly the pipe depth
8155 frameCount = mPipeFramesP2;
8156 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08008157 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07008158 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008159 // not fast track: max notification period is resampled equivalent of one HAL buffer time
8160 // or 20 ms if there is a fast capture
8161 // TODO This could be a roundupRatio inline, and const
8162 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
8163 * sampleRate + mSampleRate - 1) / mSampleRate;
8164 // minimum number of notification periods is at least kMinNotifications,
8165 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
8166 static const size_t kMinNotifications = 3;
8167 static const uint32_t kMinMs = 30;
8168 // TODO This could be a roundupRatio inline
8169 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
8170 // TODO This could be a roundupRatio inline
8171 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
8172 maxNotificationFrames;
8173 const size_t minFrameCount = maxNotificationFrames *
8174 max(kMinNotifications, minNotificationsByMs);
8175 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08008176 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
8177 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07008178 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07008179 }
Glenn Kasten74935e42013-12-19 08:56:45 -08008180 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08008181 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08008182
8183 { // scope for mLock
8184 Mutex::Autolock _l(mLock);
Eric Laurent2407ce32021-04-26 14:56:03 +02008185 int32_t startFrames = -1;
Eric Laurentec376dc2021-04-08 20:41:22 +02008186 if (!mSharedAudioPackageName.empty()
Svet Ganov33761132021-05-13 22:51:08 +00008187 && mSharedAudioPackageName == checkedAttributionSource.packageName
Eric Laurentec376dc2021-04-08 20:41:22 +02008188 && mSharedAudioSessionId == sessionId
Svet Ganov33761132021-05-13 22:51:08 +00008189 && captureHotwordAllowed(checkedAttributionSource)) {
Eric Laurent2407ce32021-04-26 14:56:03 +02008190 startFrames = mSharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008191 }
Eric Laurent81784c32012-11-19 14:55:58 -08008192
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008193 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07008194 format, channelMask, frameCount,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07008195 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid,
Svet Ganov33761132021-05-13 22:51:08 +00008196 checkedAttributionSource, *flags, TrackBase::TYPE_DEFAULT, portId,
8197 startFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08008198
Glenn Kasten03003332013-08-06 15:40:54 -07008199 lStatus = track->initCheck();
8200 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07008201 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08008202 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08008203 goto Exit;
8204 }
8205 mTracks.add(track);
8206
Eric Laurent05067782016-06-01 18:27:28 -07008207 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07008208 pid_t callingPid = IPCThreadState::self()->getCallingPid();
8209 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
8210 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07008211 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07008212 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008213
8214 if (maxSharedAudioHistoryMs != 0) {
8215 sendResizeBufferConfigEvent_l(maxSharedAudioHistoryMs);
8216 }
Eric Laurent81784c32012-11-19 14:55:58 -08008217 }
Glenn Kasten05997e22014-03-13 15:08:33 -07008218
Eric Laurent81784c32012-11-19 14:55:58 -08008219 lStatus = NO_ERROR;
8220
8221Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07008222 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08008223 return track;
8224}
8225
8226status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
8227 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08008228 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08008229{
8230 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
8231 sp<ThreadBase> strongMe = this;
8232 status_t status = NO_ERROR;
8233
8234 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008235 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008236 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008237 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08008238 triggerSession,
8239 recordTrack->sessionId(),
8240 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008241 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08008242 // Sync event can be cancelled by the trigger session if the track is not in a
8243 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008244 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08008245 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08008246 } else {
8247 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08008248 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008249 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08008250 }
8251 }
8252
8253 {
Glenn Kasten47c20702013-08-13 15:37:35 -07008254 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08008255 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008256 if (recordTrack->isInvalid()) {
8257 recordTrack->clearSyncStartEvent();
Eric Laurentd52a28c2020-08-21 17:10:39 -07008258 ALOGW("%s track %d: invalidated before startInput", __func__, recordTrack->portId());
8259 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008260 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008261 if (mActiveTracks.indexOf(recordTrack) >= 0) {
8262 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07008263 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
8264 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008265 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08008266 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008267 } else {
Andy Hung959b5b82021-09-24 10:46:20 -07008268 ALOGV("active record track state %d", (int)recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008269 }
8270 return status;
8271 }
8272
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008273 // TODO consider other ways of handling this, such as changing the state to :STARTING and
8274 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
8275 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008276 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08008277 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008278 status_t status = NO_ERROR;
8279 if (recordTrack->isExternalTrack()) {
8280 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08008281 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07008282 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07008283 if (recordTrack->isInvalid()) {
8284 recordTrack->clearSyncStartEvent();
8285 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
8286 recordTrack->mState = TrackBase::STARTING_2;
8287 // STARTING_2 forces destroy to call stopInput.
8288 }
Eric Laurentd52a28c2020-08-21 17:10:39 -07008289 ALOGW("%s track %d: invalidated after startInput", __func__, recordTrack->portId());
8290 return DEAD_OBJECT;
Andy Hungce685402018-10-05 17:23:27 -07008291 }
8292 if (recordTrack->mState != TrackBase::STARTING_1) {
8293 ALOGW("%s(%d): unsynchronized mState:%d change",
Andy Hung959b5b82021-09-24 10:46:20 -07008294 __func__, recordTrack->id(), (int)recordTrack->mState);
Andy Hungce685402018-10-05 17:23:27 -07008295 // Someone else has changed state, let them take over,
8296 // leave mState in the new state.
8297 recordTrack->clearSyncStartEvent();
8298 return INVALID_OPERATION;
8299 }
8300 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07008301 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07008302 ALOGW("%s(%d): startInput failed, status %d",
8303 __func__, recordTrack->id(), status);
8304 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
8305 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07008306 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07008307 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07008308 return status;
8309 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07008310 sendIoConfigEvent_l(
8311 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08008312 }
Andy Hungc2b11cb2020-04-22 09:04:01 -07008313
8314 recordTrack->logBeginInterval(patchSourcesToString(&mPatch)); // log to MediaMetrics
8315
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008316 // Catch up with current buffer indices if thread is already running.
8317 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
8318 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
8319 // see previously buffered data before it called start(), but with greater risk of overrun.
8320
Andy Hung73c02e42015-03-29 01:13:58 -07008321 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07008322 if (!recordTrack->isDirect()) {
8323 // clear any converter state as new data will be discontinuous
8324 recordTrack->mRecordBufferConverter->reset();
8325 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008326 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08008327 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08008328 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08008329 return status;
8330 }
Eric Laurent81784c32012-11-19 14:55:58 -08008331}
8332
Eric Laurent81784c32012-11-19 14:55:58 -08008333void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
8334{
8335 sp<SyncEvent> strongEvent = event.promote();
8336
8337 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08008338 sp<RefBase> ptr = strongEvent->cookie().promote();
8339 if (ptr != 0) {
8340 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
8341 recordTrack->handleSyncStartEvent(strongEvent);
8342 }
Eric Laurent81784c32012-11-19 14:55:58 -08008343 }
8344}
8345
Glenn Kastena8356f62013-07-25 14:37:52 -07008346bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08008347 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07008348 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07008349 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07008350 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08008351 return false;
8352 }
Glenn Kasten47c20702013-08-13 15:37:35 -07008353 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08008354 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07008355
Andy Hungabfab202019-03-07 19:45:54 -08008356 // NOTE: Waiting here is important to keep stop synchronous.
8357 // This is needed for proper patchRecord peer release.
Andy Hungce685402018-10-05 17:23:27 -07008358 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
8359 mWaitWorkCV.broadcast(); // signal thread to stop
8360 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08008361 }
Andy Hungce685402018-10-05 17:23:27 -07008362
8363 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08008364 ALOGV("Record stopped OK");
8365 return true;
8366 }
Andy Hungce685402018-10-05 17:23:27 -07008367
8368 // don't handle anything - we've been invalidated or restarted and in a different state
8369 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
8370 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08008371 return false;
8372}
8373
Glenn Kasten0f11b512014-01-31 16:18:54 -08008374bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08008375{
8376 return false;
8377}
8378
Glenn Kasten0f11b512014-01-31 16:18:54 -08008379status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008380{
8381#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
8382 if (!isValidSyncEvent(event)) {
8383 return BAD_VALUE;
8384 }
8385
Glenn Kastend848eb42016-03-08 13:42:11 -08008386 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08008387 status_t ret = NAME_NOT_FOUND;
8388
8389 Mutex::Autolock _l(mLock);
8390
8391 for (size_t i = 0; i < mTracks.size(); i++) {
8392 sp<RecordTrack> track = mTracks[i];
8393 if (eventSession == track->sessionId()) {
8394 (void) track->setSyncEvent(event);
8395 ret = NO_ERROR;
8396 }
8397 }
8398 return ret;
8399#else
8400 return BAD_VALUE;
8401#endif
8402}
8403
jiabin653cc0a2018-01-17 17:54:10 -08008404status_t AudioFlinger::RecordThread::getActiveMicrophones(
8405 std::vector<media::MicrophoneInfo>* activeMicrophones)
8406{
8407 ALOGV("RecordThread::getActiveMicrophones");
8408 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008409 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008410 return NO_INIT;
8411 }
jiabin9ff780e2018-03-19 18:19:52 -07008412 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
8413 return status;
jiabin653cc0a2018-01-17 17:54:10 -08008414}
8415
Paul McLean12340082019-03-19 09:35:05 -06008416status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection(
8417 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008418{
Paul McLean12340082019-03-19 09:35:05 -06008419 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008420 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008421 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008422 return NO_INIT;
8423 }
Paul McLean12340082019-03-19 09:35:05 -06008424 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008425}
8426
Paul McLean12340082019-03-19 09:35:05 -06008427status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07008428{
Paul McLean12340082019-03-19 09:35:05 -06008429 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008430 AutoMutex _l(mLock);
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008431 if (!isStreamInitialized()) {
Paul McLean8a661a32021-04-12 10:21:42 -06008432 return NO_INIT;
8433 }
Paul McLean12340082019-03-19 09:35:05 -06008434 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07008435}
8436
Eric Laurentec376dc2021-04-08 20:41:22 +02008437status_t AudioFlinger::RecordThread::shareAudioHistory(
8438 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8439 int64_t sharedAudioStartMs) {
8440 AutoMutex _l(mLock);
8441 return shareAudioHistory_l(sharedAudioPackageName, sharedSessionId, sharedAudioStartMs);
8442}
8443
8444status_t AudioFlinger::RecordThread::shareAudioHistory_l(
8445 const std::string& sharedAudioPackageName, audio_session_t sharedSessionId,
8446 int64_t sharedAudioStartMs) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008447
Eric Laurentec376dc2021-04-08 20:41:22 +02008448 if ((hasAudioSession_l(sharedSessionId) & ThreadBase::TRACK_SESSION) == 0) {
8449 return BAD_VALUE;
8450 }
Eric Laurent2407ce32021-04-26 14:56:03 +02008451
8452 if (sharedAudioStartMs < 0
8453 || sharedAudioStartMs > INT64_MAX / mSampleRate) {
Eric Laurentec376dc2021-04-08 20:41:22 +02008454 return BAD_VALUE;
8455 }
8456
Eric Laurent2407ce32021-04-26 14:56:03 +02008457 // Current implementation of the input resampling buffer wraps around indexes at 32 bit.
8458 // As we cannot detect more than one wraparound, only accept values up current write position
8459 // after one wraparound
8460 // We assume recent wraparounds on mRsmpInRear only given it is unlikely that the requesting
8461 // app waits several hours after the start time was computed.
Eric Laurent92d0a322021-07-16 15:32:33 +02008462 int64_t sharedAudioStartFrames = sharedAudioStartMs * mSampleRate / 1000;
Eric Laurent2407ce32021-04-26 14:56:03 +02008463 const int32_t sharedOffset = audio_utils::safe_sub_overflow(mRsmpInRear,
8464 (int32_t)sharedAudioStartFrames);
Eric Laurent92d0a322021-07-16 15:32:33 +02008465 // Bring the start frame position within the input buffer to match the documented
8466 // "best effort" behavior of the API.
8467 if (sharedOffset < 0) {
8468 sharedAudioStartFrames = mRsmpInRear;
8469 } else if (sharedOffset > mRsmpInFrames) {
8470 sharedAudioStartFrames =
8471 audio_utils::safe_sub_overflow(mRsmpInRear, (int32_t)mRsmpInFrames);
Eric Laurent2407ce32021-04-26 14:56:03 +02008472 }
8473
Eric Laurentec376dc2021-04-08 20:41:22 +02008474 mSharedAudioPackageName = sharedAudioPackageName;
8475 if (mSharedAudioPackageName.empty()) {
Eric Laurent92d0a322021-07-16 15:32:33 +02008476 resetAudioHistory_l();
Eric Laurentec376dc2021-04-08 20:41:22 +02008477 } else {
8478 mSharedAudioSessionId = sharedSessionId;
Eric Laurent2407ce32021-04-26 14:56:03 +02008479 mSharedAudioStartFrames = (int32_t)sharedAudioStartFrames;
Eric Laurentec376dc2021-04-08 20:41:22 +02008480 }
8481 return NO_ERROR;
8482}
8483
Eric Laurent92d0a322021-07-16 15:32:33 +02008484void AudioFlinger::RecordThread::resetAudioHistory_l() {
8485 mSharedAudioSessionId = AUDIO_SESSION_NONE;
8486 mSharedAudioStartFrames = -1;
8487 mSharedAudioPackageName = "";
8488}
8489
Kevin Rocard069c2712018-03-29 19:09:14 -07008490void AudioFlinger::RecordThread::updateMetadata_l()
8491{
Jasmine Chaeaa10e42021-05-11 10:11:14 +08008492 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
8493 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07008494 }
8495 StreamInHalInterface::SinkMetadata metadata;
8496 for (const sp<RecordTrack> &track : mActiveTracks) {
Eric Laurentb9cc0ab2021-01-29 11:46:52 +01008497 // Do not forward PatchRecord metadata to audio HAL
8498 if (track->isPatchTrack()) {
8499 continue;
8500 }
Kevin Rocard069c2712018-03-29 19:09:14 -07008501 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +01008502 record_track_metadata_v7_t trackMetadata;
8503 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -07008504 .source = track->attributes().source,
8505 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +01008506 };
8507 trackMetadata.channel_mask = track->channelMask(),
8508 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
8509
8510 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -07008511 }
8512 mInput->stream->updateSinkMetadata(metadata);
8513}
8514
Eric Laurent81784c32012-11-19 14:55:58 -08008515// destroyTrack_l() must be called with ThreadBase::mLock held
8516void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
8517{
Eric Laurentbfb1b832013-01-07 09:53:42 -08008518 track->terminate();
8519 track->mState = TrackBase::STOPPED;
Eric Laurentec376dc2021-04-08 20:41:22 +02008520
Eric Laurent81784c32012-11-19 14:55:58 -08008521 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08008522 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08008523 removeTrack_l(track);
8524 }
8525}
8526
8527void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
8528{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008529 String8 result;
8530 track->appendDump(result, false /* active */);
8531 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
8532
Eric Laurent81784c32012-11-19 14:55:58 -08008533 mTracks.remove(track);
8534 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008535 if (track->isFastTrack()) {
8536 ALOG_ASSERT(!mFastTrackAvail);
8537 mFastTrackAvail = true;
8538 }
Eric Laurent81784c32012-11-19 14:55:58 -08008539}
8540
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008541void AudioFlinger::RecordThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008542{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07008543 AudioStreamIn *input = mInput;
8544 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
8545 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08008546 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07008547 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07008548 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008549 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008550 }
Andy Hungbfa64962017-06-12 14:43:19 -07008551
8552 if (input != nullptr) {
8553 dprintf(fd, " Hal stream dump:\n");
8554 (void)input->stream->dump(fd);
8555 }
8556
Glenn Kasten6e6704c2014-07-03 10:20:00 -07008557 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07008558 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08008559
Glenn Kasten2f90c512015-12-02 11:40:09 -08008560 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
8561 // while we are dumping it. It may be inconsistent, but it won't mutate!
8562 // This is a large object so we place it on the heap.
8563 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07008564 const std::unique_ptr<FastCaptureDumpState> copy =
8565 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08008566 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08008567}
8568
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07008569void AudioFlinger::RecordThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08008570{
Eric Laurent81784c32012-11-19 14:55:58 -08008571 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08008572 size_t numtracks = mTracks.size();
8573 size_t numactive = mActiveTracks.size();
8574 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008575 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008576 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08008577 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07008578 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008579 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008580 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008581 for (size_t i = 0; i < numtracks ; ++i) {
8582 sp<RecordTrack> track = mTracks[i];
8583 if (track != 0) {
8584 bool active = mActiveTracks.indexOf(track) >= 0;
8585 if (active) {
8586 numactiveseen++;
8587 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008588 result.append(prefix);
8589 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08008590 }
Eric Laurent81784c32012-11-19 14:55:58 -08008591 }
Marco Nelissenb2208842014-02-07 14:00:50 -08008592 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07008593 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08008594 }
8595
Marco Nelissenb2208842014-02-07 14:00:50 -08008596 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008597 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08008598 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008599 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07008600 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08008601 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08008602 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08008603 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008604 result.append(prefix);
8605 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08008606 }
Glenn Kasten2b806402013-11-20 16:37:38 -08008607 }
Eric Laurent81784c32012-11-19 14:55:58 -08008608
8609 }
8610 write(fd, result.string(), result.size());
8611}
8612
Eric Laurent5ada82e2019-08-29 17:53:54 -07008613void AudioFlinger::RecordThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008614{
8615 Mutex::Autolock _l(mLock);
8616 for (size_t i = 0; i < mTracks.size() ; i++) {
8617 sp<RecordTrack> track = mTracks[i];
Eric Laurent5ada82e2019-08-29 17:53:54 -07008618 if (track != 0 && track->portId() == portId) {
Svet Ganovf4ddfef2018-01-16 07:37:58 -08008619 track->setSilenced(silenced);
8620 }
8621 }
8622}
Andy Hung73c02e42015-03-29 01:13:58 -07008623
8624void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
8625{
8626 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8627 RecordThread *recordThread = (RecordThread *) threadBase.get();
Andy Hung73c02e42015-03-29 01:13:58 -07008628 mRsmpInUnrel = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02008629 const int32_t rear = recordThread->mRsmpInRear;
8630 ssize_t deltaFrames = 0;
Eric Laurent2407ce32021-04-26 14:56:03 +02008631 if (mRecordTrack->startFrames() >= 0) {
8632 int32_t startFrames = mRecordTrack->startFrames();
8633 // Accept a recent wraparound of mRsmpInRear
8634 if (startFrames <= rear) {
8635 deltaFrames = rear - startFrames;
8636 } else {
8637 deltaFrames = (int32_t)((int64_t)rear + UINT32_MAX + 1 - startFrames);
Eric Laurentec376dc2021-04-08 20:41:22 +02008638 }
Eric Laurentec376dc2021-04-08 20:41:22 +02008639 // start frame cannot be further in the past than start of resampling buffer
8640 if ((size_t) deltaFrames > recordThread->mRsmpInFrames) {
8641 deltaFrames = recordThread->mRsmpInFrames;
8642 }
8643 }
8644 mRsmpInFront = audio_utils::safe_sub_overflow(rear, static_cast<int32_t>(deltaFrames));
Andy Hung73c02e42015-03-29 01:13:58 -07008645}
8646
8647void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
8648 size_t *framesAvailable, bool *hasOverrun)
8649{
8650 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
8651 RecordThread *recordThread = (RecordThread *) threadBase.get();
8652 const int32_t rear = recordThread->mRsmpInRear;
8653 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008654 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07008655
8656 size_t framesIn;
8657 bool overrun = false;
8658 if (filled < 0) {
8659 // should not happen, but treat like a massive overrun and re-sync
8660 framesIn = 0;
8661 mRsmpInFront = rear;
8662 overrun = true;
8663 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
8664 framesIn = (size_t) filled;
8665 } else {
8666 // client is not keeping up with server, but give it latest data
8667 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07008668 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
8669 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07008670 overrun = true;
8671 }
8672 if (framesAvailable != NULL) {
8673 *framesAvailable = framesIn;
8674 }
8675 if (hasOverrun != NULL) {
8676 *hasOverrun = overrun;
8677 }
8678}
8679
Eric Laurent81784c32012-11-19 14:55:58 -08008680// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008681status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08008682 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008683{
Andy Hung73c02e42015-03-29 01:13:58 -07008684 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008685 if (threadBase == 0) {
8686 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008687 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008688 return NOT_ENOUGH_DATA;
8689 }
8690 RecordThread *recordThread = (RecordThread *) threadBase.get();
8691 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07008692 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07008693 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008694 // FIXME should not be P2 (don't want to increase latency)
8695 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08008696 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07008697 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008698
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008699 front &= recordThread->mRsmpInFramesP2 - 1;
8700 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07008701 if (part1 > (size_t) filled) {
8702 part1 = filled;
8703 }
8704 size_t ask = buffer->frameCount;
8705 ALOG_ASSERT(ask > 0);
8706 if (part1 > ask) {
8707 part1 = ask;
8708 }
8709 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07008710 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07008711 buffer->raw = NULL;
8712 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07008713 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07008714 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08008715 }
8716
Andy Hung57446612015-04-19 23:56:46 -07008717 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07008718 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07008719 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08008720 return NO_ERROR;
8721}
8722
8723// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008724void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
8725 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008726{
Hongwei Wang95e37682019-04-12 11:13:36 -07008727 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008728 if (stepCount == 0) {
8729 return;
8730 }
Andy Hung73c02e42015-03-29 01:13:58 -07008731 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
8732 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07008733 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008734 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08008735 buffer->frameCount = 0;
8736}
8737
Eric Laurentd8365c52017-07-16 15:27:05 -07008738void AudioFlinger::RecordThread::checkBtNrec()
8739{
8740 Mutex::Autolock _l(mLock);
8741 checkBtNrec_l();
8742}
8743
8744void AudioFlinger::RecordThread::checkBtNrec_l()
8745{
8746 // disable AEC and NS if the device is a BT SCO headset supporting those
8747 // pre processings
jiabinc52b1ff2019-10-31 17:20:42 -07008748 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Eric Laurentd8365c52017-07-16 15:27:05 -07008749 mAudioFlinger->btNrecIsOff();
8750 if (mBtNrecSuspended.exchange(suspend) != suspend) {
8751 for (size_t i = 0; i < mEffectChains.size(); i++) {
8752 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
8753 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
8754 }
8755 }
8756}
8757
Andy Hung97a893e2015-03-29 01:03:07 -07008758
Eric Laurent10351942014-05-08 18:49:52 -07008759bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
8760 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08008761{
8762 bool reconfig = false;
8763
Eric Laurent10351942014-05-08 18:49:52 -07008764 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08008765
Eric Laurent10351942014-05-08 18:49:52 -07008766 audio_format_t reqFormat = mFormat;
8767 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07008768 // 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 -07008769 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
8770
8771 AudioParameter param = AudioParameter(keyValuePair);
8772 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07008773
8774 // scope for AutoPark extends to end of method
8775 AutoPark<FastCapture> park(mFastCapture);
8776
Eric Laurent10351942014-05-08 18:49:52 -07008777 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
8778 // channel count change can be requested. Do we mandate the first client defines the
8779 // HAL sampling rate and channel count or do we allow changes on the fly?
8780 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
8781 samplingRate = value;
8782 reconfig = true;
8783 }
8784 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07008785 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07008786 status = BAD_VALUE;
8787 } else {
8788 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08008789 reconfig = true;
8790 }
Eric Laurent10351942014-05-08 18:49:52 -07008791 }
8792 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
8793 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07008794 if (!audio_is_input_channel(mask) ||
Andy Hung936845a2021-06-08 00:09:06 -07008795 audio_channel_count_from_in_mask(mask) > FCC_LIMIT) {
Eric Laurent10351942014-05-08 18:49:52 -07008796 status = BAD_VALUE;
8797 } else {
8798 channelMask = mask;
8799 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008800 }
Eric Laurent10351942014-05-08 18:49:52 -07008801 }
8802 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
8803 // do not accept frame count changes if tracks are open as the track buffer
8804 // size depends on frame count and correct behavior would not be guaranteed
8805 // if frame count is changed after track creation
8806 if (mActiveTracks.size() > 0) {
8807 status = INVALID_OPERATION;
8808 } else {
8809 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008810 }
Eric Laurent10351942014-05-08 18:49:52 -07008811 }
8812 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07008813 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008814 }
8815 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
8816 mAudioSource != (audio_source_t)value) {
jiabinc52b1ff2019-10-31 17:20:42 -07008817 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008818 }
Glenn Kastene198c362013-08-13 09:13:36 -07008819
Eric Laurent10351942014-05-08 18:49:52 -07008820 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008821 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008822 if (status == INVALID_OPERATION) {
8823 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008824 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008825 }
8826 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008827 if (status == BAD_VALUE) {
Mikhail Naganov560637e2021-03-31 22:40:13 +00008828 audio_config_base_t config = AUDIO_CONFIG_BASE_INITIALIZER;
8829 if (mInput->stream->getAudioProperties(&config) == OK &&
8830 audio_is_linear_pcm(config.format) && audio_is_linear_pcm(reqFormat) &&
8831 config.sample_rate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
Andy Hung936845a2021-06-08 00:09:06 -07008832 audio_channel_count_from_in_mask(config.channel_mask) <= FCC_LIMIT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008833 status = NO_ERROR;
8834 }
Eric Laurent81784c32012-11-19 14:55:58 -08008835 }
Eric Laurent10351942014-05-08 18:49:52 -07008836 if (status == NO_ERROR) {
8837 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07008838 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08008839 }
8840 }
Eric Laurent81784c32012-11-19 14:55:58 -08008841 }
Eric Laurent10351942014-05-08 18:49:52 -07008842
Eric Laurent81784c32012-11-19 14:55:58 -08008843 return reconfig;
8844}
8845
8846String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
8847{
Eric Laurent81784c32012-11-19 14:55:58 -08008848 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008849 if (initCheck() == NO_ERROR) {
8850 String8 out_s8;
8851 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
8852 return out_s8;
8853 }
Eric Laurent81784c32012-11-19 14:55:58 -08008854 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008855 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08008856}
8857
Mikhail Naganov88536df2021-07-26 17:30:29 -07008858void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008859 audio_port_handle_t portId) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07008860 sp<AudioIoDescriptor> desc;
Eric Laurent81784c32012-11-19 14:55:58 -08008861 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008862 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008863 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07008864 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07008865 desc = sp<AudioIoDescriptor>::make(mId, mPatch, true /*isInput*/,
8866 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08008867 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07008868 case AUDIO_CLIENT_STARTED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07008869 desc = sp<AudioIoDescriptor>::make(mId, mPatch, portId);
Eric Laurent09f1ed22019-04-24 17:45:17 -07008870 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07008871 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08008872 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07008873 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08008874 break;
8875 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07008876 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08008877}
8878
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008879void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008880{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008881 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8882 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07008883 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008884 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8885 if (audio_is_linear_pcm(mFormat)) {
Andy Hung936845a2021-06-08 00:09:06 -07008886 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_LIMIT, "HAL channel count %d > %d",
8887 mChannelCount, FCC_LIMIT);
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008888 } else {
Andy Hung936845a2021-06-08 00:09:06 -07008889 // Can have more that FCC_LIMIT channels in encoded streams.
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008890 ALOGI("HAL format %#x is not linear pcm", mFormat);
8891 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008892 result = mInput->stream->getFrameSize(&mFrameSize);
8893 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008894 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
8895 mFrameSize);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008896 result = mInput->stream->getBufferSize(&mBufferSize);
8897 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08008898 mFrameCount = mBufferSize / mFrameSize;
Hayden Gomes1a89ab32020-06-12 11:05:47 -07008899 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
8900 "mBufferSize=%zu, mFrameCount=%zu",
8901 this, mChannelCount, mFormat, mFrameSize, mBufferSize, mFrameCount);
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008902
Eric Laurentec376dc2021-04-08 20:41:22 +02008903 // mRsmpInFrames must be 0 before calling resizeInputBuffer_l for the first time
8904 mRsmpInFrames = 0;
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02008905 resizeInputBuffer_l(0 /*maxSharedAudioHistoryMs*/);
Eric Laurent81784c32012-11-19 14:55:58 -08008906
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008907 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
8908 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Andy Hungea840382020-05-05 21:50:17 -07008909
8910 audio_input_flags_t flags = mInput->flags;
8911 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
8912 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
8913 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
8914 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
8915 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
8916 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
8917 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
8918 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
8919 .record();
Eric Laurent81784c32012-11-19 14:55:58 -08008920}
8921
Glenn Kasten5f972c02014-01-13 09:59:31 -08008922uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08008923{
8924 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008925 uint32_t result;
8926 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
8927 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08008928 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008929 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008930}
8931
Glenn Kastend848eb42016-03-08 13:42:11 -08008932KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08008933{
Glenn Kastend848eb42016-03-08 13:42:11 -08008934 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08008935 Mutex::Autolock _l(mLock);
8936 for (size_t j = 0; j < mTracks.size(); ++j) {
8937 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08008938 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08008939 if (ids.indexOfKey(sessionId) < 0) {
8940 ids.add(sessionId, true);
8941 }
8942 }
8943 return ids;
8944}
8945
8946AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
8947{
8948 Mutex::Autolock _l(mLock);
8949 AudioStreamIn *input = mInput;
8950 mInput = NULL;
8951 return input;
8952}
8953
8954// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008955sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08008956{
8957 if (mInput == NULL) {
8958 return NULL;
8959 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008960 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08008961}
8962
8963status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8964{
Eric Laurent81784c32012-11-19 14:55:58 -08008965 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07008966 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08008967 chain->setInBuffer(NULL);
8968 chain->setOutBuffer(NULL);
8969
8970 checkSuspendOnAddEffectChain_l(chain);
8971
Eric Laurent1b928682014-10-02 19:41:47 -07008972 // make sure enabled pre processing effects state is communicated to the HAL as we
8973 // just moved them to a new input stream.
8974 chain->syncHalEffectsState();
8975
Eric Laurent81784c32012-11-19 14:55:58 -08008976 mEffectChains.add(chain);
8977
8978 return NO_ERROR;
8979}
8980
8981size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8982{
8983 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008984
8985 for (size_t i = 0; i < mEffectChains.size(); i++) {
8986 if (chain == mEffectChains[i]) {
8987 mEffectChains.removeAt(i);
8988 break;
8989 }
Eric Laurent81784c32012-11-19 14:55:58 -08008990 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008991 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08008992}
8993
Eric Laurent1c333e22014-05-20 10:48:17 -07008994status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
8995 audio_patch_handle_t *handle)
8996{
8997 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008998
8999 // store new device and send to effects
jiabinc52b1ff2019-10-31 17:20:42 -07009000 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009001 mInDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
François Gaffie0c280aa2018-07-25 10:02:15 +02009002 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07009003 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009004 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07009005 }
9006
Eric Laurentd8365c52017-07-16 15:27:05 -07009007 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07009008
9009 // store new source and send to effects
9010 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9011 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07009012 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07009013 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07009014 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009015 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009016
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009017 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009018 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9019 status = hwDevice->createAudioPatch(patch->num_sources,
9020 patch->sources,
9021 patch->num_sinks,
9022 patch->sinks,
9023 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009024 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07009025 char *address;
9026 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
9027 address = audio_device_address_to_parameter(
9028 patch->sources[0].ext.device.type,
9029 patch->sources[0].ext.device.address);
9030 } else {
9031 address = (char *)calloc(1, 1);
9032 }
9033 AudioParameter param = AudioParameter(String8(address));
9034 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07009035 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07009036 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07009037 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07009038 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009039 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07009040 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07009041 }
Eric Laurent054d9d32015-04-24 08:48:48 -07009042
jiabinc52b1ff2019-10-31 17:20:42 -07009043 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07009044 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabinc52b1ff2019-10-31 17:20:42 -07009045 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07009046 }
Eric Laurent296fb132015-05-01 11:38:42 -07009047
Andy Hungc2b11cb2020-04-22 09:04:01 -07009048 const std::string pathSourcesAsString = patchSourcesToString(patch);
Andy Hungcf10d742020-04-28 15:38:24 -07009049 mThreadMetrics.logEndInterval();
Andy Hungea840382020-05-05 21:50:17 -07009050 mThreadMetrics.logCreatePatch(pathSourcesAsString, /* outDevices */ {});
Andy Hungcf10d742020-04-28 15:38:24 -07009051 mThreadMetrics.logBeginInterval();
Andy Hungc2b11cb2020-04-22 09:04:01 -07009052 // also dispatch to active AudioRecords
9053 for (const auto &track : mActiveTracks) {
9054 track->logEndInterval();
9055 track->logBeginInterval(pathSourcesAsString);
9056 }
Eric Laurent1c333e22014-05-20 10:48:17 -07009057 return status;
9058}
9059
9060status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9061{
9062 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07009063
jiabinc52b1ff2019-10-31 17:20:42 -07009064 mPatch = audio_patch{};
9065 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07009066
Mikhail Naganov9ee05402016-10-13 15:58:17 -07009067 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07009068 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
9069 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07009070 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07009071 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07009072 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07009073 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07009074 }
9075 return status;
9076}
9077
jiabinc52b1ff2019-10-31 17:20:42 -07009078void AudioFlinger::RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
9079{
wendy lin56aa82b2020-12-02 15:19:55 +08009080 Mutex::Autolock _l(mLock);
jiabinc52b1ff2019-10-31 17:20:42 -07009081 mOutDevices = outDevices;
9082 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
9083 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009084 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabinc52b1ff2019-10-31 17:20:42 -07009085 }
9086}
9087
Eric Laurentec376dc2021-04-08 20:41:22 +02009088int32_t AudioFlinger::RecordThread::getOldestFront_l()
9089{
9090 if (mTracks.size() == 0) {
Eric Laurent92d0a322021-07-16 15:32:33 +02009091 return mRsmpInRear;
Eric Laurentec376dc2021-04-08 20:41:22 +02009092 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009093 int32_t oldestFront = mRsmpInRear;
9094 int32_t maxFilled = 0;
Eric Laurentec376dc2021-04-08 20:41:22 +02009095 for (size_t i = 0; i < mTracks.size(); i++) {
Eric Laurent2407ce32021-04-26 14:56:03 +02009096 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
9097 int32_t filled;
Eric Laurent92d0a322021-07-16 15:32:33 +02009098 (void)__builtin_sub_overflow(mRsmpInRear, front, &filled);
Eric Laurent2407ce32021-04-26 14:56:03 +02009099 if (filled > maxFilled) {
9100 oldestFront = front;
9101 maxFilled = filled;
9102 }
Eric Laurentec376dc2021-04-08 20:41:22 +02009103 }
Eric Laurent92d0a322021-07-16 15:32:33 +02009104 if (maxFilled > mRsmpInFrames) {
9105 (void)__builtin_sub_overflow(mRsmpInRear, mRsmpInFrames, &oldestFront);
9106 }
Eric Laurent2407ce32021-04-26 14:56:03 +02009107 return oldestFront;
Eric Laurentec376dc2021-04-08 20:41:22 +02009108}
9109
9110void AudioFlinger::RecordThread::updateFronts_l(int32_t offset)
9111{
9112 if (offset == 0) {
9113 return;
9114 }
9115 for (size_t i = 0; i < mTracks.size(); i++) {
9116 int32_t front = mTracks[i]->mResamplerBufferProvider->getFront();
9117 front = audio_utils::safe_sub_overflow(front, offset);
9118 mTracks[i]->mResamplerBufferProvider->setFront(front);
9119 }
9120}
9121
9122void AudioFlinger::RecordThread::resizeInputBuffer_l(int32_t maxSharedAudioHistoryMs)
9123{
9124 // This is the formula for calculating the temporary buffer size.
9125 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
9126 // 1 full output buffer, regardless of the alignment of the available input.
9127 // The value is somewhat arbitrary, and could probably be even larger.
9128 // A larger value should allow more old data to be read after a track calls start(),
9129 // without increasing latency.
9130 //
9131 // Note this is independent of the maximum downsampling ratio permitted for capture.
9132 size_t minRsmpInFrames = mFrameCount * 7;
9133
9134 // maxSharedAudioHistoryMs != 0 indicates a request to possibly make some part of the audio
9135 // capture history available to another client using the same session ID:
9136 // dimension the resampler input buffer accordingly.
9137
9138 // Get oldest client read position: getOldestFront_l() must be called before altering
9139 // mRsmpInRear, or mRsmpInFrames
9140 int32_t previousFront = getOldestFront_l();
9141 size_t previousRsmpInFramesP2 = mRsmpInFramesP2;
9142 int32_t previousRear = mRsmpInRear;
9143 mRsmpInRear = 0;
9144
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009145 ALOG_ASSERT(maxSharedAudioHistoryMs >= 0
9146 && maxSharedAudioHistoryMs <= AudioFlinger::kMaxSharedAudioHistoryMs,
9147 "resizeInputBuffer_l() called with invalid max shared history %d",
9148 maxSharedAudioHistoryMs);
Eric Laurentec376dc2021-04-08 20:41:22 +02009149 if (maxSharedAudioHistoryMs != 0) {
9150 // resizeInputBuffer_l should never be called with a non zero shared history if the
9151 // buffer was not already allocated
9152 ALOG_ASSERT(mRsmpInBuffer != nullptr && mRsmpInFrames != 0,
9153 "resizeInputBuffer_l() called with shared history and unallocated buffer");
9154 size_t rsmpInFrames = (size_t)maxSharedAudioHistoryMs * mSampleRate / 1000;
9155 // never reduce resampler input buffer size
Eric Laurent92d0a322021-07-16 15:32:33 +02009156 if (rsmpInFrames <= mRsmpInFrames) {
Eric Laurentec376dc2021-04-08 20:41:22 +02009157 return;
9158 }
9159 mRsmpInFrames = rsmpInFrames;
9160 }
Eric Laurent5f0fd7b2021-05-07 16:33:26 +02009161 mMaxSharedAudioHistoryMs = maxSharedAudioHistoryMs;
Eric Laurentec376dc2021-04-08 20:41:22 +02009162 // Note: mRsmpInFrames is 0 when called with maxSharedAudioHistoryMs equals to 0 so it is always
9163 // initialized
9164 if (mRsmpInFrames < minRsmpInFrames) {
9165 mRsmpInFrames = minRsmpInFrames;
9166 }
9167 mRsmpInFramesP2 = roundup(mRsmpInFrames);
9168
9169 // TODO optimize audio capture buffer sizes ...
9170 // Here we calculate the size of the sliding buffer used as a source
9171 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
9172 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
9173 // be better to have it derived from the pipe depth in the long term.
9174 // The current value is higher than necessary. However it should not add to latency.
9175
9176 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
9177 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
9178
9179 void *rsmpInBuffer;
9180 (void)posix_memalign(&rsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
9181 // if posix_memalign fails, will segv here.
9182 memset(rsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
9183
9184 // Copy audio history if any from old buffer before freeing it
9185 if (previousRear != 0) {
9186 ALOG_ASSERT(mRsmpInBuffer != nullptr,
9187 "resizeInputBuffer_l() called with null buffer but frames already read from HAL");
9188
9189 ssize_t unread = audio_utils::safe_sub_overflow(previousRear, previousFront);
9190 previousFront &= previousRsmpInFramesP2 - 1;
9191 size_t part1 = previousRsmpInFramesP2 - previousFront;
9192 if (part1 > (size_t) unread) {
9193 part1 = unread;
9194 }
9195 if (part1 != 0) {
9196 memcpy(rsmpInBuffer, (const uint8_t*)mRsmpInBuffer + previousFront * mFrameSize,
9197 part1 * mFrameSize);
9198 mRsmpInRear = part1;
9199 part1 = unread - part1;
9200 if (part1 != 0) {
9201 memcpy((uint8_t*)rsmpInBuffer + mRsmpInRear * mFrameSize,
9202 (const uint8_t*)mRsmpInBuffer, part1 * mFrameSize);
9203 mRsmpInRear += part1;
9204 }
9205 }
9206 // Update front for all clients according to new rear
9207 updateFronts_l(audio_utils::safe_sub_overflow(previousRear, mRsmpInRear));
9208 } else {
9209 mRsmpInRear = 0;
9210 }
9211 free(mRsmpInBuffer);
9212 mRsmpInBuffer = rsmpInBuffer;
9213}
9214
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009215void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009216{
9217 Mutex::Autolock _l(mLock);
9218 mTracks.add(record);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009219 if (record->getSource()) {
9220 mSource = record->getSource();
9221 }
Eric Laurent83b88082014-06-20 18:31:16 -07009222}
9223
Mikhail Naganov444ecc32018-05-01 17:40:05 -07009224void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07009225{
9226 Mutex::Autolock _l(mLock);
Mikhail Naganov2534b382019-09-25 13:05:02 -07009227 if (mSource == record->getSource()) {
9228 mSource = mInput;
9229 }
Eric Laurent83b88082014-06-20 18:31:16 -07009230 destroyTrack_l(record);
9231}
9232
Mikhail Naganovdc769682018-05-04 15:34:08 -07009233void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07009234{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009235 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07009236 config->role = AUDIO_PORT_ROLE_SINK;
9237 config->ext.mix.hw_module = mInput->audioHwDev->handle();
9238 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009239 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9240 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9241 config->flags.input = mInput->flags;
9242 }
Eric Laurent83b88082014-06-20 18:31:16 -07009243}
Eric Laurent1c333e22014-05-20 10:48:17 -07009244
Eric Laurent6acd1d42017-01-04 14:23:29 -08009245// ----------------------------------------------------------------------------
9246// Mmap
9247// ----------------------------------------------------------------------------
9248
9249AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
9250 : mThread(thread)
9251{
Phil Burk9fabbf82017-08-03 12:02:00 -07009252 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08009253}
9254
9255AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
9256{
Phil Burk9fabbf82017-08-03 12:02:00 -07009257 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009258}
9259
9260status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
9261 struct audio_mmap_buffer_info *info)
9262{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009263 return mThread->createMmapBuffer(minSizeFrames, info);
9264}
9265
9266status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
9267{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009268 return mThread->getMmapPosition(position);
9269}
9270
jiabinb7d8c5a2020-08-26 17:24:52 -07009271status_t AudioFlinger::MmapThreadHandle::getExternalPosition(uint64_t *position,
9272 int64_t *timeNanos) {
9273 return mThread->getExternalPosition(position, timeNanos);
9274}
9275
Eric Laurenta54f1282017-07-01 19:39:32 -07009276status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009277 const audio_attributes_t *attr, audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009278
9279{
jiabind1f1cb62020-03-24 11:57:57 -07009280 return mThread->start(client, attr, handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009281}
9282
9283status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
9284{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009285 return mThread->stop(handle);
9286}
9287
Eric Laurent18b57012017-02-13 16:23:52 -08009288status_t AudioFlinger::MmapThreadHandle::standby()
9289{
Eric Laurent18b57012017-02-13 16:23:52 -08009290 return mThread->standby();
9291}
9292
Eric Laurent6acd1d42017-01-04 14:23:29 -08009293
9294AudioFlinger::MmapThread::MmapThread(
9295 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
Andy Hungcf10d742020-04-28 15:38:24 -07009296 AudioHwDevice *hwDev, sp<StreamHalInterface> stream, bool systemReady, bool isOut)
Andy Hungea840382020-05-05 21:50:17 -07009297 : ThreadBase(audioFlinger, id, (isOut ? MMAP_PLAYBACK : MMAP_CAPTURE), systemReady, isOut),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009298 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02009299 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009300 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07009301 mActiveTracks(&this->mLocalLog),
9302 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
9303 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009304{
Eric Laurent18b57012017-02-13 16:23:52 -08009305 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009306 readHalParameters_l();
9307}
9308
9309AudioFlinger::MmapThread::~MmapThread()
9310{
9311}
9312
9313void AudioFlinger::MmapThread::onFirstRef()
9314{
9315 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
9316}
9317
9318void AudioFlinger::MmapThread::disconnect()
9319{
Eric Laurent331679c2018-04-16 17:03:16 -07009320 ActiveTracks<MmapTrack> activeTracks;
9321 {
9322 Mutex::Autolock _l(mLock);
9323 for (const sp<MmapTrack> &t : mActiveTracks) {
9324 activeTracks.add(t);
9325 }
9326 }
9327 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009328 stop(t->portId());
9329 }
Phil Burk9fabbf82017-08-03 12:02:00 -07009330 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009331 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009332 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009333 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009334 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009335 }
9336}
9337
9338
9339void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
9340 audio_stream_type_t streamType __unused,
9341 audio_session_t sessionId,
9342 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009343 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009344 audio_port_handle_t portId)
9345{
9346 mAttr = *attr;
9347 mSessionId = sessionId;
9348 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009349 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009350 mPortId = portId;
9351}
9352
9353status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
9354 struct audio_mmap_buffer_info *info)
9355{
9356 if (mHalStream == 0) {
9357 return NO_INIT;
9358 }
Eric Laurent18b57012017-02-13 16:23:52 -08009359 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009360 return mHalStream->createMmapBuffer(minSizeFrames, info);
9361}
9362
9363status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
9364{
9365 if (mHalStream == 0) {
9366 return NO_INIT;
9367 }
9368 return mHalStream->getMmapPosition(position);
9369}
9370
Eric Laurent331679c2018-04-16 17:03:16 -07009371status_t AudioFlinger::MmapThread::exitStandby()
9372{
9373 status_t ret = mHalStream->start();
9374 if (ret != NO_ERROR) {
9375 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
9376 return ret;
9377 }
Andy Hungcf10d742020-04-28 15:38:24 -07009378 if (mStandby) {
9379 mThreadMetrics.logBeginInterval();
9380 mStandby = false;
9381 }
Eric Laurent331679c2018-04-16 17:03:16 -07009382 return NO_ERROR;
9383}
9384
Eric Laurenta54f1282017-07-01 19:39:32 -07009385status_t AudioFlinger::MmapThread::start(const AudioClient& client,
jiabind1f1cb62020-03-24 11:57:57 -07009386 const audio_attributes_t *attr,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009387 audio_port_handle_t *handle)
9388{
Eric Laurenta54f1282017-07-01 19:39:32 -07009389 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
Svet Ganov33761132021-05-13 22:51:08 +00009390 client.attributionSource.uid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009391 if (mHalStream == 0) {
9392 return NO_INIT;
9393 }
9394
9395 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009396
Eric Laurenta54f1282017-07-01 19:39:32 -07009397 if (*handle == mPortId) {
Phil Burk98ab4082020-09-25 21:46:34 +00009398 // For the first track, reuse portId and session allocated when the stream was opened.
9399 ret = exitStandby();
9400 if (ret == NO_ERROR) {
9401 acquireWakeLock();
9402 }
9403 return ret;
Eric Laurenta54f1282017-07-01 19:39:32 -07009404 }
9405
9406 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
9407
9408 audio_io_handle_t io = mId;
9409 if (isOutput()) {
9410 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9411 config.sample_rate = mSampleRate;
9412 config.channel_mask = mChannelMask;
9413 config.format = mFormat;
9414 audio_stream_type_t stream = streamType();
9415 audio_output_flags_t flags =
9416 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009417 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08009418 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurenta54f1282017-07-01 19:39:32 -07009419 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
9420 mSessionId,
9421 &stream,
Svet Ganov33761132021-05-13 22:51:08 +00009422 client.attributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -07009423 &config,
9424 flags,
9425 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08009426 &portId,
9427 &secondaryOutputs);
9428 ALOGD_IF(!secondaryOutputs.empty(),
9429 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009430 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07009431 audio_config_base_t config;
9432 config.sample_rate = mSampleRate;
9433 config.channel_mask = mChannelMask;
9434 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009435 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07009436 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -07009437 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -07009438 mSessionId,
Svet Ganov33761132021-05-13 22:51:08 +00009439 client.attributionSource,
Eric Laurenta54f1282017-07-01 19:39:32 -07009440 &config,
9441 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
9442 &deviceId,
9443 &portId);
9444 }
9445 // APM should not chose a different input or output stream for the same set of attributes
9446 // and audo configuration
9447 if (ret != NO_ERROR || io != mId) {
9448 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
9449 __FUNCTION__, ret, io, mId);
9450 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009451 }
9452
9453 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009454 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009455 } else {
Eric Laurent4eb58f12018-12-07 16:41:02 -08009456 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009457 }
9458
Eric Laurent331679c2018-04-16 17:03:16 -07009459 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009460 // abort if start is rejected by audio policy manager
9461 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009462 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07009463 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07009464 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009465 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009466 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009467 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009468 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009469 }
Eric Laurent331679c2018-04-16 17:03:16 -07009470 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08009471 } else {
9472 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009473 }
9474 return PERMISSION_DENIED;
9475 }
9476
Kevin Rocard1f564ac2018-03-29 13:53:10 -07009477 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
jiabind1f1cb62020-03-24 11:57:57 -07009478 sp<MmapTrack> track = new MmapTrack(this, attr == nullptr ? mAttr : *attr, mSampleRate, mFormat,
Svet Ganov33761132021-05-13 22:51:08 +00009479 mChannelMask, mSessionId, isOutput(),
9480 client.attributionSource,
Philip P. Moltmannbda45752020-07-17 16:41:18 -07009481 IPCThreadState::self()->getCallingPid(), portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009482
Eric Laurent4eb58f12018-12-07 16:41:02 -08009483 if (isOutput()) {
9484 // force volume update when a new track is added
9485 mHalVolFloat = -1.0f;
9486 } else if (!track->isSilenced_l()) {
9487 for (const sp<MmapTrack> &t : mActiveTracks) {
Svet Ganov33761132021-05-13 22:51:08 +00009488 if (t->isSilenced_l() && t->uid() != client.attributionSource.uid)
Eric Laurent4eb58f12018-12-07 16:41:02 -08009489 t->invalidate();
9490 }
9491 }
9492
9493
Eric Laurent6acd1d42017-01-04 14:23:29 -08009494 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07009495 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009496 if (chain != 0) {
Eric Laurentd66d7a12021-07-13 13:35:32 +02009497 chain->setStrategy(getStrategyForStream(streamType()));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009498 chain->incTrackCnt();
9499 chain->incActiveTrackCnt();
9500 }
9501
Andy Hungc2b11cb2020-04-22 09:04:01 -07009502 track->logBeginInterval(patchSinksToString(&mPatch)); // log to MediaMetrics
Eric Laurent6acd1d42017-01-04 14:23:29 -08009503 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009504 broadcast_l();
9505
Eric Laurenta54f1282017-07-01 19:39:32 -07009506 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009507
9508 return NO_ERROR;
9509}
9510
9511status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
9512{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009513 ALOGV("%s handle %d", __FUNCTION__, handle);
9514
9515 if (mHalStream == 0) {
9516 return NO_INIT;
9517 }
9518
Eric Laurenta54f1282017-07-01 19:39:32 -07009519 if (handle == mPortId) {
9520 mHalStream->stop();
Phil Burk98ab4082020-09-25 21:46:34 +00009521 releaseWakeLock();
Eric Laurenta54f1282017-07-01 19:39:32 -07009522 return NO_ERROR;
9523 }
9524
Eric Laurent331679c2018-04-16 17:03:16 -07009525 Mutex::Autolock _l(mLock);
9526
Eric Laurent6acd1d42017-01-04 14:23:29 -08009527 sp<MmapTrack> track;
9528 for (const sp<MmapTrack> &t : mActiveTracks) {
9529 if (handle == t->portId()) {
9530 track = t;
9531 break;
9532 }
9533 }
9534 if (track == 0) {
9535 return BAD_VALUE;
9536 }
9537
9538 mActiveTracks.remove(track);
9539
Eric Laurent331679c2018-04-16 17:03:16 -07009540 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009541 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07009542 AudioSystem::stopOutput(track->portId());
9543 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009544 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08009545 AudioSystem::stopInput(track->portId());
9546 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009547 }
Eric Laurent331679c2018-04-16 17:03:16 -07009548 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009549
9550 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
9551 if (chain != 0) {
9552 chain->decActiveTrackCnt();
9553 chain->decTrackCnt();
9554 }
9555
9556 broadcast_l();
9557
Eric Laurent6acd1d42017-01-04 14:23:29 -08009558 return NO_ERROR;
9559}
9560
Eric Laurent18b57012017-02-13 16:23:52 -08009561status_t AudioFlinger::MmapThread::standby()
9562{
9563 ALOGV("%s", __FUNCTION__);
9564
9565 if (mHalStream == 0) {
9566 return NO_INIT;
9567 }
Eric Tan39ec8d62018-07-24 09:49:29 -07009568 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08009569 return INVALID_OPERATION;
9570 }
9571 mHalStream->standby();
Andy Hungcf10d742020-04-28 15:38:24 -07009572 if (!mStandby) {
9573 mThreadMetrics.logEndInterval();
9574 mStandby = true;
9575 }
Eric Laurent18b57012017-02-13 16:23:52 -08009576 releaseWakeLock();
9577 return NO_ERROR;
9578}
9579
Eric Laurent6acd1d42017-01-04 14:23:29 -08009580
9581void AudioFlinger::MmapThread::readHalParameters_l()
9582{
9583 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
9584 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
9585 mFormat = mHALFormat;
9586 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
9587 result = mHalStream->getFrameSize(&mFrameSize);
9588 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
Hayden Gomes1a89ab32020-06-12 11:05:47 -07009589 LOG_ALWAYS_FATAL_IF(mFrameSize <= 0, "Error frame size was %zu but must be greater than zero",
9590 mFrameSize);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009591 result = mHalStream->getBufferSize(&mBufferSize);
9592 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
9593 mFrameCount = mBufferSize / mFrameSize;
Andy Hungc2b11cb2020-04-22 09:04:01 -07009594
Andy Hungcf10d742020-04-28 15:38:24 -07009595 // TODO: make a readHalParameters call?
9596 mediametrics::LogItem item(mThreadMetrics.getMetricsId());
Andy Hungc2b11cb2020-04-22 09:04:01 -07009597 item.set(AMEDIAMETRICS_PROP_EVENT, AMEDIAMETRICS_PROP_EVENT_VALUE_READPARAMETERS)
9598 .set(AMEDIAMETRICS_PROP_ENCODING, formatToString(mFormat).c_str())
9599 .set(AMEDIAMETRICS_PROP_SAMPLERATE, (int32_t)mSampleRate)
9600 .set(AMEDIAMETRICS_PROP_CHANNELMASK, (int32_t)mChannelMask)
9601 .set(AMEDIAMETRICS_PROP_CHANNELCOUNT, (int32_t)mChannelCount)
9602 .set(AMEDIAMETRICS_PROP_FRAMECOUNT, (int32_t)mFrameCount)
9603 /*
9604 .set(AMEDIAMETRICS_PROP_FLAGS, toString(flags).c_str())
9605 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELMASK,
9606 (int32_t)mHapticChannelMask)
9607 .set(AMEDIAMETRICS_PROP_PREFIX_HAPTIC AMEDIAMETRICS_PROP_CHANNELCOUNT,
9608 (int32_t)mHapticChannelCount)
9609 */
9610 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_ENCODING,
9611 formatToString(mHALFormat).c_str())
9612 .set(AMEDIAMETRICS_PROP_PREFIX_HAL AMEDIAMETRICS_PROP_FRAMECOUNT,
9613 (int32_t)mFrameCount) // sic - added HAL
9614 .record();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009615}
9616
9617bool AudioFlinger::MmapThread::threadLoop()
9618{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009619 checkSilentMode_l();
9620
9621 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
9622
9623 while (!exitPending())
9624 {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009625 Vector< sp<EffectChain> > effectChains;
9626
Andy Hung13850be2019-03-14 11:33:09 -07009627 { // under Thread lock
9628 Mutex::Autolock _l(mLock);
9629
Eric Laurent6acd1d42017-01-04 14:23:29 -08009630 if (mSignalPending) {
9631 // A signal was raised while we were unlocked
9632 mSignalPending = false;
9633 } else {
9634 if (mConfigEvents.isEmpty()) {
9635 // we're about to wait, flush the binder command buffer
9636 IPCThreadState::self()->flushCommands();
9637
9638 if (exitPending()) {
9639 break;
9640 }
9641
Eric Laurent6acd1d42017-01-04 14:23:29 -08009642 // wait until we have something to do...
9643 ALOGV("%s going to sleep", myName.string());
9644 mWaitWorkCV.wait(mLock);
9645 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08009646
9647 checkSilentMode_l();
9648
9649 continue;
9650 }
9651 }
9652
9653 processConfigEvents_l();
9654
9655 processVolume_l();
9656
9657 checkInvalidTracks_l();
9658
9659 mActiveTracks.updatePowerState(this);
9660
Kevin Rocard069c2712018-03-29 19:09:14 -07009661 updateMetadata_l();
9662
Eric Laurent6acd1d42017-01-04 14:23:29 -08009663 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -07009664 } // release Thread lock
9665
Eric Laurent6acd1d42017-01-04 14:23:29 -08009666 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -07009667 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -08009668 }
Andy Hung13850be2019-03-14 11:33:09 -07009669
9670 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08009671 unlockEffectChains(effectChains);
9672 // Effect chains will be actually deleted here if they were removed from
9673 // mEffectChains list during mixing or effects processing
9674 }
9675
9676 threadLoop_exit();
9677
9678 if (!mStandby) {
9679 threadLoop_standby();
9680 mStandby = true;
9681 }
9682
Eric Laurent6acd1d42017-01-04 14:23:29 -08009683 ALOGV("Thread %p type %d exiting", this, mType);
9684 return false;
9685}
9686
9687// checkForNewParameter_l() must be called with ThreadBase::mLock held
9688bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
9689 status_t& status)
9690{
9691 AudioParameter param = AudioParameter(keyValuePair);
9692 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07009693 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009694 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabinc52b1ff2019-10-31 17:20:42 -07009695 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -08009696 }
Eric Laurente6e9a482017-07-25 19:26:02 -07009697 if (sendToHal) {
9698 status = mHalStream->setParameters(keyValuePair);
9699 } else {
9700 status = NO_ERROR;
9701 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009702
9703 return false;
9704}
9705
9706String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
9707{
9708 Mutex::Autolock _l(mLock);
9709 String8 out_s8;
9710 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
9711 return out_s8;
9712 }
9713 return String8();
9714}
9715
Mikhail Naganov88536df2021-07-26 17:30:29 -07009716void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event_t event, pid_t pid,
Eric Laurent09f1ed22019-04-24 17:45:17 -07009717 audio_port_handle_t portId __unused) {
Mikhail Naganov88536df2021-07-26 17:30:29 -07009718 sp<AudioIoDescriptor> desc;
9719 bool isInput = false;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009720 switch (event) {
9721 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009722 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009723 case AUDIO_INPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009724 isInput = true;
9725 FALLTHROUGH_INTENDED;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009726 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07009727 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08009728 case AUDIO_OUTPUT_CONFIG_CHANGED:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009729 desc = sp<AudioIoDescriptor>::make(mId, mPatch, isInput,
9730 mSampleRate, mFormat, mChannelMask, mFrameCount, mFrameCount);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009731 break;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009732 case AUDIO_INPUT_CLOSED:
9733 case AUDIO_OUTPUT_CLOSED:
9734 default:
Mikhail Naganov88536df2021-07-26 17:30:29 -07009735 desc = sp<AudioIoDescriptor>::make(mId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009736 break;
9737 }
9738 mAudioFlinger->ioConfigChanged(event, desc, pid);
9739}
9740
9741status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
9742 audio_patch_handle_t *handle)
9743{
9744 status_t status = NO_ERROR;
9745
9746 // store new device and send to effects
9747 audio_devices_t type = AUDIO_DEVICE_NONE;
9748 audio_port_handle_t deviceId;
jiabinc52b1ff2019-10-31 17:20:42 -07009749 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
9750 AudioDeviceTypeAddr sourceDeviceTypeAddr;
9751 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009752 if (isOutput()) {
9753 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabinc52b1ff2019-10-31 17:20:42 -07009754 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
9755 && !mAudioHwDev->supportsAudioPatches(),
9756 "Enumerated device type(%#x) must not be used "
9757 "as it does not support audio patches",
9758 patch->sinks[i].ext.device.type);
Mikhail Naganov55773032020-10-01 15:08:13 -07009759 type = static_cast<audio_devices_t>(type | patch->sinks[i].ext.device.type);
jiabinc52b1ff2019-10-31 17:20:42 -07009760 sinkDeviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
9761 patch->sinks[i].ext.device.address));
Eric Laurent6acd1d42017-01-04 14:23:29 -08009762 }
9763 deviceId = patch->sinks[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009764 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009765 } else {
9766 type = patch->sources[0].ext.device.type;
9767 deviceId = patch->sources[0].id;
jiabinc52b1ff2019-10-31 17:20:42 -07009768 numDevices = mPatch.num_sources;
9769 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
jiabin0a488932020-08-07 17:32:40 -07009770 sourceDeviceTypeAddr.setAddress(patch->sources[0].ext.device.address);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009771 }
9772
9773 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabin8f278ee2019-11-11 12:16:27 -08009774 if (isOutput()) {
9775 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
9776 } else {
9777 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
9778 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009779 }
9780
jiabinc52b1ff2019-10-31 17:20:42 -07009781 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009782 // store new source and send to effects
9783 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
9784 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
9785 for (size_t i = 0; i < mEffectChains.size(); i++) {
9786 mEffectChains[i]->setAudioSource_l(mAudioSource);
9787 }
9788 }
9789 }
9790
9791 if (mAudioHwDev->supportsAudioPatches()) {
9792 status = mHalDevice->createAudioPatch(patch->num_sources,
9793 patch->sources,
9794 patch->num_sinks,
9795 patch->sinks,
9796 handle);
9797 } else {
9798 char *address;
9799 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
9800 //FIXME: we only support address on first sink with HAL version < 3.0
9801 address = audio_device_address_to_parameter(
9802 patch->sinks[0].ext.device.type,
9803 patch->sinks[0].ext.device.address);
9804 } else {
9805 address = (char *)calloc(1, 1);
9806 }
9807 AudioParameter param = AudioParameter(String8(address));
9808 free(address);
9809 param.addInt(String8(AudioParameter::keyRouting), (int)type);
9810 if (!isOutput()) {
9811 param.addInt(String8(AudioParameter::keyInputSource),
9812 (int)patch->sinks[0].ext.mix.usecase.source);
9813 }
9814 status = mHalStream->setParameters(param.toString());
9815 *handle = AUDIO_PATCH_HANDLE_NONE;
9816 }
9817
jiabinc52b1ff2019-10-31 17:20:42 -07009818 if (numDevices == 0 || mDeviceId != deviceId) {
9819 if (isOutput()) {
9820 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
9821 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
jiabin0a957d32020-04-29 10:56:20 -07009822 checkSilentMode_l();
jiabinc52b1ff2019-10-31 17:20:42 -07009823 } else {
9824 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
9825 mInDeviceTypeAddr = sourceDeviceTypeAddr;
9826 }
Phil Burk7f6b40d2017-02-09 13:18:38 -08009827 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009828 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009829 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08009830 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07009831 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009832 }
jiabinc52b1ff2019-10-31 17:20:42 -07009833 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009834 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009835 }
9836 return status;
9837}
9838
9839status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
9840{
9841 status_t status = NO_ERROR;
9842
jiabinc52b1ff2019-10-31 17:20:42 -07009843 mPatch = audio_patch{};
9844 mOutDeviceTypeAddrs.clear();
9845 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009846
9847 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
9848 supportsAudioPatches : false;
9849
9850 if (supportsAudioPatches) {
9851 status = mHalDevice->releaseAudioPatch(handle);
9852 } else {
9853 AudioParameter param;
9854 param.addInt(String8(AudioParameter::keyRouting), 0);
9855 status = mHalStream->setParameters(param.toString());
9856 }
9857 return status;
9858}
9859
Mikhail Naganovdc769682018-05-04 15:34:08 -07009860void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009861{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009862 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009863 if (isOutput()) {
9864 config->role = AUDIO_PORT_ROLE_SOURCE;
9865 config->ext.mix.hw_module = mAudioHwDev->handle();
9866 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
9867 } else {
9868 config->role = AUDIO_PORT_ROLE_SINK;
9869 config->ext.mix.hw_module = mAudioHwDev->handle();
9870 config->ext.mix.usecase.source = mAudioSource;
9871 }
9872}
9873
9874status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
9875{
9876 audio_session_t session = chain->sessionId();
9877
9878 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
9879 // Attach all tracks with same session ID to this chain.
9880 // indicate all active tracks in the chain
9881 for (const sp<MmapTrack> &track : mActiveTracks) {
9882 if (session == track->sessionId()) {
9883 chain->incTrackCnt();
9884 chain->incActiveTrackCnt();
9885 }
9886 }
9887
9888 chain->setThread(this);
9889 chain->setInBuffer(nullptr);
9890 chain->setOutBuffer(nullptr);
9891 chain->syncHalEffectsState();
9892
9893 mEffectChains.add(chain);
9894 checkSuspendOnAddEffectChain_l(chain);
9895 return NO_ERROR;
9896}
9897
9898size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
9899{
9900 audio_session_t session = chain->sessionId();
9901
9902 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
9903
9904 for (size_t i = 0; i < mEffectChains.size(); i++) {
9905 if (chain == mEffectChains[i]) {
9906 mEffectChains.removeAt(i);
9907 // detach all active tracks from the chain
9908 // detach all tracks with same session ID from this chain
9909 for (const sp<MmapTrack> &track : mActiveTracks) {
9910 if (session == track->sessionId()) {
9911 chain->decActiveTrackCnt();
9912 chain->decTrackCnt();
9913 }
9914 }
9915 break;
9916 }
9917 }
9918 return mEffectChains.size();
9919}
9920
Eric Laurent6acd1d42017-01-04 14:23:29 -08009921void AudioFlinger::MmapThread::threadLoop_standby()
9922{
9923 mHalStream->standby();
9924}
9925
9926void AudioFlinger::MmapThread::threadLoop_exit()
9927{
Phil Burk7dce7282017-09-27 13:51:41 -07009928 // Do not call callback->onTearDown() because it is redundant for thread exit
9929 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08009930}
9931
9932status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
9933{
9934 return BAD_VALUE;
9935}
9936
9937bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
9938{
9939 return false;
9940}
9941
9942status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
9943 const effect_descriptor_t *desc, audio_session_t sessionId)
9944{
9945 // No global effect sessions on mmap threads
Eric Laurent3f75a5b2019-11-12 15:55:51 -08009946 if (audio_is_global_session(sessionId)) {
9947 ALOGW("checkEffectCompatibility_l(): global effect %s on MMAP thread %s",
Eric Laurent6acd1d42017-01-04 14:23:29 -08009948 desc->name, mThreadName);
9949 return BAD_VALUE;
9950 }
9951
9952 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
9953 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
9954 desc->name);
9955 return BAD_VALUE;
9956 }
9957 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08009958 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
9959 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009960 return BAD_VALUE;
9961 }
9962
9963 // Only allow effects without processing load or latency
9964 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
9965 return BAD_VALUE;
9966 }
9967
jiabineb3bda02020-06-30 14:07:03 -07009968 if (EffectModule::isHapticGenerator(&desc->type)) {
9969 ALOGE("%s(): HapticGenerator is not supported for MmapThread", __func__);
9970 return BAD_VALUE;
9971 }
9972
Eric Laurent6acd1d42017-01-04 14:23:29 -08009973 return NO_ERROR;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009974}
9975
9976void AudioFlinger::MmapThread::checkInvalidTracks_l()
9977{
9978 for (const sp<MmapTrack> &track : mActiveTracks) {
9979 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009980 sp<MmapStreamCallback> callback = mCallback.promote();
9981 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009982 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07009983 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07009984 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07009985 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9986 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
9987 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009988 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009989 }
9990 }
9991}
9992
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009993void AudioFlinger::MmapThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009994{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009995 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
9996 mAttr.content_type, mAttr.usage, mAttr.source);
9997 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -07009998 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009999 dprintf(fd, " No active clients\n");
10000 }
10001}
10002
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010003void AudioFlinger::MmapThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010004{
Eric Laurent6acd1d42017-01-04 14:23:29 -080010005 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -080010006 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010007 dprintf(fd, " %zu Tracks\n", numtracks);
10008 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -080010009 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010010 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -070010011 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010012 for (size_t i = 0; i < numtracks ; ++i) {
10013 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -070010014 result.append(prefix);
10015 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010016 }
10017 } else {
10018 dprintf(fd, "\n");
10019 }
10020 write(fd, result.string(), result.size());
10021}
10022
10023AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
10024 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010025 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010026 : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady, true /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010027 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010028 mStreamVolume(1.0),
10029 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -070010030 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010031{
10032 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
10033 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
10034 mMasterVolume = audioFlinger->masterVolume_l();
10035 mMasterMute = audioFlinger->masterMute_l();
10036 if (mAudioHwDev) {
10037 if (mAudioHwDev->canSetMasterVolume()) {
10038 mMasterVolume = 1.0;
10039 }
10040
10041 if (mAudioHwDev->canSetMasterMute()) {
10042 mMasterMute = false;
10043 }
10044 }
10045}
10046
10047void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
10048 audio_stream_type_t streamType,
10049 audio_session_t sessionId,
10050 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010051 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -080010052 audio_port_handle_t portId)
10053{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -070010054 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010055 mStreamType = streamType;
10056}
10057
10058AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
10059{
10060 Mutex::Autolock _l(mLock);
10061 AudioStreamOut *output = mOutput;
10062 mOutput = NULL;
10063 return output;
10064}
10065
10066void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
10067{
10068 Mutex::Autolock _l(mLock);
10069 // Don't apply master volume in SW if our HAL can do it for us.
10070 if (mAudioHwDev &&
10071 mAudioHwDev->canSetMasterVolume()) {
10072 mMasterVolume = 1.0;
10073 } else {
10074 mMasterVolume = value;
10075 }
10076}
10077
10078void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
10079{
10080 Mutex::Autolock _l(mLock);
10081 // Don't apply master mute in SW if our HAL can do it for us.
10082 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
10083 mMasterMute = false;
10084 } else {
10085 mMasterMute = muted;
10086 }
10087}
10088
10089void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
10090{
10091 Mutex::Autolock _l(mLock);
10092 if (stream == mStreamType) {
10093 mStreamVolume = value;
10094 broadcast_l();
10095 }
10096}
10097
10098float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
10099{
10100 Mutex::Autolock _l(mLock);
10101 if (stream == mStreamType) {
10102 return mStreamVolume;
10103 }
10104 return 0.0f;
10105}
10106
10107void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
10108{
10109 Mutex::Autolock _l(mLock);
10110 if (stream == mStreamType) {
10111 mStreamMute= muted;
10112 broadcast_l();
10113 }
10114}
10115
10116void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
10117{
10118 Mutex::Autolock _l(mLock);
10119 if (streamType == mStreamType) {
10120 for (const sp<MmapTrack> &track : mActiveTracks) {
10121 track->invalidate();
10122 }
10123 broadcast_l();
10124 }
10125}
10126
10127void AudioFlinger::MmapPlaybackThread::processVolume_l()
10128{
10129 float volume;
10130
10131 if (mMasterMute || mStreamMute) {
10132 volume = 0;
10133 } else {
10134 volume = mMasterVolume * mStreamVolume;
10135 }
10136
10137 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -080010138
10139 // Convert volumes from float to 8.24
10140 uint32_t vol = (uint32_t)(volume * (1 << 24));
10141
10142 // Delegate volume control to effect in track effect chain if needed
10143 // only one effect chain can be present on DirectOutputThread, so if
10144 // there is one, the track is connected to it
10145 if (!mEffectChains.isEmpty()) {
10146 mEffectChains[0]->setVolume_l(&vol, &vol);
10147 volume = (float)vol / (1 << 24);
10148 }
Eric Laurentdff774a2017-04-21 15:29:38 -070010149 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -070010150 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
10151 mHalVolFloat = volume; // HW volume control worked, so update value.
10152 mNoCallbackWarningCount = 0;
10153 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -070010154 sp<MmapStreamCallback> callback = mCallback.promote();
10155 if (callback != 0) {
10156 int channelCount;
10157 if (isOutput()) {
10158 channelCount = audio_channel_count_from_out_mask(mChannelMask);
10159 } else {
10160 channelCount = audio_channel_count_from_in_mask(mChannelMask);
10161 }
10162 Vector<float> values;
10163 for (int i = 0; i < channelCount; i++) {
10164 values.add(volume);
10165 }
Phil Burk56ecf3e2018-03-12 15:38:17 -070010166 mHalVolFloat = volume; // SW volume control worked, so update value.
10167 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -070010168 mLock.unlock();
10169 callback->onVolumeChanged(mChannelMask, values);
10170 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -080010171 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -070010172 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10173 ALOGW("Could not set MMAP stream volume: no volume callback!");
10174 mNoCallbackWarningCount++;
10175 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010176 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010177 }
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010178 for (const sp<MmapTrack> &track : mActiveTracks) {
10179 track->setMetadataHasChanged();
10180 }
Eric Laurent6acd1d42017-01-04 14:23:29 -080010181 }
10182}
10183
Kevin Rocard069c2712018-03-29 19:09:14 -070010184void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
10185{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010186 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10187 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010188 }
10189 StreamOutHalInterface::SourceMetadata metadata;
10190 for (const sp<MmapTrack> &track : mActiveTracks) {
10191 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010192 playback_track_metadata_v7_t trackMetadata;
10193 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010194 .usage = track->attributes().usage,
10195 .content_type = track->attributes().content_type,
10196 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
Eric Laurent94579172020-11-20 18:41:04 +010010197 };
10198 trackMetadata.channel_mask = track->channelMask(),
10199 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10200 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010201 }
10202 mOutput->stream->updateSourceMetadata(metadata);
10203}
10204
Eric Laurent6acd1d42017-01-04 14:23:29 -080010205void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
10206{
10207 if (!mMasterMute) {
10208 char value[PROPERTY_VALUE_MAX];
10209 if (property_get("ro.audio.silent", value, "0") > 0) {
10210 char *endptr;
10211 unsigned long ul = strtoul(value, &endptr, 0);
10212 if (*endptr == '\0' && ul != 0) {
10213 ALOGD("Silence is golden");
10214 // The setprop command will not allow a property to be changed after
10215 // the first time it is set, so we don't have to worry about un-muting.
10216 setMasterMute_l(true);
10217 }
10218 }
10219 }
10220}
10221
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010222void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
10223{
10224 MmapThread::toAudioPortConfig(config);
10225 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
10226 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10227 config->flags.output = mOutput->flags;
10228 }
10229}
10230
jiabinb7d8c5a2020-08-26 17:24:52 -070010231status_t AudioFlinger::MmapPlaybackThread::getExternalPosition(uint64_t *position,
10232 int64_t *timeNanos)
10233{
10234 if (mOutput == nullptr) {
10235 return NO_INIT;
10236 }
10237 struct timespec timestamp;
10238 status_t status = mOutput->getPresentationPosition(position, &timestamp);
10239 if (status == NO_ERROR) {
10240 *timeNanos = timestamp.tv_sec * NANOS_PER_SECOND + timestamp.tv_nsec;
10241 }
10242 return status;
10243}
10244
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010245void AudioFlinger::MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -080010246{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -070010247 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010248
Glenn Kastend3bb6452016-12-05 18:14:37 -080010249 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
10250 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -080010251 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
10252}
10253
10254AudioFlinger::MmapCaptureThread::MmapCaptureThread(
10255 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabinc52b1ff2019-10-31 17:20:42 -070010256 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
Andy Hungcf10d742020-04-28 15:38:24 -070010257 : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady, false /* isOut */),
Eric Laurent6acd1d42017-01-04 14:23:29 -080010258 mInput(input)
10259{
10260 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
10261 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
10262}
10263
Eric Laurent331679c2018-04-16 17:03:16 -070010264status_t AudioFlinger::MmapCaptureThread::exitStandby()
10265{
Phil Burkf054fc32018-12-06 09:45:59 -080010266 {
10267 // mInput might have been cleared by clearInput()
10268 Mutex::Autolock _l(mLock);
10269 if (mInput != nullptr && mInput->stream != nullptr) {
10270 mInput->stream->setGain(1.0f);
10271 }
10272 }
Eric Laurent331679c2018-04-16 17:03:16 -070010273 return MmapThread::exitStandby();
10274}
10275
Eric Laurent6acd1d42017-01-04 14:23:29 -080010276AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
10277{
10278 Mutex::Autolock _l(mLock);
10279 AudioStreamIn *input = mInput;
10280 mInput = NULL;
10281 return input;
10282}
Kevin Rocard069c2712018-03-29 19:09:14 -070010283
Eric Laurent331679c2018-04-16 17:03:16 -070010284
10285void AudioFlinger::MmapCaptureThread::processVolume_l()
10286{
10287 bool changed = false;
10288 bool silenced = false;
10289
10290 sp<MmapStreamCallback> callback = mCallback.promote();
10291 if (callback == 0) {
10292 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
10293 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
10294 mNoCallbackWarningCount++;
10295 }
10296 }
10297
10298 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
10299 // track is silenced and unmute otherwise
10300 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
10301 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
10302 changed = true;
10303 silenced = mActiveTracks[i]->isSilenced_l();
10304 }
10305 }
10306
10307 if (changed) {
10308 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
10309 }
10310}
10311
Kevin Rocard069c2712018-03-29 19:09:14 -070010312void AudioFlinger::MmapCaptureThread::updateMetadata_l()
10313{
Jasmine Chaeaa10e42021-05-11 10:11:14 +080010314 if (!isStreamInitialized() || !mActiveTracks.readAndClearHasChanged()) {
10315 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -070010316 }
10317 StreamInHalInterface::SinkMetadata metadata;
10318 for (const sp<MmapTrack> &track : mActiveTracks) {
10319 // No track is invalid as this is called after prepareTrack_l in the same critical section
Eric Laurent94579172020-11-20 18:41:04 +010010320 record_track_metadata_v7_t trackMetadata;
10321 trackMetadata.base = {
Kevin Rocard069c2712018-03-29 19:09:14 -070010322 .source = track->attributes().source,
10323 .gain = 1, // capture tracks do not have volumes
Eric Laurent94579172020-11-20 18:41:04 +010010324 };
10325 trackMetadata.channel_mask = track->channelMask(),
10326 strncpy(trackMetadata.tags, track->attributes().tags, AUDIO_ATTRIBUTES_TAGS_MAX_SIZE);
10327 metadata.tracks.push_back(trackMetadata);
Kevin Rocard069c2712018-03-29 19:09:14 -070010328 }
10329 mInput->stream->updateSinkMetadata(metadata);
10330}
10331
Eric Laurent5ada82e2019-08-29 17:53:54 -070010332void AudioFlinger::MmapCaptureThread::setRecordSilenced(audio_port_handle_t portId, bool silenced)
Eric Laurent331679c2018-04-16 17:03:16 -070010333{
10334 Mutex::Autolock _l(mLock);
10335 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -070010336 if (mActiveTracks[i]->portId() == portId) {
Eric Laurent331679c2018-04-16 17:03:16 -070010337 mActiveTracks[i]->setSilenced_l(silenced);
10338 broadcast_l();
10339 }
10340 }
10341}
10342
Mikhail Naganov32abc2b2018-05-24 12:57:11 -070010343void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
10344{
10345 MmapThread::toAudioPortConfig(config);
10346 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
10347 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
10348 config->flags.input = mInput->flags;
10349 }
10350}
10351
jiabinb7d8c5a2020-08-26 17:24:52 -070010352status_t AudioFlinger::MmapCaptureThread::getExternalPosition(
10353 uint64_t *position, int64_t *timeNanos)
10354{
10355 if (mInput == nullptr) {
10356 return NO_INIT;
10357 }
10358 return mInput->getCapturePosition((int64_t*)position, timeNanos);
10359}
10360
Glenn Kasten63238ef2015-03-02 15:50:29 -080010361} // namespace android