blob: b5592e302f669ec0db544f12e15d370c2fc5d592 [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>
27#include <string>
Glenn Kastenad8510a2015-02-17 16:24:07 -080028#include <linux/futex.h>
Eric Laurent81784c32012-11-19 14:55:58 -080029#include <sys/stat.h>
Glenn Kastenad8510a2015-02-17 16:24:07 -080030#include <sys/syscall.h>
Eric Laurent81784c32012-11-19 14:55:58 -080031#include <cutils/properties.h>
jiabin10d86fd2019-10-31 17:20:42 -070032#include <media/AudioContainers.h>
33#include <media/AudioDeviceTypeAddr.h>
Glenn Kasten1ab85ec2013-05-31 09:18:43 -070034#include <media/AudioParameter.h>
Andy Hungcd044842014-08-07 11:04:34 -070035#include <media/AudioResamplerPublic.h>
Andy Hung89816052017-01-11 17:08:23 -080036#include <media/RecordBufferConverter.h>
Mikhail Naganov913d06c2016-11-01 12:49:22 -070037#include <media/TypeConverter.h>
Eric Laurent81784c32012-11-19 14:55:58 -080038#include <utils/Log.h>
Alex Ray371eb972012-11-30 11:11:54 -080039#include <utils/Trace.h>
Eric Laurent81784c32012-11-19 14:55:58 -080040
41#include <private/media/AudioTrackShared.h>
Wei Jiaf2ae3e12016-10-27 17:10:59 -070042#include <private/android_filesystem_config.h>
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +010043#include <audio_utils/Balance.h>
jiabin245cdd92018-12-07 17:55:15 -080044#include <audio_utils/channels.h>
Glenn Kasten6bf707f2017-02-23 16:53:58 -080045#include <audio_utils/mono_blend.h>
Eric Laurent81784c32012-11-19 14:55:58 -080046#include <audio_utils/primitives.h>
Andy Hung98ef9782014-03-04 14:46:50 -080047#include <audio_utils/format.h>
Glenn Kastenc56f3422014-03-21 17:53:17 -070048#include <audio_utils/minifloat.h>
Hongwei Wang95e37682019-04-12 11:13:36 -070049#include <audio_utils/safe_math.h>
Mikhail Naganov9fe94012016-10-14 14:57:40 -070050#include <system/audio_effects/effect_ns.h>
51#include <system/audio_effects/effect_aec.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070052#include <system/audio.h>
Eric Laurent81784c32012-11-19 14:55:58 -080053
54// NBAIO implementations
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070055#include <media/nbaio/AudioStreamInSource.h>
Eric Laurent81784c32012-11-19 14:55:58 -080056#include <media/nbaio/AudioStreamOutSink.h>
57#include <media/nbaio/MonoPipe.h>
58#include <media/nbaio/MonoPipeReader.h>
59#include <media/nbaio/Pipe.h>
60#include <media/nbaio/PipeReader.h>
61#include <media/nbaio/SourceAudioBufferProvider.h>
Wei Jia3f273d12015-11-24 09:06:49 -080062#include <mediautils/BatteryNotifier.h>
Eric Laurent81784c32012-11-19 14:55:58 -080063
Mikhail Naganov2996f672019-04-18 12:29:59 -070064#include <audiomanager/AudioManager.h>
Eric Laurent81784c32012-11-19 14:55:58 -080065#include <powermanager/PowerManager.h>
66
Kevin Rocard7588ff42018-01-08 11:11:30 -080067#include <media/audiohal/EffectsFactoryHalInterface.h>
Kevin Rocard069c2712018-03-29 19:09:14 -070068#include <media/audiohal/StreamHalInterface.h>
Kevin Rocard7588ff42018-01-08 11:11:30 -080069
Eric Laurent81784c32012-11-19 14:55:58 -080070#include "AudioFlinger.h"
Eric Laurent81784c32012-11-19 14:55:58 -080071#include "FastMixer.h"
Glenn Kasten6dbb5e32014-05-13 10:38:42 -070072#include "FastCapture.h"
Andy Hungab7ef302018-05-15 19:35:29 -070073#include <mediautils/SchedulingPolicyService.h>
74#include <mediautils/ServiceUtilities.h>
Eric Laurent81784c32012-11-19 14:55:58 -080075
Eric Laurent81784c32012-11-19 14:55:58 -080076#ifdef ADD_BATTERY_DATA
77#include <media/IMediaPlayerService.h>
78#include <media/IMediaDeathNotifier.h>
79#endif
80
Eric Laurent81784c32012-11-19 14:55:58 -080081#ifdef DEBUG_CPU_USAGE
Eric Tan5b13ff82018-07-27 11:20:17 -070082#include <audio_utils/Statistics.h>
Eric Laurent81784c32012-11-19 14:55:58 -080083#include <cpustats/ThreadCpuUsage.h>
84#endif
85
Glenn Kastenc05b8d72016-03-24 09:48:17 -070086#include "AutoPark.h"
87
Nicolas Rouletfe1e1442017-01-30 12:02:03 -080088#include <pthread.h>
89#include "TypedLogger.h"
90
Eric Laurent81784c32012-11-19 14:55:58 -080091// ----------------------------------------------------------------------------
92
93// Note: the following macro is used for extremely verbose logging message. In
94// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
95// 0; but one side effect of this is to turn all LOGV's as well. Some messages
96// are so verbose that we want to suppress them even when we have ALOG_ASSERT
97// turned on. Do not uncomment the #def below unless you really know what you
98// are doing and want to see all of the extremely verbose messages.
99//#define VERY_VERY_VERBOSE_LOGGING
100#ifdef VERY_VERY_VERBOSE_LOGGING
101#define ALOGVV ALOGV
102#else
103#define ALOGVV(a...) do { } while(0)
104#endif
105
Andy Hung6770c6f2015-04-07 13:43:36 -0700106// TODO: Move these macro/inlines to a header file.
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700107#define max(a, b) ((a) > (b) ? (a) : (b))
Andy Hung6770c6f2015-04-07 13:43:36 -0700108template <typename T>
109static inline T min(const T& a, const T& b)
110{
111 return a < b ? a : b;
112}
Glenn Kasten49d00ad2014-07-21 11:22:03 -0700113
Eric Laurent81784c32012-11-19 14:55:58 -0800114namespace android {
115
116// retry counts for buffer fill timeout
117// 50 * ~20msecs = 1 second
118static const int8_t kMaxTrackRetries = 50;
119static const int8_t kMaxTrackStartupRetries = 50;
120// allow less retry attempts on direct output thread.
121// direct outputs can be a scarce resource in audio hardware and should
122// be released as quickly as possible.
123static const int8_t kMaxTrackRetriesDirect = 2;
Eric Laurente93cc032016-05-05 10:15:10 -0700124
Eric Laurent51716182016-02-29 18:00:56 -0800125
Eric Laurent81784c32012-11-19 14:55:58 -0800126
127// don't warn about blocked writes or record buffer overflows more often than this
128static const nsecs_t kWarningThrottleNs = seconds(5);
129
130// RecordThread loop sleep time upon application overrun or audio HAL read error
131static const int kRecordThreadSleepUs = 5000;
132
Eric Laurent10351942014-05-08 18:49:52 -0700133// maximum time to wait in sendConfigEvent_l() for a status to be received
134static const nsecs_t kConfigEventTimeoutNs = seconds(2);
Eric Laurent81784c32012-11-19 14:55:58 -0800135
136// minimum sleep time for the mixer thread loop when tracks are active but in underrun
137static const uint32_t kMinThreadSleepTimeUs = 5000;
138// maximum divider applied to the active sleep time in the mixer thread loop
139static const uint32_t kMaxThreadSleepTimeShift = 2;
140
Andy Hung09a50072014-02-27 14:30:47 -0800141// minimum normal sink buffer size, expressed in milliseconds rather than frames
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700142// FIXME This should be based on experimentally observed scheduling jitter
Andy Hung09a50072014-02-27 14:30:47 -0800143static const uint32_t kMinNormalSinkBufferSizeMs = 20;
144// maximum normal sink buffer size
145static const uint32_t kMaxNormalSinkBufferSizeMs = 24;
Eric Laurent81784c32012-11-19 14:55:58 -0800146
Glenn Kasteneb9487e2015-07-22 09:15:17 -0700147// minimum capture buffer size in milliseconds to _not_ need a fast capture thread
148// FIXME This should be based on experimentally observed scheduling jitter
149static const uint32_t kMinNormalCaptureBufferSizeMs = 12;
150
Eric Laurent972a1732013-09-04 09:42:59 -0700151// Offloaded output thread standby delay: allows track transition without going to standby
152static const nsecs_t kOffloadStandbyDelayNs = seconds(1);
153
Eric Laurent51716182016-02-29 18:00:56 -0800154// Direct output thread minimum sleep time in idle or active(underrun) state
155static const nsecs_t kDirectMinSleepTimeUs = 10000;
156
Glenn Kasten1b291842016-07-18 14:55:21 -0700157// The universal constant for ubiquitous 20ms value. The value of 20ms seems to provide a good
158// balance between power consumption and latency, and allows threads to be scheduled reliably
159// by the CFS scheduler.
160// FIXME Express other hardcoded references to 20ms with references to this constant and move
161// it appropriately.
162#define FMS_20 20
Eric Laurent51716182016-02-29 18:00:56 -0800163
Eric Laurent81784c32012-11-19 14:55:58 -0800164// Whether to use fast mixer
165static const enum {
166 FastMixer_Never, // never initialize or use: for debugging only
167 FastMixer_Always, // always initialize and use, even if not needed: for debugging only
168 // normal mixer multiplier is 1
169 FastMixer_Static, // initialize if needed, then use all the time if initialized,
170 // multiplier is calculated based on min & max normal mixer buffer size
171 FastMixer_Dynamic, // initialize if needed, then use dynamically depending on track load,
172 // multiplier is calculated based on min & max normal mixer buffer size
173 // FIXME for FastMixer_Dynamic:
174 // Supporting this option will require fixing HALs that can't handle large writes.
175 // For example, one HAL implementation returns an error from a large write,
176 // and another HAL implementation corrupts memory, possibly in the sample rate converter.
177 // We could either fix the HAL implementations, or provide a wrapper that breaks
178 // up large writes into smaller ones, and the wrapper would need to deal with scheduler.
179} kUseFastMixer = FastMixer_Static;
180
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700181// Whether to use fast capture
182static const enum {
183 FastCapture_Never, // never initialize or use: for debugging only
184 FastCapture_Always, // always initialize and use, even if not needed: for debugging only
185 FastCapture_Static, // initialize if needed, then use all the time if initialized
186} kUseFastCapture = FastCapture_Static;
187
Eric Laurent81784c32012-11-19 14:55:58 -0800188// Priorities for requestPriority
189static const int kPriorityAudioApp = 2;
190static const int kPriorityFastMixer = 3;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700191static const int kPriorityFastCapture = 3;
Eric Laurent81784c32012-11-19 14:55:58 -0800192
Glenn Kastenea38ee72016-04-18 11:08:01 -0700193// IAudioFlinger::createTrack() has an in/out parameter 'pFrameCount' for the total size of the
194// track buffer in shared memory. Zero on input means to use a default value. For fast tracks,
195// AudioFlinger derives the default from HAL buffer size and 'fast track multiplier'.
Glenn Kasten03490092014-05-27 12:30:54 -0700196
197// This is the default value, if not specified by property.
Glenn Kastenb5fed682013-12-03 09:06:43 -0800198static const int kFastTrackMultiplier = 2;
Eric Laurent81784c32012-11-19 14:55:58 -0800199
Glenn Kasten03490092014-05-27 12:30:54 -0700200// The minimum and maximum allowed values
201static const int kFastTrackMultiplierMin = 1;
202static const int kFastTrackMultiplierMax = 2;
203
204// The actual value to use, which can be specified per-device via property af.fast_track_multiplier.
205static int sFastTrackMultiplier = kFastTrackMultiplier;
206
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700207// See Thread::readOnlyHeap().
208// Initially this heap is used to allocate client buffers for "fast" AudioRecord.
209// Eventually it will be the single buffer that FastCapture writes into via HAL read(),
210// and that all "fast" AudioRecord clients read from. In either case, the size can be small.
Mikhail Naganov79a77822018-05-10 15:57:25 -0700211static const size_t kRecordThreadReadOnlyHeapSize = 0xD000;
Glenn Kastenb880f5e2014-05-07 08:43:45 -0700212
Eric Laurent81784c32012-11-19 14:55:58 -0800213// ----------------------------------------------------------------------------
214
Glenn Kasten03490092014-05-27 12:30:54 -0700215static pthread_once_t sFastTrackMultiplierOnce = PTHREAD_ONCE_INIT;
216
217static void sFastTrackMultiplierInit()
218{
219 char value[PROPERTY_VALUE_MAX];
220 if (property_get("af.fast_track_multiplier", value, NULL) > 0) {
221 char *endptr;
222 unsigned long ul = strtoul(value, &endptr, 0);
223 if (*endptr == '\0' && kFastTrackMultiplierMin <= ul && ul <= kFastTrackMultiplierMax) {
224 sFastTrackMultiplier = (int) ul;
225 }
226 }
227}
228
229// ----------------------------------------------------------------------------
230
Eric Laurent81784c32012-11-19 14:55:58 -0800231#ifdef ADD_BATTERY_DATA
232// To collect the amplifier usage
233static void addBatteryData(uint32_t params) {
234 sp<IMediaPlayerService> service = IMediaDeathNotifier::getMediaPlayerService();
235 if (service == NULL) {
236 // it already logged
237 return;
238 }
239
240 service->addBatteryData(params);
241}
242#endif
243
Andy Hung3f0c9022016-01-15 17:49:46 -0800244// Track the CLOCK_BOOTTIME versus CLOCK_MONOTONIC timebase offset
245struct {
246 // call when you acquire a partial wakelock
247 void acquire(const sp<IBinder> &wakeLockToken) {
248 pthread_mutex_lock(&mLock);
249 if (wakeLockToken.get() == nullptr) {
250 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
251 } else {
252 if (mCount == 0) {
253 adjustTimebaseOffset(&mBoottimeOffset, ExtendedTimestamp::TIMEBASE_BOOTTIME);
254 }
255 ++mCount;
256 }
257 pthread_mutex_unlock(&mLock);
258 }
259
260 // call when you release a partial wakelock.
261 void release(const sp<IBinder> &wakeLockToken) {
262 if (wakeLockToken.get() == nullptr) {
263 return;
264 }
265 pthread_mutex_lock(&mLock);
266 if (--mCount < 0) {
267 ALOGE("negative wakelock count");
268 mCount = 0;
269 }
270 pthread_mutex_unlock(&mLock);
271 }
272
273 // retrieves the boottime timebase offset from monotonic.
274 int64_t getBoottimeOffset() {
275 pthread_mutex_lock(&mLock);
276 int64_t boottimeOffset = mBoottimeOffset;
277 pthread_mutex_unlock(&mLock);
278 return boottimeOffset;
279 }
280
281 // Adjusts the timebase offset between TIMEBASE_MONOTONIC
282 // and the selected timebase.
283 // Currently only TIMEBASE_BOOTTIME is allowed.
284 //
285 // This only needs to be called upon acquiring the first partial wakelock
286 // after all other partial wakelocks are released.
287 //
288 // We do an empirical measurement of the offset rather than parsing
289 // /proc/timer_list since the latter is not a formal kernel ABI.
290 static void adjustTimebaseOffset(int64_t *offset, ExtendedTimestamp::Timebase timebase) {
291 int clockbase;
292 switch (timebase) {
293 case ExtendedTimestamp::TIMEBASE_BOOTTIME:
294 clockbase = SYSTEM_TIME_BOOTTIME;
295 break;
296 default:
297 LOG_ALWAYS_FATAL("invalid timebase %d", timebase);
298 break;
299 }
300 // try three times to get the clock offset, choose the one
301 // with the minimum gap in measurements.
302 const int tries = 3;
303 nsecs_t bestGap, measured;
304 for (int i = 0; i < tries; ++i) {
305 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
306 const nsecs_t tbase = systemTime(clockbase);
307 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
308 const nsecs_t gap = tmono2 - tmono;
309 if (i == 0 || gap < bestGap) {
310 bestGap = gap;
311 measured = tbase - ((tmono + tmono2) >> 1);
312 }
313 }
314
315 // to avoid micro-adjusting, we don't change the timebase
316 // unless it is significantly different.
317 //
318 // Assumption: It probably takes more than toleranceNs to
319 // suspend and resume the device.
320 static int64_t toleranceNs = 10000; // 10 us
321 if (llabs(*offset - measured) > toleranceNs) {
322 ALOGV("Adjusting timebase offset old: %lld new: %lld",
323 (long long)*offset, (long long)measured);
324 *offset = measured;
325 }
326 }
327
328 pthread_mutex_t mLock;
329 int32_t mCount;
330 int64_t mBoottimeOffset;
331} gBoottime = { PTHREAD_MUTEX_INITIALIZER, 0, 0 }; // static, so use POD initialization
Eric Laurent81784c32012-11-19 14:55:58 -0800332
333// ----------------------------------------------------------------------------
334// CPU Stats
335// ----------------------------------------------------------------------------
336
337class CpuStats {
338public:
339 CpuStats();
340 void sample(const String8 &title);
341#ifdef DEBUG_CPU_USAGE
342private:
343 ThreadCpuUsage mCpuUsage; // instantaneous thread CPU usage in wall clock ns
Andy Hung16698b82018-08-01 10:48:38 -0700344 audio_utils::Statistics<double> mWcStats; // statistics on thread CPU usage in wall clock ns
Eric Laurent81784c32012-11-19 14:55:58 -0800345
Andy Hung16698b82018-08-01 10:48:38 -0700346 audio_utils::Statistics<double> mHzStats; // statistics on thread CPU usage in cycles
Eric Laurent81784c32012-11-19 14:55:58 -0800347
348 int mCpuNum; // thread's current CPU number
349 int mCpukHz; // frequency of thread's current CPU in kHz
350#endif
351};
352
353CpuStats::CpuStats()
354#ifdef DEBUG_CPU_USAGE
355 : mCpuNum(-1), mCpukHz(-1)
356#endif
357{
358}
359
Glenn Kasten0f11b512014-01-31 16:18:54 -0800360void CpuStats::sample(const String8 &title
361#ifndef DEBUG_CPU_USAGE
362 __unused
363#endif
364 ) {
Eric Laurent81784c32012-11-19 14:55:58 -0800365#ifdef DEBUG_CPU_USAGE
366 // get current thread's delta CPU time in wall clock ns
367 double wcNs;
368 bool valid = mCpuUsage.sampleAndEnable(wcNs);
369
370 // record sample for wall clock statistics
371 if (valid) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700372 mWcStats.add(wcNs);
Eric Laurent81784c32012-11-19 14:55:58 -0800373 }
374
375 // get the current CPU number
376 int cpuNum = sched_getcpu();
377
378 // get the current CPU frequency in kHz
379 int cpukHz = mCpuUsage.getCpukHz(cpuNum);
380
381 // check if either CPU number or frequency changed
382 if (cpuNum != mCpuNum || cpukHz != mCpukHz) {
383 mCpuNum = cpuNum;
384 mCpukHz = cpukHz;
385 // ignore sample for purposes of cycles
386 valid = false;
387 }
388
389 // if no change in CPU number or frequency, then record sample for cycle statistics
390 if (valid && mCpukHz > 0) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700391 const double cycles = wcNs * cpukHz * 0.000001;
392 mHzStats.add(cycles);
Eric Laurent81784c32012-11-19 14:55:58 -0800393 }
394
Eric Tan5b13ff82018-07-27 11:20:17 -0700395 const unsigned n = mWcStats.getN();
Eric Laurent81784c32012-11-19 14:55:58 -0800396 // mCpuUsage.elapsed() is expensive, so don't call it every loop
397 if ((n & 127) == 1) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700398 const long long elapsed = mCpuUsage.elapsed();
Eric Laurent81784c32012-11-19 14:55:58 -0800399 if (elapsed >= DEBUG_CPU_USAGE * 1000000000LL) {
Eric Tan5b13ff82018-07-27 11:20:17 -0700400 const double perLoop = elapsed / (double) n;
401 const double perLoop100 = perLoop * 0.01;
402 const double perLoop1k = perLoop * 0.001;
403 const double mean = mWcStats.getMean();
404 const double stddev = mWcStats.getStdDev();
405 const double minimum = mWcStats.getMin();
406 const double maximum = mWcStats.getMax();
407 const double meanCycles = mHzStats.getMean();
408 const double stddevCycles = mHzStats.getStdDev();
409 const double minCycles = mHzStats.getMin();
410 const double maxCycles = mHzStats.getMax();
Eric Laurent81784c32012-11-19 14:55:58 -0800411 mCpuUsage.resetElapsed();
412 mWcStats.reset();
413 mHzStats.reset();
414 ALOGD("CPU usage for %s over past %.1f secs\n"
415 " (%u mixer loops at %.1f mean ms per loop):\n"
416 " us per mix loop: mean=%.0f stddev=%.0f min=%.0f max=%.0f\n"
417 " %% of wall: mean=%.1f stddev=%.1f min=%.1f max=%.1f\n"
418 " MHz: mean=%.1f, stddev=%.1f, min=%.1f max=%.1f",
419 title.string(),
420 elapsed * .000000001, n, perLoop * .000001,
421 mean * .001,
422 stddev * .001,
423 minimum * .001,
424 maximum * .001,
425 mean / perLoop100,
426 stddev / perLoop100,
427 minimum / perLoop100,
428 maximum / perLoop100,
429 meanCycles / perLoop1k,
430 stddevCycles / perLoop1k,
431 minCycles / perLoop1k,
432 maxCycles / perLoop1k);
433
434 }
435 }
436#endif
437};
438
439// ----------------------------------------------------------------------------
440// ThreadBase
441// ----------------------------------------------------------------------------
442
Glenn Kasten97b7b752014-09-28 13:04:24 -0700443// static
444const char *AudioFlinger::ThreadBase::threadTypeToString(AudioFlinger::ThreadBase::type_t type)
445{
446 switch (type) {
447 case MIXER:
448 return "MIXER";
449 case DIRECT:
450 return "DIRECT";
451 case DUPLICATING:
452 return "DUPLICATING";
453 case RECORD:
454 return "RECORD";
455 case OFFLOAD:
456 return "OFFLOAD";
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800457 case MMAP:
458 return "MMAP";
Glenn Kasten97b7b752014-09-28 13:04:24 -0700459 default:
460 return "unknown";
461 }
462}
463
Eric Laurent81784c32012-11-19 14:55:58 -0800464AudioFlinger::ThreadBase::ThreadBase(const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabin10d86fd2019-10-31 17:20:42 -0700465 type_t type, bool systemReady)
Eric Laurent81784c32012-11-19 14:55:58 -0800466 : Thread(false /*canCallJava*/),
467 mType(type),
Glenn Kasten9b58f632013-07-16 11:37:48 -0700468 mAudioFlinger(audioFlinger),
Glenn Kasten70949c42013-08-06 07:40:12 -0700469 // mSampleRate, mFrameCount, mChannelMask, mChannelCount, mFrameSize, mFormat, mBufferSize
Glenn Kastendeca2ae2014-02-07 10:25:56 -0800470 // are set by PlaybackThread::readOutputParameters_l() or
471 // RecordThread::readInputParameters_l()
Eric Laurentfd477972013-10-25 18:10:40 -0700472 //FIXME: mStandby should be true here. Is this some kind of hack?
jiabin10d86fd2019-10-31 17:20:42 -0700473 mStandby(false),
Eric Laurent7c1ec5f2015-07-09 14:52:47 -0700474 mAudioSource(AUDIO_SOURCE_DEFAULT), mId(id),
Eric Laurent81784c32012-11-19 14:55:58 -0800475 // mName will be set by concrete (non-virtual) subclass
Eric Laurent72e3f392015-05-20 14:43:50 -0700476 mDeathRecipient(new PMDeathRecipient(this)),
Eric Laurent6acd1d42017-01-04 14:23:29 -0800477 mSystemReady(systemReady),
478 mSignalPending(false)
Eric Laurent81784c32012-11-19 14:55:58 -0800479{
Eric Laurent296fb132015-05-01 11:38:42 -0700480 memset(&mPatch, 0, sizeof(struct audio_patch));
Eric Laurent81784c32012-11-19 14:55:58 -0800481}
482
483AudioFlinger::ThreadBase::~ThreadBase()
484{
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700485 // mConfigEvents should be empty, but just in case it isn't, free the memory it owns
Glenn Kastenc6ae3c82013-07-17 09:08:51 -0700486 mConfigEvents.clear();
487
Eric Laurent81784c32012-11-19 14:55:58 -0800488 // do not lock the mutex in destructor
489 releaseWakeLock_l();
490 if (mPowerManager != 0) {
Marco Nelissen06b46062014-11-14 07:58:25 -0800491 sp<IBinder> binder = IInterface::asBinder(mPowerManager);
Eric Laurent81784c32012-11-19 14:55:58 -0800492 binder->unlinkToDeath(mDeathRecipient);
493 }
Andy Hungd0979812019-02-21 15:51:44 -0800494
495 sendStatistics(true /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -0800496}
497
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700498status_t AudioFlinger::ThreadBase::readyToRun()
499{
500 status_t status = initCheck();
501 if (status == NO_ERROR) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800502 ALOGI("AudioFlinger's thread %p tid=%d ready to run", this, getTid());
Glenn Kastencf04c2c2013-08-06 07:41:16 -0700503 } else {
504 ALOGE("No working audio driver found.");
505 }
506 return status;
507}
508
Eric Laurent81784c32012-11-19 14:55:58 -0800509void AudioFlinger::ThreadBase::exit()
510{
511 ALOGV("ThreadBase::exit");
512 // do any cleanup required for exit to succeed
513 preExit();
514 {
515 // This lock prevents the following race in thread (uniprocessor for illustration):
516 // if (!exitPending()) {
517 // // context switch from here to exit()
518 // // exit() calls requestExit(), what exitPending() observes
519 // // exit() calls signal(), which is dropped since no waiters
520 // // context switch back from exit() to here
521 // mWaitWorkCV.wait(...);
522 // // now thread is hung
523 // }
524 AutoMutex lock(mLock);
525 requestExit();
526 mWaitWorkCV.broadcast();
527 }
528 // When Thread::requestExitAndWait is made virtual and this method is renamed to
529 // "virtual status_t requestExitAndWait()", replace by "return Thread::requestExitAndWait();"
530 requestExitAndWait();
531}
532
533status_t AudioFlinger::ThreadBase::setParameters(const String8& keyValuePairs)
534{
Eric Laurent81784c32012-11-19 14:55:58 -0800535 ALOGV("ThreadBase::setParameters() %s", keyValuePairs.string());
536 Mutex::Autolock _l(mLock);
537
Eric Laurent10351942014-05-08 18:49:52 -0700538 return sendSetParameterConfigEvent_l(keyValuePairs);
539}
540
541// sendConfigEvent_l() must be called with ThreadBase::mLock held
542// Can temporarily release the lock if waiting for a reply from processConfigEvents_l().
543status_t AudioFlinger::ThreadBase::sendConfigEvent_l(sp<ConfigEvent>& event)
544{
545 status_t status = NO_ERROR;
546
Eric Laurent72e3f392015-05-20 14:43:50 -0700547 if (event->mRequiresSystemReady && !mSystemReady) {
548 event->mWaitStatus = false;
549 mPendingConfigEvents.add(event);
550 return status;
551 }
Eric Laurent10351942014-05-08 18:49:52 -0700552 mConfigEvents.add(event);
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700553 ALOGV("sendConfigEvent_l() num events %zu event %d", mConfigEvents.size(), event->mType);
Eric Laurent81784c32012-11-19 14:55:58 -0800554 mWaitWorkCV.signal();
Eric Laurent10351942014-05-08 18:49:52 -0700555 mLock.unlock();
556 {
557 Mutex::Autolock _l(event->mLock);
558 while (event->mWaitStatus) {
559 if (event->mCond.waitRelative(event->mLock, kConfigEventTimeoutNs) != NO_ERROR) {
560 event->mStatus = TIMED_OUT;
561 event->mWaitStatus = false;
562 }
563 }
564 status = event->mStatus;
Eric Laurent81784c32012-11-19 14:55:58 -0800565 }
Eric Laurent10351942014-05-08 18:49:52 -0700566 mLock.lock();
Eric Laurent81784c32012-11-19 14:55:58 -0800567 return status;
568}
569
Eric Laurent09f1ed22019-04-24 17:45:17 -0700570void AudioFlinger::ThreadBase::sendIoConfigEvent(audio_io_config_event event, pid_t pid,
571 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800572{
573 Mutex::Autolock _l(mLock);
Eric Laurent09f1ed22019-04-24 17:45:17 -0700574 sendIoConfigEvent_l(event, pid, portId);
Eric Laurent81784c32012-11-19 14:55:58 -0800575}
576
577// sendIoConfigEvent_l() must be called with ThreadBase::mLock held
Eric Laurent09f1ed22019-04-24 17:45:17 -0700578void AudioFlinger::ThreadBase::sendIoConfigEvent_l(audio_io_config_event event, pid_t pid,
579 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -0800580{
Andy Hungd0979812019-02-21 15:51:44 -0800581 // The audio statistics history is exponentially weighted to forget events
582 // about five or more seconds in the past. In order to have
583 // crisper statistics for mediametrics, we reset the statistics on
584 // an IoConfigEvent, to reflect different properties for a new device.
585 mIoJitterMs.reset();
586 mLatencyMs.reset();
587 mProcessTimeMs.reset();
588 mTimestampVerifier.discontinuity();
589
Eric Laurent09f1ed22019-04-24 17:45:17 -0700590 sp<ConfigEvent> configEvent = (ConfigEvent *)new IoConfigEvent(event, pid, portId);
Eric Laurent10351942014-05-08 18:49:52 -0700591 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800592}
593
Mikhail Naganov83f04272017-02-07 10:45:09 -0800594void AudioFlinger::ThreadBase::sendPrioConfigEvent(pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent72e3f392015-05-20 14:43:50 -0700595{
596 Mutex::Autolock _l(mLock);
Mikhail Naganov83f04272017-02-07 10:45:09 -0800597 sendPrioConfigEvent_l(pid, tid, prio, forApp);
Eric Laurent72e3f392015-05-20 14:43:50 -0700598}
599
Eric Laurent81784c32012-11-19 14:55:58 -0800600// sendPrioConfigEvent_l() must be called with ThreadBase::mLock held
Mikhail Naganov83f04272017-02-07 10:45:09 -0800601void AudioFlinger::ThreadBase::sendPrioConfigEvent_l(
602 pid_t pid, pid_t tid, int32_t prio, bool forApp)
Eric Laurent81784c32012-11-19 14:55:58 -0800603{
Mikhail Naganov83f04272017-02-07 10:45:09 -0800604 sp<ConfigEvent> configEvent = (ConfigEvent *)new PrioConfigEvent(pid, tid, prio, forApp);
Eric Laurent10351942014-05-08 18:49:52 -0700605 sendConfigEvent_l(configEvent);
Eric Laurent81784c32012-11-19 14:55:58 -0800606}
607
Eric Laurent10351942014-05-08 18:49:52 -0700608// sendSetParameterConfigEvent_l() must be called with ThreadBase::mLock held
609status_t AudioFlinger::ThreadBase::sendSetParameterConfigEvent_l(const String8& keyValuePair)
Eric Laurent81784c32012-11-19 14:55:58 -0800610{
Andy Hung2ddee192015-12-18 17:34:44 -0800611 sp<ConfigEvent> configEvent;
612 AudioParameter param(keyValuePair);
613 int value;
Mikhail Naganov00260b52016-10-13 12:54:24 -0700614 if (param.getInt(String8(AudioParameter::keyMonoOutput), value) == NO_ERROR) {
Andy Hung2ddee192015-12-18 17:34:44 -0800615 setMasterMono_l(value != 0);
616 if (param.size() == 1) {
617 return NO_ERROR; // should be a solo parameter - we don't pass down
618 }
Mikhail Naganov00260b52016-10-13 12:54:24 -0700619 param.remove(String8(AudioParameter::keyMonoOutput));
Andy Hung2ddee192015-12-18 17:34:44 -0800620 configEvent = new SetParameterConfigEvent(param.toString());
621 } else {
622 configEvent = new SetParameterConfigEvent(keyValuePair);
623 }
Eric Laurent10351942014-05-08 18:49:52 -0700624 return sendConfigEvent_l(configEvent);
Glenn Kastenf7773312013-08-13 16:00:42 -0700625}
626
Eric Laurent1c333e22014-05-20 10:48:17 -0700627status_t AudioFlinger::ThreadBase::sendCreateAudioPatchConfigEvent(
628 const struct audio_patch *patch,
629 audio_patch_handle_t *handle)
630{
631 Mutex::Autolock _l(mLock);
632 sp<ConfigEvent> configEvent = (ConfigEvent *)new CreateAudioPatchConfigEvent(*patch, *handle);
633 status_t status = sendConfigEvent_l(configEvent);
634 if (status == NO_ERROR) {
635 CreateAudioPatchConfigEventData *data =
636 (CreateAudioPatchConfigEventData *)configEvent->mData.get();
637 *handle = data->mHandle;
638 }
639 return status;
640}
641
642status_t AudioFlinger::ThreadBase::sendReleaseAudioPatchConfigEvent(
643 const audio_patch_handle_t handle)
644{
645 Mutex::Autolock _l(mLock);
646 sp<ConfigEvent> configEvent = (ConfigEvent *)new ReleaseAudioPatchConfigEvent(handle);
647 return sendConfigEvent_l(configEvent);
648}
649
jiabin10d86fd2019-10-31 17:20:42 -0700650status_t AudioFlinger::ThreadBase::sendUpdateOutDeviceConfigEvent(
651 const DeviceDescriptorBaseVector& outDevices)
652{
653 if (type() != RECORD) {
654 // The update out device operation is only for record thread.
655 return INVALID_OPERATION;
656 }
657 Mutex::Autolock _l(mLock);
658 sp<ConfigEvent> configEvent = (ConfigEvent *)new UpdateOutDevicesConfigEvent(outDevices);
659 return sendConfigEvent_l(configEvent);
660}
661
Eric Laurent1c333e22014-05-20 10:48:17 -0700662
Glenn Kasten2cfbf882013-08-14 13:12:11 -0700663// post condition: mConfigEvents.isEmpty()
Eric Laurent021cf962014-05-13 10:18:14 -0700664void AudioFlinger::ThreadBase::processConfigEvents_l()
Glenn Kastenf7773312013-08-13 16:00:42 -0700665{
Eric Laurent10351942014-05-08 18:49:52 -0700666 bool configChanged = false;
667
Eric Laurent81784c32012-11-19 14:55:58 -0800668 while (!mConfigEvents.isEmpty()) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700669 ALOGV("processConfigEvents_l() remaining events %zu", mConfigEvents.size());
Eric Laurent10351942014-05-08 18:49:52 -0700670 sp<ConfigEvent> event = mConfigEvents[0];
Eric Laurent81784c32012-11-19 14:55:58 -0800671 mConfigEvents.removeAt(0);
Eric Laurent10351942014-05-08 18:49:52 -0700672 switch (event->mType) {
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700673 case CFG_EVENT_PRIO: {
Eric Laurent10351942014-05-08 18:49:52 -0700674 PrioConfigEventData *data = (PrioConfigEventData *)event->mData.get();
675 // FIXME Need to understand why this has to be done asynchronously
Mikhail Naganov83f04272017-02-07 10:45:09 -0800676 int err = requestPriority(data->mPid, data->mTid, data->mPrio, data->mForApp,
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700677 true /*asynchronous*/);
678 if (err != 0) {
679 ALOGW("Policy SCHED_FIFO priority %d is unavailable for pid %d tid %d; error %d",
Eric Laurent10351942014-05-08 18:49:52 -0700680 data->mPrio, data->mPid, data->mTid, err);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700681 }
682 } break;
683 case CFG_EVENT_IO: {
Eric Laurent10351942014-05-08 18:49:52 -0700684 IoConfigEventData *data = (IoConfigEventData *)event->mData.get();
Eric Laurent09f1ed22019-04-24 17:45:17 -0700685 ioConfigChanged(data->mEvent, data->mPid, data->mPortId);
Eric Laurent10351942014-05-08 18:49:52 -0700686 } break;
687 case CFG_EVENT_SET_PARAMETER: {
688 SetParameterConfigEventData *data = (SetParameterConfigEventData *)event->mData.get();
689 if (checkForNewParameter_l(data->mKeyValuePairs, event->mStatus)) {
690 configChanged = true;
Andy Hung293558a2017-03-21 12:19:20 -0700691 mLocalLog.log("CFG_EVENT_SET_PARAMETER: (%s) configuration changed",
692 data->mKeyValuePairs.string());
Glenn Kastend5418eb2013-08-14 13:11:06 -0700693 }
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700694 } break;
Eric Laurent1c333e22014-05-20 10:48:17 -0700695 case CFG_EVENT_CREATE_AUDIO_PATCH: {
jiabin10d86fd2019-10-31 17:20:42 -0700696 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700697 CreateAudioPatchConfigEventData *data =
698 (CreateAudioPatchConfigEventData *)event->mData.get();
699 event->mStatus = createAudioPatch_l(&data->mPatch, &data->mHandle);
jiabin10d86fd2019-10-31 17:20:42 -0700700 const DeviceTypeSet newDevices = getDeviceTypes();
701 mLocalLog.log("CFG_EVENT_CREATE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
702 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
703 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -0700704 } break;
705 case CFG_EVENT_RELEASE_AUDIO_PATCH: {
jiabin10d86fd2019-10-31 17:20:42 -0700706 const DeviceTypeSet oldDevices = getDeviceTypes();
Eric Laurent1c333e22014-05-20 10:48:17 -0700707 ReleaseAudioPatchConfigEventData *data =
708 (ReleaseAudioPatchConfigEventData *)event->mData.get();
709 event->mStatus = releaseAudioPatch_l(data->mHandle);
jiabin10d86fd2019-10-31 17:20:42 -0700710 const DeviceTypeSet newDevices = getDeviceTypes();
711 mLocalLog.log("CFG_EVENT_RELEASE_AUDIO_PATCH: old device %s (%s) new device %s (%s)",
712 dumpDeviceTypes(oldDevices).c_str(), toString(oldDevices).c_str(),
713 dumpDeviceTypes(newDevices).c_str(), toString(newDevices).c_str());
714 } break;
715 case CFG_EVENT_UPDATE_OUT_DEVICE: {
716 UpdateOutDevicesConfigEventData *data =
717 (UpdateOutDevicesConfigEventData *)event->mData.get();
718 updateOutDevices(data->mOutDevices);
Eric Laurent1c333e22014-05-20 10:48:17 -0700719 } break;
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700720 default:
Eric Laurent10351942014-05-08 18:49:52 -0700721 ALOG_ASSERT(false, "processConfigEvents_l() unknown event type %d", event->mType);
Glenn Kasten3468e8a2013-08-13 16:01:22 -0700722 break;
Eric Laurent81784c32012-11-19 14:55:58 -0800723 }
Eric Laurent10351942014-05-08 18:49:52 -0700724 {
725 Mutex::Autolock _l(event->mLock);
726 if (event->mWaitStatus) {
727 event->mWaitStatus = false;
728 event->mCond.signal();
729 }
730 }
731 ALOGV_IF(mConfigEvents.isEmpty(), "processConfigEvents_l() DONE thread %p", this);
732 }
733
734 if (configChanged) {
735 cacheParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800736 }
Eric Laurent81784c32012-11-19 14:55:58 -0800737}
738
Marco Nelissenb2208842014-02-07 14:00:50 -0800739String8 channelMaskToString(audio_channel_mask_t mask, bool output) {
740 String8 s;
Glenn Kastene1635ec2015-06-08 15:46:49 -0700741 const audio_channel_representation_t representation =
742 audio_channel_mask_get_representation(mask);
Andy Hungf98ec8d2015-05-19 12:53:24 -0700743
744 switch (representation) {
jiabin245cdd92018-12-07 17:55:15 -0800745 // Travel all single bit channel mask to convert channel mask to string.
Andy Hungf98ec8d2015-05-19 12:53:24 -0700746 case AUDIO_CHANNEL_REPRESENTATION_POSITION: {
747 if (output) {
748 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT) s.append("front-left, ");
749 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT) s.append("front-right, ");
750 if (mask & AUDIO_CHANNEL_OUT_FRONT_CENTER) s.append("front-center, ");
751 if (mask & AUDIO_CHANNEL_OUT_LOW_FREQUENCY) s.append("low freq, ");
752 if (mask & AUDIO_CHANNEL_OUT_BACK_LEFT) s.append("back-left, ");
753 if (mask & AUDIO_CHANNEL_OUT_BACK_RIGHT) s.append("back-right, ");
754 if (mask & AUDIO_CHANNEL_OUT_FRONT_LEFT_OF_CENTER) s.append("front-left-of-center, ");
755 if (mask & AUDIO_CHANNEL_OUT_FRONT_RIGHT_OF_CENTER) s.append("front-right-of-center, ");
756 if (mask & AUDIO_CHANNEL_OUT_BACK_CENTER) s.append("back-center, ");
757 if (mask & AUDIO_CHANNEL_OUT_SIDE_LEFT) s.append("side-left, ");
758 if (mask & AUDIO_CHANNEL_OUT_SIDE_RIGHT) s.append("side-right, ");
759 if (mask & AUDIO_CHANNEL_OUT_TOP_CENTER) s.append("top-center ,");
760 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_LEFT) s.append("top-front-left, ");
761 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_CENTER) s.append("top-front-center, ");
762 if (mask & AUDIO_CHANNEL_OUT_TOP_FRONT_RIGHT) s.append("top-front-right, ");
763 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_LEFT) s.append("top-back-left, ");
764 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_CENTER) s.append("top-back-center, " );
765 if (mask & AUDIO_CHANNEL_OUT_TOP_BACK_RIGHT) s.append("top-back-right, " );
Mikhail Naganovc9948492018-05-10 17:25:28 -0700766 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_LEFT) s.append("top-side-left, " );
767 if (mask & AUDIO_CHANNEL_OUT_TOP_SIDE_RIGHT) s.append("top-side-right, " );
jiabin245cdd92018-12-07 17:55:15 -0800768 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_B) s.append("haptic-B, " );
769 if (mask & AUDIO_CHANNEL_OUT_HAPTIC_A) s.append("haptic-A, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700770 if (mask & ~AUDIO_CHANNEL_OUT_ALL) s.append("unknown, ");
771 } else {
772 if (mask & AUDIO_CHANNEL_IN_LEFT) s.append("left, ");
773 if (mask & AUDIO_CHANNEL_IN_RIGHT) s.append("right, ");
774 if (mask & AUDIO_CHANNEL_IN_FRONT) s.append("front, ");
775 if (mask & AUDIO_CHANNEL_IN_BACK) s.append("back, ");
776 if (mask & AUDIO_CHANNEL_IN_LEFT_PROCESSED) s.append("left-processed, ");
777 if (mask & AUDIO_CHANNEL_IN_RIGHT_PROCESSED) s.append("right-processed, ");
778 if (mask & AUDIO_CHANNEL_IN_FRONT_PROCESSED) s.append("front-processed, ");
779 if (mask & AUDIO_CHANNEL_IN_BACK_PROCESSED) s.append("back-processed, ");
780 if (mask & AUDIO_CHANNEL_IN_PRESSURE) s.append("pressure, ");
781 if (mask & AUDIO_CHANNEL_IN_X_AXIS) s.append("X, ");
782 if (mask & AUDIO_CHANNEL_IN_Y_AXIS) s.append("Y, ");
783 if (mask & AUDIO_CHANNEL_IN_Z_AXIS) s.append("Z, ");
Mikhail Naganovc9948492018-05-10 17:25:28 -0700784 if (mask & AUDIO_CHANNEL_IN_BACK_LEFT) s.append("back-left, ");
785 if (mask & AUDIO_CHANNEL_IN_BACK_RIGHT) s.append("back-right, ");
786 if (mask & AUDIO_CHANNEL_IN_CENTER) s.append("center, ");
787 if (mask & AUDIO_CHANNEL_IN_LOW_FREQUENCY) s.append("low freq, ");
788 if (mask & AUDIO_CHANNEL_IN_TOP_LEFT) s.append("top-left, " );
789 if (mask & AUDIO_CHANNEL_IN_TOP_RIGHT) s.append("top-right, " );
Andy Hungf98ec8d2015-05-19 12:53:24 -0700790 if (mask & AUDIO_CHANNEL_IN_VOICE_UPLINK) s.append("voice-uplink, ");
791 if (mask & AUDIO_CHANNEL_IN_VOICE_DNLINK) s.append("voice-dnlink, ");
792 if (mask & ~AUDIO_CHANNEL_IN_ALL) s.append("unknown, ");
793 }
794 const int len = s.length();
795 if (len > 2) {
Glenn Kasten57c4e6f2016-03-18 14:54:07 -0700796 (void) s.lockBuffer(len); // needed?
Andy Hungf98ec8d2015-05-19 12:53:24 -0700797 s.unlockBuffer(len - 2); // remove trailing ", "
798 }
799 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800800 }
Andy Hungf98ec8d2015-05-19 12:53:24 -0700801 case AUDIO_CHANNEL_REPRESENTATION_INDEX:
802 s.appendFormat("index mask, bits:%#x", audio_channel_mask_get_bits(mask));
803 return s;
804 default:
805 s.appendFormat("unknown mask, representation:%d bits:%#x",
806 representation, audio_channel_mask_get_bits(mask));
807 return s;
Marco Nelissenb2208842014-02-07 14:00:50 -0800808 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800809}
810
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700811void AudioFlinger::ThreadBase::dump(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800812{
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800813 dprintf(fd, "\n%s thread %p, name %s, tid %d, type %d (%s):\n", isOutput() ? "Output" : "Input",
814 this, mThreadName, getTid(), type(), threadTypeToString(type()));
815
Eric Laurent81784c32012-11-19 14:55:58 -0800816 bool locked = AudioFlinger::dumpTryLock(mLock);
817 if (!locked) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800818 dprintf(fd, " Thread may be deadlocked\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800819 }
820
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700821 dumpBase_l(fd, args);
822 dumpInternals_l(fd, args);
823 dumpTracks_l(fd, args);
824 dumpEffectChains_l(fd, args);
825
826 if (locked) {
827 mLock.unlock();
828 }
829
830 dprintf(fd, " Local log:\n");
831 mLocalLog.dump(fd, " " /* prefix */, 40 /* lines */);
832}
833
834void AudioFlinger::ThreadBase::dumpBase_l(int fd, const Vector<String16>& args __unused)
835{
Elliott Hughes87cebad2014-05-22 10:14:43 -0700836 dprintf(fd, " I/O handle: %d\n", mId);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700837 dprintf(fd, " Standby: %s\n", mStandby ? "yes" : "no");
Glenn Kasten97b7b752014-09-28 13:04:24 -0700838 dprintf(fd, " Sample rate: %u Hz\n", mSampleRate);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700839 dprintf(fd, " HAL frame count: %zu\n", mFrameCount);
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700840 dprintf(fd, " HAL format: 0x%x (%s)\n", mHALFormat, formatToString(mHALFormat).c_str());
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700841 dprintf(fd, " HAL buffer size: %zu bytes\n", mBufferSize);
Glenn Kasten97b7b752014-09-28 13:04:24 -0700842 dprintf(fd, " Channel count: %u\n", mChannelCount);
843 dprintf(fd, " Channel mask: 0x%08x (%s)\n", mChannelMask,
Marco Nelissenb2208842014-02-07 14:00:50 -0800844 channelMaskToString(mChannelMask, mType != RECORD).string());
Mikhail Naganov913d06c2016-11-01 12:49:22 -0700845 dprintf(fd, " Processing format: 0x%x (%s)\n", mFormat, formatToString(mFormat).c_str());
Glenn Kastenf87c2f52015-08-21 08:03:57 -0700846 dprintf(fd, " Processing frame size: %zu bytes\n", mFrameSize);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700847 dprintf(fd, " Pending config events:");
Marco Nelissenb2208842014-02-07 14:00:50 -0800848 size_t numConfig = mConfigEvents.size();
849 if (numConfig) {
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700850 const size_t SIZE = 256;
851 char buffer[SIZE];
Marco Nelissenb2208842014-02-07 14:00:50 -0800852 for (size_t i = 0; i < numConfig; i++) {
853 mConfigEvents[i]->dump(buffer, SIZE);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700854 dprintf(fd, "\n %s", buffer);
Marco Nelissenb2208842014-02-07 14:00:50 -0800855 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700856 dprintf(fd, "\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800857 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700858 dprintf(fd, " none\n");
Eric Laurent81784c32012-11-19 14:55:58 -0800859 }
Andy Hung293558a2017-03-21 12:19:20 -0700860 // Note: output device may be used by capture threads for effects such as AEC.
jiabin10d86fd2019-10-31 17:20:42 -0700861 dprintf(fd, " Output devices: %s (%s)\n",
862 dumpDeviceTypes(outDeviceTypes()).c_str(), toString(outDeviceTypes()).c_str());
863 dprintf(fd, " Input device: %#x (%s)\n",
864 inDeviceType(), toString(inDeviceType()).c_str());
Andy Hung9b181952019-02-25 14:53:36 -0800865 dprintf(fd, " Audio source: %d (%s)\n", mAudioSource, toString(mAudioSource).c_str());
Eric Laurent81784c32012-11-19 14:55:58 -0800866
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700867 // Dump timestamp statistics for the Thread types that support it.
868 if (mType == RECORD
869 || mType == MIXER
870 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -0700871 || mType == DIRECT
872 || mType == OFFLOAD) {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700873 dprintf(fd, " Timestamp stats: %s\n", mTimestampVerifier.toString().c_str());
Andy Hungc8fddf32018-08-08 18:32:37 -0700874 dprintf(fd, " Timestamp corrected: %s\n", isTimestampCorrectionEnabled() ? "yes" : "no");
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700875 }
876
Andy Hung446f4df2019-02-21 12:26:41 -0800877 if (mLastIoBeginNs > 0) { // MMAP may not set this
878 dprintf(fd, " Last %s occurred (msecs): %lld\n",
879 isOutput() ? "write" : "read",
880 (long long) (systemTime() - mLastIoBeginNs) / NANOS_PER_MILLISECOND);
881 }
882
883 if (mProcessTimeMs.getN() > 0) {
884 dprintf(fd, " Process time ms stats: %s\n", mProcessTimeMs.toString().c_str());
885 }
886
887 if (mIoJitterMs.getN() > 0) {
888 dprintf(fd, " Hal %s jitter ms stats: %s\n",
889 isOutput() ? "write" : "read",
890 mIoJitterMs.toString().c_str());
891 }
892
Andy Hunge6c37112019-02-26 17:38:10 -0800893 if (mLatencyMs.getN() > 0) {
894 dprintf(fd, " Threadloop %s latency stats: %s\n",
895 isOutput() ? "write" : "read",
896 mLatencyMs.toString().c_str());
897 }
Eric Laurent81784c32012-11-19 14:55:58 -0800898}
899
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -0700900void AudioFlinger::ThreadBase::dumpEffectChains_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -0800901{
902 const size_t SIZE = 256;
903 char buffer[SIZE];
Eric Laurent81784c32012-11-19 14:55:58 -0800904
Marco Nelissenb2208842014-02-07 14:00:50 -0800905 size_t numEffectChains = mEffectChains.size();
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000906 snprintf(buffer, SIZE, " %zu Effect Chains\n", numEffectChains);
Eric Laurent81784c32012-11-19 14:55:58 -0800907 write(fd, buffer, strlen(buffer));
908
Marco Nelissenb2208842014-02-07 14:00:50 -0800909 for (size_t i = 0; i < numEffectChains; ++i) {
Eric Laurent81784c32012-11-19 14:55:58 -0800910 sp<EffectChain> chain = mEffectChains[i];
911 if (chain != 0) {
912 chain->dump(fd, args);
913 }
914 }
915}
916
Andy Hungdae27702016-10-31 14:01:16 -0700917void AudioFlinger::ThreadBase::acquireWakeLock()
Eric Laurent81784c32012-11-19 14:55:58 -0800918{
919 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -0700920 acquireWakeLock_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800921}
922
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100923String16 AudioFlinger::ThreadBase::getWakeLockTag()
924{
925 switch (mType) {
Glenn Kastenbcb14862015-03-05 17:11:21 -0800926 case MIXER:
927 return String16("AudioMix");
928 case DIRECT:
929 return String16("AudioDirectOut");
930 case DUPLICATING:
931 return String16("AudioDup");
932 case RECORD:
933 return String16("AudioIn");
934 case OFFLOAD:
935 return String16("AudioOffload");
Eric Laurent6acd1d42017-01-04 14:23:29 -0800936 case MMAP:
937 return String16("Mmap");
Glenn Kastenbcb14862015-03-05 17:11:21 -0800938 default:
939 ALOG_ASSERT(false);
940 return String16("AudioUnknown");
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100941 }
942}
943
Andy Hungdae27702016-10-31 14:01:16 -0700944void AudioFlinger::ThreadBase::acquireWakeLock_l()
Eric Laurent81784c32012-11-19 14:55:58 -0800945{
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800946 getPowerManager_l();
Eric Laurent81784c32012-11-19 14:55:58 -0800947 if (mPowerManager != 0) {
948 sp<IBinder> binder = new BBinder();
Andy Hungdae27702016-10-31 14:01:16 -0700949 // Uses AID_AUDIOSERVER for wakelock. updateWakeLockUids_l() updates with client uids.
950 status_t status = mPowerManager->acquireWakeLock(POWERMANAGER_PARTIAL_WAKE_LOCK,
Marco Nelissene14a5d62013-10-03 08:51:24 -0700951 binder,
Narayan Kamath014e7fa2013-10-14 15:03:38 +0100952 getWakeLockTag(),
Marco Nelissendcb346b2015-09-09 10:47:29 -0700953 String16("audioserver"),
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700954 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800955 if (status == NO_ERROR) {
956 mWakeLockToken = binder;
957 }
Glenn Kastend7dca052015-03-05 16:05:54 -0800958 ALOGV("acquireWakeLock_l() %s status %d", mThreadName, status);
Eric Laurent81784c32012-11-19 14:55:58 -0800959 }
Wei Jia3f273d12015-11-24 09:06:49 -0800960
Andy Hung3f0c9022016-01-15 17:49:46 -0800961 gBoottime.acquire(mWakeLockToken);
Andy Hung818e7a32016-02-16 18:08:07 -0800962 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
963 gBoottime.getBoottimeOffset();
Eric Laurent81784c32012-11-19 14:55:58 -0800964}
965
966void AudioFlinger::ThreadBase::releaseWakeLock()
967{
968 Mutex::Autolock _l(mLock);
969 releaseWakeLock_l();
970}
971
972void AudioFlinger::ThreadBase::releaseWakeLock_l()
973{
Andy Hung3f0c9022016-01-15 17:49:46 -0800974 gBoottime.release(mWakeLockToken);
Eric Laurent81784c32012-11-19 14:55:58 -0800975 if (mWakeLockToken != 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800976 ALOGV("releaseWakeLock_l() %s", mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -0800977 if (mPowerManager != 0) {
Glenn Kasten3abc2de2014-09-05 16:45:52 -0700978 mPowerManager->releaseWakeLock(mWakeLockToken, 0,
979 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent81784c32012-11-19 14:55:58 -0800980 }
981 mWakeLockToken.clear();
982 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800983}
984
985void AudioFlinger::ThreadBase::getPowerManager_l() {
Eric Laurent72e3f392015-05-20 14:43:50 -0700986 if (mSystemReady && mPowerManager == 0) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800987 // use checkService() to avoid blocking if power service is not up yet
988 sp<IBinder> binder =
989 defaultServiceManager()->checkService(String16("power"));
990 if (binder == 0) {
Glenn Kastend7dca052015-03-05 16:05:54 -0800991 ALOGW("Thread %s cannot connect to the power manager service", mThreadName);
Marco Nelissen462fd2f2013-01-14 14:12:05 -0800992 } else {
993 mPowerManager = interface_cast<IPowerManager>(binder);
994 binder->linkToDeath(mDeathRecipient);
995 }
996 }
997}
998
Andy Hungd01b0f12016-11-07 16:10:30 -0800999void AudioFlinger::ThreadBase::updateWakeLockUids_l(const SortedVector<uid_t> &uids) {
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001000 getPowerManager_l();
Andy Hungdae27702016-10-31 14:01:16 -07001001
1002#if !LOG_NDEBUG
1003 std::stringstream s;
Andy Hungd01b0f12016-11-07 16:10:30 -08001004 for (uid_t uid : uids) {
Andy Hungdae27702016-10-31 14:01:16 -07001005 s << uid << " ";
1006 }
1007 ALOGD("updateWakeLockUids_l %s uids:%s", mThreadName, s.str().c_str());
1008#endif
1009
Andy Hung438e7572015-12-14 15:51:17 -08001010 if (mWakeLockToken == NULL) { // token may be NULL if AudioFlinger::systemReady() not called.
1011 if (mSystemReady) {
1012 ALOGE("no wake lock to update, but system ready!");
1013 } else {
1014 ALOGW("no wake lock to update, system not ready yet");
1015 }
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001016 return;
1017 }
1018 if (mPowerManager != 0) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08001019 std::vector<int> uidsAsInt(uids.begin(), uids.end()); // powermanager expects uids as ints
1020 status_t status = mPowerManager->updateWakeLockUids(
1021 mWakeLockToken, uidsAsInt.size(), uidsAsInt.data(),
1022 true /* FIXME force oneway contrary to .aidl */);
Eric Laurent4d231dc2016-03-11 18:38:23 -08001023 ALOGV("updateWakeLockUids_l() %s status %d", mThreadName, status);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08001024 }
1025}
1026
Eric Laurent81784c32012-11-19 14:55:58 -08001027void AudioFlinger::ThreadBase::clearPowerManager()
1028{
1029 Mutex::Autolock _l(mLock);
1030 releaseWakeLock_l();
1031 mPowerManager.clear();
1032}
1033
jiabin10d86fd2019-10-31 17:20:42 -07001034void AudioFlinger::ThreadBase::updateOutDevices(
1035 const DeviceDescriptorBaseVector& outDevices __unused)
1036{
1037 ALOGE("%s should only be called in RecordThread", __func__);
1038}
1039
Glenn Kasten0f11b512014-01-31 16:18:54 -08001040void AudioFlinger::ThreadBase::PMDeathRecipient::binderDied(const wp<IBinder>& who __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001041{
1042 sp<ThreadBase> thread = mThread.promote();
1043 if (thread != 0) {
1044 thread->clearPowerManager();
1045 }
1046 ALOGW("power manager service died !!!");
1047}
1048
Eric Laurent81784c32012-11-19 14:55:58 -08001049void AudioFlinger::ThreadBase::setEffectSuspended_l(
Glenn Kastend848eb42016-03-08 13:42:11 -08001050 const effect_uuid_t *type, bool suspend, audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001051{
1052 sp<EffectChain> chain = getEffectChain_l(sessionId);
1053 if (chain != 0) {
1054 if (type != NULL) {
1055 chain->setEffectSuspended_l(type, suspend);
1056 } else {
1057 chain->setEffectSuspendedAll_l(suspend);
1058 }
1059 }
1060
1061 updateSuspendedSessions_l(type, suspend, sessionId);
1062}
1063
1064void AudioFlinger::ThreadBase::checkSuspendOnAddEffectChain_l(const sp<EffectChain>& chain)
1065{
1066 ssize_t index = mSuspendedSessions.indexOfKey(chain->sessionId());
1067 if (index < 0) {
1068 return;
1069 }
1070
1071 const KeyedVector <int, sp<SuspendedSessionDesc> >& sessionEffects =
1072 mSuspendedSessions.valueAt(index);
1073
1074 for (size_t i = 0; i < sessionEffects.size(); i++) {
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07001075 const sp<SuspendedSessionDesc>& desc = sessionEffects.valueAt(i);
Eric Laurent81784c32012-11-19 14:55:58 -08001076 for (int j = 0; j < desc->mRefCount; j++) {
1077 if (sessionEffects.keyAt(i) == EffectChain::kKeyForSuspendAll) {
1078 chain->setEffectSuspendedAll_l(true);
1079 } else {
1080 ALOGV("checkSuspendOnAddEffectChain_l() suspending effects %08x",
1081 desc->mType.timeLow);
1082 chain->setEffectSuspended_l(&desc->mType, true);
1083 }
1084 }
1085 }
1086}
1087
1088void AudioFlinger::ThreadBase::updateSuspendedSessions_l(const effect_uuid_t *type,
1089 bool suspend,
Glenn Kastend848eb42016-03-08 13:42:11 -08001090 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001091{
1092 ssize_t index = mSuspendedSessions.indexOfKey(sessionId);
1093
1094 KeyedVector <int, sp<SuspendedSessionDesc> > sessionEffects;
1095
1096 if (suspend) {
1097 if (index >= 0) {
1098 sessionEffects = mSuspendedSessions.valueAt(index);
1099 } else {
1100 mSuspendedSessions.add(sessionId, sessionEffects);
1101 }
1102 } else {
1103 if (index < 0) {
1104 return;
1105 }
1106 sessionEffects = mSuspendedSessions.valueAt(index);
1107 }
1108
1109
1110 int key = EffectChain::kKeyForSuspendAll;
1111 if (type != NULL) {
1112 key = type->timeLow;
1113 }
1114 index = sessionEffects.indexOfKey(key);
1115
1116 sp<SuspendedSessionDesc> desc;
1117 if (suspend) {
1118 if (index >= 0) {
1119 desc = sessionEffects.valueAt(index);
1120 } else {
1121 desc = new SuspendedSessionDesc();
1122 if (type != NULL) {
1123 desc->mType = *type;
1124 }
1125 sessionEffects.add(key, desc);
1126 ALOGV("updateSuspendedSessions_l() suspend adding effect %08x", key);
1127 }
1128 desc->mRefCount++;
1129 } else {
1130 if (index < 0) {
1131 return;
1132 }
1133 desc = sessionEffects.valueAt(index);
1134 if (--desc->mRefCount == 0) {
1135 ALOGV("updateSuspendedSessions_l() restore removing effect %08x", key);
1136 sessionEffects.removeItemsAt(index);
1137 if (sessionEffects.isEmpty()) {
1138 ALOGV("updateSuspendedSessions_l() restore removing session %d",
1139 sessionId);
1140 mSuspendedSessions.removeItem(sessionId);
1141 }
1142 }
1143 }
1144 if (!sessionEffects.isEmpty()) {
1145 mSuspendedSessions.replaceValueFor(sessionId, sessionEffects);
1146 }
1147}
1148
1149void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled(const sp<EffectModule>& effect,
1150 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001151 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001152{
1153 Mutex::Autolock _l(mLock);
1154 checkSuspendOnEffectEnabled_l(effect, enabled, sessionId);
1155}
1156
1157void AudioFlinger::ThreadBase::checkSuspendOnEffectEnabled_l(const sp<EffectModule>& effect,
1158 bool enabled,
Glenn Kastend848eb42016-03-08 13:42:11 -08001159 audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001160{
1161 if (mType != RECORD) {
1162 // suspend all effects in AUDIO_SESSION_OUTPUT_MIX when enabling any effect on
1163 // another session. This gives the priority to well behaved effect control panels
1164 // and applications not using global effects.
1165 // Enabling post processing in AUDIO_SESSION_OUTPUT_STAGE session does not affect
1166 // global effects
1167 if ((sessionId != AUDIO_SESSION_OUTPUT_MIX) && (sessionId != AUDIO_SESSION_OUTPUT_STAGE)) {
1168 setEffectSuspended_l(NULL, enabled, AUDIO_SESSION_OUTPUT_MIX);
1169 }
1170 }
1171
1172 sp<EffectChain> chain = getEffectChain_l(sessionId);
1173 if (chain != 0) {
1174 chain->checkSuspendOnEffectEnabled(effect, enabled);
1175 }
1176}
1177
Eric Laurent4c415062016-06-17 16:14:16 -07001178// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1179status_t AudioFlinger::RecordThread::checkEffectCompatibility_l(
1180 const effect_descriptor_t *desc, audio_session_t sessionId)
1181{
1182 // No global effect sessions on record threads
1183 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1184 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
1185 desc->name, mThreadName);
1186 return BAD_VALUE;
1187 }
1188 // only pre processing effects on record thread
1189 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC) {
1190 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on record thread %s",
1191 desc->name, mThreadName);
1192 return BAD_VALUE;
1193 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001194
1195 // always allow effects without processing load or latency
1196 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1197 return NO_ERROR;
1198 }
1199
Eric Laurent4c415062016-06-17 16:14:16 -07001200 audio_input_flags_t flags = mInput->flags;
1201 if (hasFastCapture() || (flags & AUDIO_INPUT_FLAG_FAST)) {
1202 if (flags & AUDIO_INPUT_FLAG_RAW) {
1203 ALOGW("checkEffectCompatibility_l(): effect %s on record thread %s in raw mode",
1204 desc->name, mThreadName);
1205 return BAD_VALUE;
1206 }
1207 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1208 ALOGW("checkEffectCompatibility_l(): non HW effect %s on record thread %s in fast mode",
1209 desc->name, mThreadName);
1210 return BAD_VALUE;
1211 }
1212 }
1213 return NO_ERROR;
1214}
1215
1216// checkEffectCompatibility_l() must be called with ThreadBase::mLock held
1217status_t AudioFlinger::PlaybackThread::checkEffectCompatibility_l(
1218 const effect_descriptor_t *desc, audio_session_t sessionId)
1219{
1220 // no preprocessing on playback threads
1221 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC) {
1222 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback"
1223 " thread %s", desc->name, mThreadName);
1224 return BAD_VALUE;
1225 }
1226
Eric Laurent3e4de772017-07-16 16:55:08 -07001227 // always allow effects without processing load or latency
1228 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) == EFFECT_FLAG_NO_PROCESS) {
1229 return NO_ERROR;
1230 }
1231
Eric Laurent4c415062016-06-17 16:14:16 -07001232 switch (mType) {
1233 case MIXER: {
Andy Hung9aad48c2017-11-29 10:29:19 -08001234#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001235 // Reject any effect on mixer multichannel sinks.
1236 // TODO: fix both format and multichannel issues with effects.
1237 if (mChannelCount != FCC_2) {
1238 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d) on MIXER"
1239 " thread %s", desc->name, mChannelCount, mThreadName);
1240 return BAD_VALUE;
1241 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001242#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001243 audio_output_flags_t flags = mOutput->flags;
1244 if (hasFastMixer() || (flags & AUDIO_OUTPUT_FLAG_FAST)) {
1245 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
1246 // global effects are applied only to non fast tracks if they are SW
1247 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1248 break;
1249 }
1250 } else if (sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
1251 // only post processing on output stage session
1252 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_POST_PROC) {
1253 ALOGW("checkEffectCompatibility_l(): non post processing effect %s not allowed"
1254 " on output stage session", desc->name);
1255 return BAD_VALUE;
1256 }
1257 } else {
1258 // no restriction on effects applied on non fast tracks
1259 if ((hasAudioSession_l(sessionId) & ThreadBase::FAST_SESSION) == 0) {
1260 break;
1261 }
1262 }
Eric Laurent6dd0fd92016-09-15 12:44:53 -07001263
Eric Laurent4c415062016-06-17 16:14:16 -07001264 if (flags & AUDIO_OUTPUT_FLAG_RAW) {
1265 ALOGW("checkEffectCompatibility_l(): effect %s on playback thread in raw mode",
1266 desc->name);
1267 return BAD_VALUE;
1268 }
1269 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) == 0) {
1270 ALOGW("checkEffectCompatibility_l(): non HW effect %s on playback thread"
1271 " in fast mode", desc->name);
1272 return BAD_VALUE;
1273 }
1274 }
1275 } break;
1276 case OFFLOAD:
Jean-Michel Trivi773ee952016-07-11 16:53:18 -07001277 // nothing actionable on offload threads, if the effect:
1278 // - is offloadable: the effect can be created
1279 // - is NOT offloadable: the effect should still be created, but EffectHandle::enable()
1280 // will take care of invalidating the tracks of the thread
Eric Laurent4c415062016-06-17 16:14:16 -07001281 break;
1282 case DIRECT:
1283 // Reject any effect on Direct output threads for now, since the format of
1284 // mSinkBuffer is not guaranteed to be compatible with effect processing (PCM 16 stereo).
1285 ALOGW("checkEffectCompatibility_l(): effect %s on DIRECT output thread %s",
1286 desc->name, mThreadName);
1287 return BAD_VALUE;
1288 case DUPLICATING:
Andy Hung9aad48c2017-11-29 10:29:19 -08001289#ifndef MULTICHANNEL_EFFECT_CHAIN
Eric Laurent4c415062016-06-17 16:14:16 -07001290 // Reject any effect on mixer multichannel sinks.
1291 // TODO: fix both format and multichannel issues with effects.
1292 if (mChannelCount != FCC_2) {
1293 ALOGW("checkEffectCompatibility_l(): effect %s for multichannel(%d)"
1294 " on DUPLICATING thread %s", desc->name, mChannelCount, mThreadName);
1295 return BAD_VALUE;
1296 }
Andy Hung9aad48c2017-11-29 10:29:19 -08001297#endif
Eric Laurent4c415062016-06-17 16:14:16 -07001298 if ((sessionId == AUDIO_SESSION_OUTPUT_STAGE) || (sessionId == AUDIO_SESSION_OUTPUT_MIX)) {
1299 ALOGW("checkEffectCompatibility_l(): global effect %s on DUPLICATING"
1300 " thread %s", desc->name, mThreadName);
1301 return BAD_VALUE;
1302 }
1303 if ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_POST_PROC) {
1304 ALOGW("checkEffectCompatibility_l(): post processing effect %s on"
1305 " DUPLICATING thread %s", desc->name, mThreadName);
1306 return BAD_VALUE;
1307 }
1308 if ((desc->flags & EFFECT_FLAG_HW_ACC_TUNNEL) != 0) {
1309 ALOGW("checkEffectCompatibility_l(): HW tunneled effect %s on"
1310 " DUPLICATING thread %s", desc->name, mThreadName);
1311 return BAD_VALUE;
1312 }
1313 break;
1314 default:
1315 LOG_ALWAYS_FATAL("checkEffectCompatibility_l(): wrong thread type %d", mType);
1316 }
1317
1318 return NO_ERROR;
1319}
1320
Eric Laurent81784c32012-11-19 14:55:58 -08001321// ThreadBase::createEffect_l() must be called with AudioFlinger::mLock held
1322sp<AudioFlinger::EffectHandle> AudioFlinger::ThreadBase::createEffect_l(
1323 const sp<AudioFlinger::Client>& client,
1324 const sp<IEffectClient>& effectClient,
1325 int32_t priority,
Glenn Kastend848eb42016-03-08 13:42:11 -08001326 audio_session_t sessionId,
Eric Laurent81784c32012-11-19 14:55:58 -08001327 effect_descriptor_t *desc,
1328 int *enabled,
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001329 status_t *status,
1330 bool pinned)
Eric Laurent81784c32012-11-19 14:55:58 -08001331{
1332 sp<EffectModule> effect;
1333 sp<EffectHandle> handle;
1334 status_t lStatus;
1335 sp<EffectChain> chain;
1336 bool chainCreated = false;
1337 bool effectCreated = false;
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001338 audio_unique_id_t effectId = AUDIO_UNIQUE_ID_USE_UNSPECIFIED;
Eric Laurent81784c32012-11-19 14:55:58 -08001339
1340 lStatus = initCheck();
1341 if (lStatus != NO_ERROR) {
1342 ALOGW("createEffect_l() Audio driver not initialized.");
1343 goto Exit;
1344 }
1345
Eric Laurent81784c32012-11-19 14:55:58 -08001346 ALOGV("createEffect_l() thread %p effect %s on session %d", this, desc->name, sessionId);
1347
1348 { // scope for mLock
1349 Mutex::Autolock _l(mLock);
1350
Eric Laurent4c415062016-06-17 16:14:16 -07001351 lStatus = checkEffectCompatibility_l(desc, sessionId);
1352 if (lStatus != NO_ERROR) {
1353 goto Exit;
1354 }
1355
Eric Laurent81784c32012-11-19 14:55:58 -08001356 // check for existing effect chain with the requested audio session
1357 chain = getEffectChain_l(sessionId);
1358 if (chain == 0) {
1359 // create a new chain for this session
1360 ALOGV("createEffect_l() new effect chain for session %d", sessionId);
1361 chain = new EffectChain(this, sessionId);
1362 addEffectChain_l(chain);
1363 chain->setStrategy(getStrategyForSession_l(sessionId));
1364 chainCreated = true;
1365 } else {
1366 effect = chain->getEffectFromDesc_l(desc);
1367 }
1368
1369 ALOGV("createEffect_l() got effect %p on chain %p", effect.get(), chain.get());
1370
1371 if (effect == 0) {
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001372 effectId = mAudioFlinger->nextUniqueId(AUDIO_UNIQUE_ID_USE_EFFECT);
Eric Laurent81784c32012-11-19 14:55:58 -08001373 // create a new effect module if none present in the chain
Mikhail Naganov2247f7b2017-01-13 11:52:54 -08001374 lStatus = chain->createEffect_l(effect, this, desc, effectId, sessionId, pinned);
Eric Laurent81784c32012-11-19 14:55:58 -08001375 if (lStatus != NO_ERROR) {
1376 goto Exit;
1377 }
1378 effectCreated = true;
1379
jiabin10d86fd2019-10-31 17:20:42 -07001380 // FIXME: use vector of device and address when effect interface is ready.
jiabinb8269fd2019-11-11 12:16:27 -08001381 effect->setDevices(outDeviceTypeAddrs());
1382 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001383 effect->setMode(mAudioFlinger->getMode());
1384 effect->setAudioSource(mAudioSource);
1385 }
1386 // create effect handle and connect it to effect module
1387 handle = new EffectHandle(effect, client, effectClient, priority);
Glenn Kastene75da402013-11-20 13:54:52 -08001388 lStatus = handle->initCheck();
1389 if (lStatus == OK) {
1390 lStatus = effect->addHandle(handle.get());
1391 }
Eric Laurent81784c32012-11-19 14:55:58 -08001392 if (enabled != NULL) {
1393 *enabled = (int)effect->isEnabled();
1394 }
1395 }
1396
1397Exit:
1398 if (lStatus != NO_ERROR && lStatus != ALREADY_EXISTS) {
1399 Mutex::Autolock _l(mLock);
1400 if (effectCreated) {
1401 chain->removeEffect_l(effect);
1402 }
Eric Laurent81784c32012-11-19 14:55:58 -08001403 if (chainCreated) {
1404 removeEffectChain_l(chain);
1405 }
haobo101735295ff7b0d2017-03-17 17:44:03 +08001406 // handle must be cleared by caller to avoid deadlock.
Eric Laurent81784c32012-11-19 14:55:58 -08001407 }
1408
Glenn Kasten9156ef32013-08-06 15:39:08 -07001409 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08001410 return handle;
1411}
1412
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001413void AudioFlinger::ThreadBase::disconnectEffectHandle(EffectHandle *handle,
1414 bool unpinIfLast)
1415{
1416 bool remove = false;
1417 sp<EffectModule> effect;
1418 {
1419 Mutex::Autolock _l(mLock);
1420
1421 effect = handle->effect().promote();
1422 if (effect == 0) {
1423 return;
1424 }
1425 // restore suspended effects if the disconnected handle was enabled and the last one.
1426 remove = (effect->removeHandle(handle) == 0) && (!effect->isPinned() || unpinIfLast);
1427 if (remove) {
1428 removeEffect_l(effect, true);
1429 }
1430 }
1431 if (remove) {
1432 mAudioFlinger->updateOrphanEffectChains(effect);
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001433 if (handle->enabled()) {
1434 checkSuspendOnEffectEnabled(effect, false, effect->sessionId());
1435 }
1436 }
1437}
1438
Glenn Kastend848eb42016-03-08 13:42:11 -08001439sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect(audio_session_t sessionId,
1440 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001441{
1442 Mutex::Autolock _l(mLock);
1443 return getEffect_l(sessionId, effectId);
1444}
1445
Glenn Kastend848eb42016-03-08 13:42:11 -08001446sp<AudioFlinger::EffectModule> AudioFlinger::ThreadBase::getEffect_l(audio_session_t sessionId,
1447 int effectId)
Eric Laurent81784c32012-11-19 14:55:58 -08001448{
1449 sp<EffectChain> chain = getEffectChain_l(sessionId);
1450 return chain != 0 ? chain->getEffectFromId_l(effectId) : 0;
1451}
1452
Eric Laurent6c796322019-04-09 14:13:17 -07001453std::vector<int> AudioFlinger::ThreadBase::getEffectIds_l(audio_session_t sessionId)
1454{
1455 sp<EffectChain> chain = getEffectChain_l(sessionId);
1456 return chain != nullptr ? chain->getEffectIds() : std::vector<int>{};
1457}
1458
Eric Laurent81784c32012-11-19 14:55:58 -08001459// PlaybackThread::addEffect_l() must be called with AudioFlinger::mLock and
1460// PlaybackThread::mLock held
1461status_t AudioFlinger::ThreadBase::addEffect_l(const sp<EffectModule>& effect)
1462{
1463 // check for existing effect chain with the requested audio session
Glenn Kastend848eb42016-03-08 13:42:11 -08001464 audio_session_t sessionId = effect->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08001465 sp<EffectChain> chain = getEffectChain_l(sessionId);
1466 bool chainCreated = false;
1467
Eric Laurent5baf2af2013-09-12 17:37:00 -07001468 ALOGD_IF((mType == OFFLOAD) && !effect->isOffloadable(),
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001469 "addEffect_l() on offloaded thread %p: effect %s does not support offload flags %#x",
Eric Laurent5baf2af2013-09-12 17:37:00 -07001470 this, effect->desc().name, effect->desc().flags);
1471
Eric Laurent81784c32012-11-19 14:55:58 -08001472 if (chain == 0) {
1473 // create a new chain for this session
1474 ALOGV("addEffect_l() new effect chain for session %d", sessionId);
1475 chain = new EffectChain(this, sessionId);
1476 addEffectChain_l(chain);
1477 chain->setStrategy(getStrategyForSession_l(sessionId));
1478 chainCreated = true;
1479 }
1480 ALOGV("addEffect_l() %p chain %p effect %p", this, chain.get(), effect.get());
1481
1482 if (chain->getEffectFromId_l(effect->id()) != 0) {
1483 ALOGW("addEffect_l() %p effect %s already present in chain %p",
1484 this, effect->desc().name, chain.get());
1485 return BAD_VALUE;
1486 }
1487
Eric Laurent5baf2af2013-09-12 17:37:00 -07001488 effect->setOffloaded(mType == OFFLOAD, mId);
1489
Eric Laurent81784c32012-11-19 14:55:58 -08001490 status_t status = chain->addEffect_l(effect);
1491 if (status != NO_ERROR) {
1492 if (chainCreated) {
1493 removeEffectChain_l(chain);
1494 }
1495 return status;
1496 }
1497
jiabinb8269fd2019-11-11 12:16:27 -08001498 effect->setDevices(outDeviceTypeAddrs());
1499 effect->setInputDevice(inDeviceTypeAddr());
Eric Laurent81784c32012-11-19 14:55:58 -08001500 effect->setMode(mAudioFlinger->getMode());
1501 effect->setAudioSource(mAudioSource);
Eric Laurentd8365c52017-07-16 15:27:05 -07001502
Eric Laurent81784c32012-11-19 14:55:58 -08001503 return NO_ERROR;
1504}
1505
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001506void AudioFlinger::ThreadBase::removeEffect_l(const sp<EffectModule>& effect, bool release) {
Eric Laurent81784c32012-11-19 14:55:58 -08001507
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001508 ALOGV("%s %p effect %p", __FUNCTION__, this, effect.get());
Eric Laurent81784c32012-11-19 14:55:58 -08001509 effect_descriptor_t desc = effect->desc();
1510 if ((desc.flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
1511 detachAuxEffect_l(effect->id());
1512 }
1513
1514 sp<EffectChain> chain = effect->chain().promote();
1515 if (chain != 0) {
1516 // remove effect chain if removing last effect
Eric Laurent0d5a2ed2016-12-01 15:28:29 -08001517 if (chain->removeEffect_l(effect, release) == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08001518 removeEffectChain_l(chain);
1519 }
1520 } else {
1521 ALOGW("removeEffect_l() %p cannot promote chain for effect %p", this, effect.get());
1522 }
1523}
1524
1525void AudioFlinger::ThreadBase::lockEffectChains_l(
1526 Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1527{
1528 effectChains = mEffectChains;
1529 for (size_t i = 0; i < mEffectChains.size(); i++) {
1530 mEffectChains[i]->lock();
1531 }
1532}
1533
1534void AudioFlinger::ThreadBase::unlockEffectChains(
1535 const Vector< sp<AudioFlinger::EffectChain> >& effectChains)
1536{
1537 for (size_t i = 0; i < effectChains.size(); i++) {
1538 effectChains[i]->unlock();
1539 }
1540}
1541
Glenn Kastend848eb42016-03-08 13:42:11 -08001542sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08001543{
1544 Mutex::Autolock _l(mLock);
1545 return getEffectChain_l(sessionId);
1546}
1547
Glenn Kastend848eb42016-03-08 13:42:11 -08001548sp<AudioFlinger::EffectChain> AudioFlinger::ThreadBase::getEffectChain_l(audio_session_t sessionId)
1549 const
Eric Laurent81784c32012-11-19 14:55:58 -08001550{
1551 size_t size = mEffectChains.size();
1552 for (size_t i = 0; i < size; i++) {
1553 if (mEffectChains[i]->sessionId() == sessionId) {
1554 return mEffectChains[i];
1555 }
1556 }
1557 return 0;
1558}
1559
1560void AudioFlinger::ThreadBase::setMode(audio_mode_t mode)
1561{
1562 Mutex::Autolock _l(mLock);
1563 size_t size = mEffectChains.size();
1564 for (size_t i = 0; i < size; i++) {
1565 mEffectChains[i]->setMode_l(mode);
1566 }
1567}
1568
Mikhail Naganovdc769682018-05-04 15:34:08 -07001569void AudioFlinger::ThreadBase::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07001570{
1571 config->type = AUDIO_PORT_TYPE_MIX;
1572 config->ext.mix.handle = mId;
1573 config->sample_rate = mSampleRate;
1574 config->format = mFormat;
1575 config->channel_mask = mChannelMask;
1576 config->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
1577 AUDIO_PORT_CONFIG_FORMAT;
1578}
1579
Eric Laurent72e3f392015-05-20 14:43:50 -07001580void AudioFlinger::ThreadBase::systemReady()
1581{
1582 Mutex::Autolock _l(mLock);
1583 if (mSystemReady) {
1584 return;
1585 }
1586 mSystemReady = true;
1587
1588 for (size_t i = 0; i < mPendingConfigEvents.size(); i++) {
1589 sendConfigEvent_l(mPendingConfigEvents.editItemAt(i));
1590 }
1591 mPendingConfigEvents.clear();
1592}
1593
Andy Hungdae27702016-10-31 14:01:16 -07001594template <typename T>
1595ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::add(const sp<T> &track) {
1596 ssize_t index = mActiveTracks.indexOf(track);
1597 if (index >= 0) {
1598 ALOGW("ActiveTracks<T>::add track %p already there", track.get());
1599 return index;
1600 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001601 logTrack("add", track);
Andy Hungdae27702016-10-31 14:01:16 -07001602 mActiveTracksGeneration++;
1603 mLatestActiveTrack = track;
1604 ++mBatteryCounter[track->uid()].second;
Kevin Rocard069c2712018-03-29 19:09:14 -07001605 mHasChanged = true;
Andy Hungdae27702016-10-31 14:01:16 -07001606 return mActiveTracks.add(track);
1607}
1608
1609template <typename T>
1610ssize_t AudioFlinger::ThreadBase::ActiveTracks<T>::remove(const sp<T> &track) {
1611 ssize_t index = mActiveTracks.remove(track);
1612 if (index < 0) {
1613 ALOGW("ActiveTracks<T>::remove nonexistent track %p", track.get());
1614 return index;
1615 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001616 logTrack("remove", track);
Andy Hungdae27702016-10-31 14:01:16 -07001617 mActiveTracksGeneration++;
1618 --mBatteryCounter[track->uid()].second;
1619 // mLatestActiveTrack is not cleared even if is the same as track.
Kevin Rocard069c2712018-03-29 19:09:14 -07001620 mHasChanged = true;
Andy Hung8946a282018-04-19 20:04:56 -07001621#ifdef TEE_SINK
1622 track->dumpTee(-1 /* fd */, "_REMOVE");
1623#endif
Andy Hungdae27702016-10-31 14:01:16 -07001624 return index;
1625}
1626
1627template <typename T>
1628void AudioFlinger::ThreadBase::ActiveTracks<T>::clear() {
1629 for (const sp<T> &track : mActiveTracks) {
1630 BatteryNotifier::getInstance().noteStopAudio(track->uid());
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001631 logTrack("clear", track);
Andy Hungdae27702016-10-31 14:01:16 -07001632 }
1633 mLastActiveTracksGeneration = mActiveTracksGeneration;
Kevin Rocard069c2712018-03-29 19:09:14 -07001634 if (!mActiveTracks.empty()) { mHasChanged = true; }
Andy Hungdae27702016-10-31 14:01:16 -07001635 mActiveTracks.clear();
1636 mLatestActiveTrack.clear();
1637 mBatteryCounter.clear();
1638}
1639
1640template <typename T>
1641void AudioFlinger::ThreadBase::ActiveTracks<T>::updatePowerState(
1642 sp<ThreadBase> thread, bool force) {
1643 // Updates ActiveTracks client uids to the thread wakelock.
1644 if (mActiveTracksGeneration != mLastActiveTracksGeneration || force) {
1645 thread->updateWakeLockUids_l(getWakeLockUids());
1646 mLastActiveTracksGeneration = mActiveTracksGeneration;
1647 }
1648
1649 // Updates BatteryNotifier uids
1650 for (auto it = mBatteryCounter.begin(); it != mBatteryCounter.end();) {
1651 const uid_t uid = it->first;
1652 ssize_t &previous = it->second.first;
1653 ssize_t &current = it->second.second;
1654 if (current > 0) {
1655 if (previous == 0) {
1656 BatteryNotifier::getInstance().noteStartAudio(uid);
1657 }
1658 previous = current;
1659 ++it;
1660 } else if (current == 0) {
1661 if (previous > 0) {
1662 BatteryNotifier::getInstance().noteStopAudio(uid);
1663 }
1664 it = mBatteryCounter.erase(it); // std::map<> is stable on iterator erase.
1665 } else /* (current < 0) */ {
1666 LOG_ALWAYS_FATAL("negative battery count %zd", current);
1667 }
1668 }
1669}
Eric Laurent83b88082014-06-20 18:31:16 -07001670
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001671template <typename T>
Kevin Rocard069c2712018-03-29 19:09:14 -07001672bool AudioFlinger::ThreadBase::ActiveTracks<T>::readAndClearHasChanged() {
1673 const bool hasChanged = mHasChanged;
1674 mHasChanged = false;
1675 return hasChanged;
1676}
1677
1678template <typename T>
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001679void AudioFlinger::ThreadBase::ActiveTracks<T>::logTrack(
1680 const char *funcName, const sp<T> &track) const {
1681 if (mLocalLog != nullptr) {
1682 String8 result;
1683 track->appendDump(result, false /* active */);
1684 mLocalLog->log("AT::%-10s(%p) %s", funcName, track.get(), result.string());
1685 }
1686}
1687
Eric Laurent6acd1d42017-01-04 14:23:29 -08001688void AudioFlinger::ThreadBase::broadcast_l()
1689{
1690 // Thread could be blocked waiting for async
1691 // so signal it to handle state changes immediately
1692 // If threadLoop is currently unlocked a signal of mWaitWorkCV will
1693 // be lost so we also flag to prevent it blocking on mWaitWorkCV
1694 mSignalPending = true;
1695 mWaitWorkCV.broadcast();
1696}
1697
Andy Hungd0979812019-02-21 15:51:44 -08001698// Call only from threadLoop() or when it is idle.
1699// Do not call from high performance code as this may do binder rpc to the MediaMetrics service.
1700void AudioFlinger::ThreadBase::sendStatistics(bool force)
1701{
1702 // Do not log if we have no stats.
1703 // We choose the timestamp verifier because it is the most likely item to be present.
1704 const int64_t nstats = mTimestampVerifier.getN() - mLastRecordedTimestampVerifierN;
1705 if (nstats == 0) {
1706 return;
1707 }
1708
1709 // Don't log more frequently than once per 12 hours.
1710 // We use BOOTTIME to include suspend time.
1711 const int64_t timeNs = systemTime(SYSTEM_TIME_BOOTTIME);
1712 const int64_t sinceNs = timeNs - mLastRecordedTimeNs; // ok if mLastRecordedTimeNs = 0
1713 if (!force && sinceNs <= 12 * NANOS_PER_HOUR) {
1714 return;
1715 }
1716
1717 mLastRecordedTimestampVerifierN = mTimestampVerifier.getN();
1718 mLastRecordedTimeNs = timeNs;
1719
1720 std::unique_ptr<MediaAnalyticsItem> item(MediaAnalyticsItem::create("audiothread"));
1721
1722#define MM_PREFIX "android.media.audiothread." // avoid cut-n-paste errors.
1723
1724 // thread configuration
1725 item->setInt32(MM_PREFIX "id", (int32_t)mId); // IO handle
1726 // item->setInt32(MM_PREFIX "portId", (int32_t)mPortId);
1727 item->setCString(MM_PREFIX "type", threadTypeToString(mType));
1728 item->setInt32(MM_PREFIX "sampleRate", (int32_t)mSampleRate);
1729 item->setInt64(MM_PREFIX "channelMask", (int64_t)mChannelMask);
1730 item->setCString(MM_PREFIX "encoding", toString(mFormat).c_str());
1731 item->setInt32(MM_PREFIX "frameCount", (int32_t)mFrameCount);
jiabin10d86fd2019-10-31 17:20:42 -07001732 item->setCString(MM_PREFIX "outDevice", toString(outDeviceTypes()).c_str());
1733 item->setCString(MM_PREFIX "inDevice", toString(inDeviceType()).c_str());
Andy Hungd0979812019-02-21 15:51:44 -08001734
1735 // thread statistics
1736 if (mIoJitterMs.getN() > 0) {
1737 item->setDouble(MM_PREFIX "ioJitterMs.mean", mIoJitterMs.getMean());
1738 item->setDouble(MM_PREFIX "ioJitterMs.std", mIoJitterMs.getStdDev());
1739 }
1740 if (mProcessTimeMs.getN() > 0) {
1741 item->setDouble(MM_PREFIX "processTimeMs.mean", mProcessTimeMs.getMean());
1742 item->setDouble(MM_PREFIX "processTimeMs.std", mProcessTimeMs.getStdDev());
1743 }
1744 const auto tsjitter = mTimestampVerifier.getJitterMs();
1745 if (tsjitter.getN() > 0) {
1746 item->setDouble(MM_PREFIX "timestampJitterMs.mean", tsjitter.getMean());
1747 item->setDouble(MM_PREFIX "timestampJitterMs.std", tsjitter.getStdDev());
1748 }
1749 if (mLatencyMs.getN() > 0) {
1750 item->setDouble(MM_PREFIX "latencyMs.mean", mLatencyMs.getMean());
1751 item->setDouble(MM_PREFIX "latencyMs.std", mLatencyMs.getStdDev());
1752 }
1753
1754 item->selfrecord();
1755}
1756
Eric Laurent81784c32012-11-19 14:55:58 -08001757// ----------------------------------------------------------------------------
1758// Playback
1759// ----------------------------------------------------------------------------
1760
1761AudioFlinger::PlaybackThread::PlaybackThread(const sp<AudioFlinger>& audioFlinger,
1762 AudioStreamOut* output,
1763 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07001764 type_t type,
Eric Laurente93cc032016-05-05 10:15:10 -07001765 bool systemReady)
jiabin10d86fd2019-10-31 17:20:42 -07001766 : ThreadBase(audioFlinger, id, type, systemReady),
Andy Hung2098f272014-02-27 14:00:06 -08001767 mNormalFrameCount(0), mSinkBuffer(NULL),
Andy Hung6146c082014-03-18 11:56:15 -07001768 mMixerBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung69aed5f2014-02-25 17:24:40 -08001769 mMixerBuffer(NULL),
1770 mMixerBufferSize(0),
1771 mMixerBufferFormat(AUDIO_FORMAT_INVALID),
1772 mMixerBufferValid(false),
Andy Hung6146c082014-03-18 11:56:15 -07001773 mEffectBufferEnabled(AudioFlinger::kEnableExtendedPrecision),
Andy Hung98ef9782014-03-04 14:46:50 -08001774 mEffectBuffer(NULL),
1775 mEffectBufferSize(0),
1776 mEffectBufferFormat(AUDIO_FORMAT_INVALID),
1777 mEffectBufferValid(false),
Glenn Kastenc1fac192013-08-06 07:41:36 -07001778 mSuspended(0), mBytesWritten(0),
Andy Hungc54b1ff2016-02-23 14:07:07 -08001779 mFramesWritten(0),
Andy Hung238fa3d2016-07-28 10:53:22 -07001780 mSuspendedFrames(0),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001781 mActiveTracks(&this->mLocalLog),
Eric Laurent81784c32012-11-19 14:55:58 -08001782 // mStreamTypes[] initialized in constructor body
Andy Hung1bc088a2018-02-09 15:57:31 -08001783 mTracks(type == MIXER),
Eric Laurent81784c32012-11-19 14:55:58 -08001784 mOutput(output),
Andy Hung446f4df2019-02-21 12:26:41 -08001785 mNumWrites(0), mNumDelayedWrites(0), mInWrite(false),
Eric Laurent81784c32012-11-19 14:55:58 -08001786 mMixerStatus(MIXER_IDLE),
1787 mMixerStatusIgnoringFastTracks(MIXER_IDLE),
Eric Laurentad9cb8b2015-05-26 16:38:19 -07001788 mStandbyDelayNs(AudioFlinger::mStandbyTimeInNsecs),
Eric Laurentbfb1b832013-01-07 09:53:42 -08001789 mBytesRemaining(0),
1790 mCurrentWriteLength(0),
1791 mUseAsyncWrite(false),
Eric Laurent3b4529e2013-09-05 18:09:19 -07001792 mWriteAckSequence(0),
1793 mDrainSequence(0),
Eric Laurent81784c32012-11-19 14:55:58 -08001794 mScreenState(AudioFlinger::mScreenState),
1795 // index 0 is reserved for normal mixer's submix
Glenn Kastendc2c50b2016-04-21 08:13:14 -07001796 mFastTrackAvailMask(((1 << FastMixerState::sMaxFastTracks) - 1) & ~1),
Eric Laurent7c29ec92017-09-20 17:54:22 -07001797 mHwSupportsPause(false), mHwPaused(false), mFlushPending(false),
1798 mLeftVolFloat(-1.0), mRightVolFloat(-1.0)
Eric Laurent81784c32012-11-19 14:55:58 -08001799{
Glenn Kastend7dca052015-03-05 16:05:54 -08001800 snprintf(mThreadName, kThreadNameLength, "AudioOut_%X", id);
1801 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08001802
1803 // Assumes constructor is called by AudioFlinger with it's mLock held, but
1804 // it would be safer to explicitly pass initial masterVolume/masterMute as
1805 // parameter.
1806 //
1807 // If the HAL we are using has support for master volume or master mute,
1808 // then do not attenuate or mute during mixing (just leave the volume at 1.0
1809 // and the mute set to false).
1810 mMasterVolume = audioFlinger->masterVolume_l();
1811 mMasterMute = audioFlinger->masterMute_l();
1812 if (mOutput && mOutput->audioHwDev) {
1813 if (mOutput->audioHwDev->canSetMasterVolume()) {
1814 mMasterVolume = 1.0;
1815 }
1816
1817 if (mOutput->audioHwDev->canSetMasterMute()) {
1818 mMasterMute = false;
1819 }
Andy Hungc8fddf32018-08-08 18:32:37 -07001820 mIsMsdDevice = strcmp(
1821 mOutput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
Eric Laurent81784c32012-11-19 14:55:58 -08001822 }
1823
Glenn Kastendeca2ae2014-02-07 10:25:56 -08001824 readOutputParameters_l();
Eric Laurent81784c32012-11-19 14:55:58 -08001825
Andy Hungc8fddf32018-08-08 18:32:37 -07001826 // TODO: We may also match on address as well as device type for
1827 // AUDIO_DEVICE_OUT_BUS, AUDIO_DEVICE_OUT_ALL_A2DP, AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Dean Wheatleyf8726f02019-12-02 14:12:01 +11001828 if (type == MIXER || type == DIRECT || type == OFFLOAD) {
jiabin10d86fd2019-10-31 17:20:42 -07001829 // TODO: This property should be ensure that only contains one single device type.
1830 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
1831 "audio.timestamp.corrected_output_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07001832 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_OUT_BUS // turn on by default for MSD
1833 : AUDIO_DEVICE_NONE));
1834 }
1835
Eric Laurent223fd5c2014-11-11 13:43:36 -08001836 // ++ operator does not compile
Eric Laurent98e38192018-02-15 18:31:53 -08001837 for (audio_stream_type_t stream = AUDIO_STREAM_MIN; stream < AUDIO_STREAM_FOR_POLICY_CNT;
Eric Laurent81784c32012-11-19 14:55:58 -08001838 stream = (audio_stream_type_t) (stream + 1)) {
Eric Laurent98e38192018-02-15 18:31:53 -08001839 mStreamTypes[stream].volume = 0.0f;
Eric Laurent81784c32012-11-19 14:55:58 -08001840 mStreamTypes[stream].mute = mAudioFlinger->streamMute_l(stream);
1841 }
Eric Laurent98e38192018-02-15 18:31:53 -08001842 // Audio patch volume is always max
1843 mStreamTypes[AUDIO_STREAM_PATCH].volume = 1.0f;
1844 mStreamTypes[AUDIO_STREAM_PATCH].mute = false;
Eric Laurent81784c32012-11-19 14:55:58 -08001845}
1846
1847AudioFlinger::PlaybackThread::~PlaybackThread()
1848{
Glenn Kasten9e58b552013-01-18 15:09:48 -08001849 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung010a1a12014-03-13 13:57:33 -07001850 free(mSinkBuffer);
Andy Hung69aed5f2014-02-25 17:24:40 -08001851 free(mMixerBuffer);
Andy Hung98ef9782014-03-04 14:46:50 -08001852 free(mEffectBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08001853}
1854
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001855// Thread virtuals
1856
1857void AudioFlinger::PlaybackThread::onFirstRef()
Eric Laurent81784c32012-11-19 14:55:58 -08001858{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001859 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08001860}
1861
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001862// ThreadBase virtuals
1863void AudioFlinger::PlaybackThread::preExit()
1864{
1865 ALOGV(" preExit()");
1866 // FIXME this is using hard-coded strings but in the future, this functionality will be
1867 // converted to use audio HAL extensions required to support tunneling
1868 status_t result = mOutput->stream->setParameters(String8("exiting=1"));
1869 ALOGE_IF(result != OK, "Error when setting parameters on exit: %d", result);
1870}
1871
1872void AudioFlinger::PlaybackThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001873{
Eric Laurent81784c32012-11-19 14:55:58 -08001874 String8 result;
1875
Marco Nelissenb2208842014-02-07 14:00:50 -08001876 result.appendFormat(" Stream volumes in dB: ");
Eric Laurent81784c32012-11-19 14:55:58 -08001877 for (int i = 0; i < AUDIO_STREAM_CNT; ++i) {
1878 const stream_type_t *st = &mStreamTypes[i];
1879 if (i > 0) {
1880 result.appendFormat(", ");
1881 }
1882 result.appendFormat("%d:%.2g", i, 20.0 * log10(st->volume));
1883 if (st->mute) {
1884 result.append("M");
1885 }
1886 }
1887 result.append("\n");
1888 write(fd, result.string(), result.length());
1889 result.clear();
1890
Eric Laurent81784c32012-11-19 14:55:58 -08001891 // These values are "raw"; they will wrap around. See prepareTracks_l() for a better way.
1892 FastTrackUnderruns underruns = getFastTrackUnderruns(0);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001893 dprintf(fd, " Normal mixer raw underrun counters: partial=%u empty=%u\n",
Eric Laurent81784c32012-11-19 14:55:58 -08001894 underruns.mBitFields.mPartial, underruns.mBitFields.mEmpty);
Marco Nelissenb2208842014-02-07 14:00:50 -08001895
1896 size_t numtracks = mTracks.size();
1897 size_t numactive = mActiveTracks.size();
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001898 dprintf(fd, " %zu Tracks", numtracks);
Marco Nelissenb2208842014-02-07 14:00:50 -08001899 size_t numactiveseen = 0;
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001900 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08001901 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07001902 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001903 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001904 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08001905 for (size_t i = 0; i < numtracks; ++i) {
1906 sp<Track> track = mTracks[i];
1907 if (track != 0) {
1908 bool active = mActiveTracks.indexOf(track) >= 0;
1909 if (active) {
1910 numactiveseen++;
1911 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001912 result.append(prefix);
1913 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08001914 }
1915 }
1916 } else {
1917 result.append("\n");
1918 }
1919 if (numactiveseen != numactive) {
1920 // some tracks in the active list were not in the tracks list
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001921 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08001922 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001923 result.append(prefix);
Andy Hungf6ab58d2018-05-25 12:50:39 -07001924 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08001925 for (size_t i = 0; i < numactive; ++i) {
Andy Hungdae27702016-10-31 14:01:16 -07001926 sp<Track> track = mActiveTracks[i];
1927 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001928 result.append(prefix);
1929 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08001930 }
1931 }
1932 }
1933
1934 write(fd, result.string(), result.size());
Eric Laurent81784c32012-11-19 14:55:58 -08001935}
1936
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07001937void AudioFlinger::PlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08001938{
Mikhail Naganovdfb411f2018-09-11 13:39:56 -07001939 dprintf(fd, " Master mute: %s\n", mMasterMute ? "on" : "off");
jiabin245cdd92018-12-07 17:55:15 -08001940 if (mHapticChannelMask != AUDIO_CHANNEL_NONE) {
1941 dprintf(fd, " Haptic channel mask: %#x (%s)\n", mHapticChannelMask,
1942 channelMaskToString(mHapticChannelMask, true /* output */).c_str());
1943 }
Elliott Hughes87cebad2014-05-22 10:14:43 -07001944 dprintf(fd, " Normal frame count: %zu\n", mNormalFrameCount);
Elliott Hughes87cebad2014-05-22 10:14:43 -07001945 dprintf(fd, " Total writes: %d\n", mNumWrites);
1946 dprintf(fd, " Delayed writes: %d\n", mNumDelayedWrites);
1947 dprintf(fd, " Blocked in write: %s\n", mInWrite ? "yes" : "no");
1948 dprintf(fd, " Suspend count: %d\n", mSuspended);
1949 dprintf(fd, " Sink buffer : %p\n", mSinkBuffer);
1950 dprintf(fd, " Mixer buffer: %p\n", mMixerBuffer);
1951 dprintf(fd, " Effect buffer: %p\n", mEffectBuffer);
1952 dprintf(fd, " Fast track availMask=%#x\n", mFastTrackAvailMask);
Eric Laurent42537be2016-01-08 17:16:42 -08001953 dprintf(fd, " Standby delay ns=%lld\n", (long long)mStandbyDelayNs);
Glenn Kasten97b7b752014-09-28 13:04:24 -07001954 AudioStreamOut *output = mOutput;
1955 audio_output_flags_t flags = output != NULL ? output->flags : AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov913d06c2016-11-01 12:49:22 -07001956 dprintf(fd, " AudioStreamOut: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08001957 output, flags, toString(flags).c_str());
Andy Hungb54c8542016-09-21 12:55:15 -07001958 dprintf(fd, " Frames written: %lld\n", (long long)mFramesWritten);
1959 dprintf(fd, " Suspended frames: %lld\n", (long long)mSuspendedFrames);
1960 if (mPipeSink.get() != nullptr) {
1961 dprintf(fd, " PipeSink frames written: %lld\n", (long long)mPipeSink->framesWritten());
1962 }
1963 if (output != nullptr) {
1964 dprintf(fd, " Hal stream dump:\n");
1965 (void)output->stream->dump(fd);
1966 }
Eric Laurent81784c32012-11-19 14:55:58 -08001967}
1968
Eric Laurent81784c32012-11-19 14:55:58 -08001969// PlaybackThread::createTrack_l() must be called with AudioFlinger::mLock held
1970sp<AudioFlinger::PlaybackThread::Track> AudioFlinger::PlaybackThread::createTrack_l(
1971 const sp<AudioFlinger::Client>& client,
1972 audio_stream_type_t streamType,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07001973 const audio_attributes_t& attr,
Eric Laurent21da6472017-11-09 16:29:26 -08001974 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08001975 audio_format_t format,
1976 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08001977 size_t *pFrameCount,
Eric Laurent21da6472017-11-09 16:29:26 -08001978 size_t *pNotificationFrameCount,
1979 uint32_t notificationsPerBuffer,
1980 float speed,
Eric Laurent81784c32012-11-19 14:55:58 -08001981 const sp<IMemory>& sharedBuffer,
Glenn Kastend848eb42016-03-08 13:42:11 -08001982 audio_session_t sessionId,
Eric Laurent05067782016-06-01 18:27:28 -07001983 audio_output_flags_t *flags,
Eric Laurent09f1ed22019-04-24 17:45:17 -07001984 pid_t creatorPid,
Eric Laurent81784c32012-11-19 14:55:58 -08001985 pid_t tid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08001986 uid_t uid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08001987 status_t *status,
1988 audio_port_handle_t portId)
Eric Laurent81784c32012-11-19 14:55:58 -08001989{
Glenn Kasten74935e42013-12-19 08:56:45 -08001990 size_t frameCount = *pFrameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08001991 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08001992 sp<Track> track;
1993 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07001994 audio_output_flags_t outputFlags = mOutput->flags;
Eric Laurent21da6472017-11-09 16:29:26 -08001995 audio_output_flags_t requestedFlags = *flags;
Eric Laurent9b11c022018-06-06 19:19:22 -07001996 uint32_t sampleRate;
1997
1998 if (sharedBuffer != 0 && checkIMemory(sharedBuffer) != NO_ERROR) {
1999 lStatus = BAD_VALUE;
2000 goto Exit;
2001 }
Eric Laurent21da6472017-11-09 16:29:26 -08002002
2003 if (*pSampleRate == 0) {
2004 *pSampleRate = mSampleRate;
2005 }
Eric Laurent9b11c022018-06-06 19:19:22 -07002006 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07002007
2008 // special case for FAST flag considered OK if fast mixer is present
2009 if (hasFastMixer()) {
2010 outputFlags = (audio_output_flags_t)(outputFlags | AUDIO_OUTPUT_FLAG_FAST);
2011 }
2012
2013 // Check if requested flags are compatible with output stream flags
2014 if ((*flags & outputFlags) != *flags) {
2015 ALOGW("createTrack_l(): mismatch between requested flags (%08x) and output flags (%08x)",
2016 *flags, outputFlags);
2017 *flags = (audio_output_flags_t)(*flags & outputFlags);
2018 }
Eric Laurent81784c32012-11-19 14:55:58 -08002019
Eric Laurent81784c32012-11-19 14:55:58 -08002020 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07002021 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
Eric Laurent81784c32012-11-19 14:55:58 -08002022 if (
Eric Laurent81784c32012-11-19 14:55:58 -08002023 // PCM data
2024 audio_is_linear_pcm(format) &&
Andy Hung1f439e12015-05-19 12:57:41 -07002025 // TODO: extract as a data library function that checks that a computationally
2026 // expensive downmixer is not required: isFastOutputChannelConversion()
jiabin245cdd92018-12-07 17:55:15 -08002027 (channelMask == (mChannelMask | mHapticChannelMask) ||
Andy Hung1f439e12015-05-19 12:57:41 -07002028 mChannelMask != AUDIO_CHANNEL_OUT_STEREO ||
2029 (channelMask == AUDIO_CHANNEL_OUT_MONO
2030 /* && mChannelMask == AUDIO_CHANNEL_OUT_STEREO */)) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002031 // hardware sample rate
2032 (sampleRate == mSampleRate) &&
Eric Laurent81784c32012-11-19 14:55:58 -08002033 // normal mixer has an associated fast mixer
2034 hasFastMixer() &&
2035 // there are sufficient fast track slots available
2036 (mFastTrackAvailMask != 0)
2037 // FIXME test that MixerThread for this fast track has a capable output HAL
2038 // FIXME add a permission test also?
2039 ) {
Andy Hunge0a269a2016-03-23 15:13:42 -07002040 // static tracks can have any nonzero framecount, streaming tracks check against minimum.
2041 if (sharedBuffer == 0) {
Glenn Kasten03490092014-05-27 12:30:54 -07002042 // read the fast track multiplier property the first time it is needed
2043 int ok = pthread_once(&sFastTrackMultiplierOnce, sFastTrackMultiplierInit);
2044 if (ok != 0) {
2045 ALOGE("%s pthread_once failed: %d", __func__, ok);
2046 }
Andy Hunge0a269a2016-03-23 15:13:42 -07002047 frameCount = max(frameCount, mFrameCount * sFastTrackMultiplier); // incl framecount 0
Eric Laurent81784c32012-11-19 14:55:58 -08002048 }
Eric Laurent4c415062016-06-17 16:14:16 -07002049
2050 // check compatibility with audio effects.
2051 { // scope for mLock
2052 Mutex::Autolock _l(mLock);
Andy Hungd3bb0ad2016-10-11 17:16:43 -07002053 for (audio_session_t session : {
2054 AUDIO_SESSION_OUTPUT_STAGE,
2055 AUDIO_SESSION_OUTPUT_MIX,
2056 sessionId,
2057 }) {
2058 sp<EffectChain> chain = getEffectChain_l(session);
2059 if (chain.get() != nullptr) {
2060 audio_output_flags_t old = *flags;
2061 chain->checkOutputFlagCompatibility(flags);
2062 if (old != *flags) {
2063 ALOGV("AUDIO_OUTPUT_FLAGS denied by effect, session=%d old=%#x new=%#x",
2064 (int)session, (int)old, (int)*flags);
2065 }
Eric Laurent4c415062016-06-17 16:14:16 -07002066 }
2067 }
2068 }
Eric Laurent122f7e72016-06-29 11:53:29 -07002069 ALOGV_IF((*flags & AUDIO_OUTPUT_FLAG_FAST) != 0,
Eric Laurent4c415062016-06-17 16:14:16 -07002070 "AUDIO_OUTPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
2071 frameCount, mFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08002072 } else {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002073 ALOGV("AUDIO_OUTPUT_FLAG_FAST denied: sharedBuffer=%p frameCount=%zu "
2074 "mFrameCount=%zu format=%#x mFormat=%#x isLinear=%d channelMask=%#x "
Andy Hung6146c082014-03-18 11:56:15 -07002075 "sampleRate=%u mSampleRate=%u "
Eric Laurent81784c32012-11-19 14:55:58 -08002076 "hasFastMixer=%d tid=%d fastTrackAvailMask=%#x",
Glenn Kastend79072e2016-01-06 08:41:20 -08002077 sharedBuffer.get(), frameCount, mFrameCount, format, mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08002078 audio_is_linear_pcm(format),
2079 channelMask, sampleRate, mSampleRate, hasFastMixer(), tid, mFastTrackAvailMask);
Eric Laurent4c415062016-06-17 16:14:16 -07002080 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_FAST);
Andy Hung0e48d252015-01-26 11:43:15 -08002081 }
2082 }
Eric Laurent21da6472017-11-09 16:29:26 -08002083
2084 if (!audio_has_proportional_frames(format)) {
2085 if (sharedBuffer != 0) {
2086 // Same comment as below about ignoring frameCount parameter for set()
2087 frameCount = sharedBuffer->size();
2088 } else if (frameCount == 0) {
2089 frameCount = mNormalFrameCount;
2090 }
2091 if (notificationFrameCount != frameCount) {
2092 notificationFrameCount = frameCount;
2093 }
2094 } else if (sharedBuffer != 0) {
2095 // FIXME: Ensure client side memory buffers need
2096 // not have additional alignment beyond sample
2097 // (e.g. 16 bit stereo accessed as 32 bit frame).
2098 size_t alignment = audio_bytes_per_sample(format);
2099 if (alignment & 1) {
2100 // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
2101 alignment = 1;
2102 }
2103 uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2104 size_t frameSize = channelCount * audio_bytes_per_sample(format);
2105 if (channelCount > 1) {
2106 // More than 2 channels does not require stronger alignment than stereo
2107 alignment <<= 1;
2108 }
2109 if (((uintptr_t)sharedBuffer->pointer() & (alignment - 1)) != 0) {
2110 ALOGE("Invalid buffer alignment: address %p, channel count %u",
2111 sharedBuffer->pointer(), channelCount);
2112 lStatus = BAD_VALUE;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002113 goto Exit;
2114 }
Eric Laurent21da6472017-11-09 16:29:26 -08002115
2116 // When initializing a shared buffer AudioTrack via constructors,
2117 // there's no frameCount parameter.
2118 // But when initializing a shared buffer AudioTrack via set(),
2119 // there _is_ a frameCount parameter. We silently ignore it.
2120 frameCount = sharedBuffer->size() / frameSize;
2121 } else {
2122 size_t minFrameCount = 0;
2123 // For fast tracks we try to respect the application's request for notifications per buffer.
2124 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2125 if (notificationsPerBuffer > 0) {
2126 // Avoid possible arithmetic overflow during multiplication.
2127 if (notificationsPerBuffer > SIZE_MAX / mFrameCount) {
2128 ALOGE("Requested notificationPerBuffer=%u ignored for HAL frameCount=%zu",
2129 notificationsPerBuffer, mFrameCount);
2130 } else {
2131 minFrameCount = mFrameCount * notificationsPerBuffer;
2132 }
2133 }
2134 } else {
2135 // For normal PCM streaming tracks, update minimum frame count.
2136 // Buffer depth is forced to be at least 2 x the normal mixer frame count and
2137 // cover audio hardware latency.
2138 // This is probably too conservative, but legacy application code may depend on it.
2139 // If you change this calculation, also review the start threshold which is related.
2140 uint32_t latencyMs = latency_l();
2141 if (latencyMs == 0) {
2142 ALOGE("Error when retrieving output stream latency");
2143 lStatus = UNKNOWN_ERROR;
2144 goto Exit;
2145 }
2146
2147 minFrameCount = AudioSystem::calculateMinFrameCount(latencyMs, mNormalFrameCount,
2148 mSampleRate, sampleRate, speed /*, 0 mNotificationsPerBufferReq*/);
2149
Eric Laurent81784c32012-11-19 14:55:58 -08002150 }
Eric Laurent21da6472017-11-09 16:29:26 -08002151 if (frameCount < minFrameCount) {
Eric Laurent81784c32012-11-19 14:55:58 -08002152 frameCount = minFrameCount;
2153 }
Eric Laurent81784c32012-11-19 14:55:58 -08002154 }
Eric Laurent21da6472017-11-09 16:29:26 -08002155
2156 // Make sure that application is notified with sufficient margin before underrun.
2157 // The client can divide the AudioTrack buffer into sub-buffers,
2158 // and expresses its desire to server as the notification frame count.
2159 if (sharedBuffer == 0 && audio_is_linear_pcm(format)) {
2160 size_t maxNotificationFrames;
2161 if (*flags & AUDIO_OUTPUT_FLAG_FAST) {
2162 // notify every HAL buffer, regardless of the size of the track buffer
2163 maxNotificationFrames = mFrameCount;
2164 } else {
Andy Hungfa117802019-04-12 13:50:39 -07002165 // Triple buffer the notification period for a triple buffered mixer period;
2166 // otherwise, double buffering for the notification period is fine.
2167 //
2168 // TODO: This should be moved to AudioTrack to modify the notification period
2169 // on AudioTrack::setBufferSizeInFrames() changes.
2170 const int nBuffering =
2171 (uint64_t{frameCount} * mSampleRate)
2172 / (uint64_t{mNormalFrameCount} * sampleRate) == 3 ? 3 : 2;
2173
Eric Laurent21da6472017-11-09 16:29:26 -08002174 maxNotificationFrames = frameCount / nBuffering;
2175 // If client requested a fast track but this was denied, then use the smaller maximum.
2176 if (requestedFlags & AUDIO_OUTPUT_FLAG_FAST) {
2177 size_t maxNotificationFramesFastDenied = FMS_20 * sampleRate / 1000;
2178 if (maxNotificationFrames > maxNotificationFramesFastDenied) {
2179 maxNotificationFrames = maxNotificationFramesFastDenied;
2180 }
2181 }
2182 }
2183 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
2184 if (notificationFrameCount == 0) {
2185 ALOGD("Client defaulted notificationFrames to %zu for frameCount %zu",
2186 maxNotificationFrames, frameCount);
2187 } else {
2188 ALOGW("Client adjusted notificationFrames from %zu to %zu for frameCount %zu",
2189 notificationFrameCount, maxNotificationFrames, frameCount);
2190 }
2191 notificationFrameCount = maxNotificationFrames;
2192 }
2193 }
2194
Glenn Kasten74935e42013-12-19 08:56:45 -08002195 *pFrameCount = frameCount;
Eric Laurent21da6472017-11-09 16:29:26 -08002196 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08002197
Glenn Kastenc3df8382014-03-13 15:05:25 -07002198 switch (mType) {
2199
2200 case DIRECT:
Phil Burkfdb3c072016-02-09 10:47:02 -08002201 if (audio_is_linear_pcm(format)) { // TODO maybe use audio_has_proportional_frames()?
Eric Laurent81784c32012-11-19 14:55:58 -08002202 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002203 ALOGE("createTrack_l() Bad parameter: sampleRate %u format %#x, channelMask 0x%08x "
2204 "for output %p with format %#x",
Eric Laurent81784c32012-11-19 14:55:58 -08002205 sampleRate, format, channelMask, mOutput, mFormat);
2206 lStatus = BAD_VALUE;
2207 goto Exit;
2208 }
2209 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002210 break;
2211
2212 case OFFLOAD:
Eric Laurentbfb1b832013-01-07 09:53:42 -08002213 if (sampleRate != mSampleRate || format != mFormat || channelMask != mChannelMask) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002214 ALOGE("createTrack_l() Bad parameter: sampleRate %d format %#x, channelMask 0x%08x \""
2215 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002216 sampleRate, format, channelMask, mOutput, mFormat);
2217 lStatus = BAD_VALUE;
2218 goto Exit;
2219 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002220 break;
2221
2222 default:
Glenn Kasten993fa062014-05-02 11:14:34 -07002223 if (!audio_is_linear_pcm(format)) {
Glenn Kastencac3daa2014-02-07 09:47:14 -08002224 ALOGE("createTrack_l() Bad parameter: format %#x \""
2225 "for output %p with format %#x",
Eric Laurentbfb1b832013-01-07 09:53:42 -08002226 format, mOutput, mFormat);
2227 lStatus = BAD_VALUE;
2228 goto Exit;
2229 }
Andy Hungcd044842014-08-07 11:04:34 -07002230 if (sampleRate > mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
Eric Laurent81784c32012-11-19 14:55:58 -08002231 ALOGE("Sample rate out of range: %u mSampleRate %u", sampleRate, mSampleRate);
2232 lStatus = BAD_VALUE;
2233 goto Exit;
2234 }
Glenn Kastenc3df8382014-03-13 15:05:25 -07002235 break;
2236
Eric Laurent81784c32012-11-19 14:55:58 -08002237 }
2238
2239 lStatus = initCheck();
2240 if (lStatus != NO_ERROR) {
Glenn Kasten15e57982013-09-24 11:52:37 -07002241 ALOGE("createTrack_l() audio driver not initialized");
Eric Laurent81784c32012-11-19 14:55:58 -08002242 goto Exit;
2243 }
2244
2245 { // scope for mLock
2246 Mutex::Autolock _l(mLock);
2247
2248 // all tracks in same audio session must share the same routing strategy otherwise
2249 // conflicts will happen when tracks are moved from one output to another by audio policy
2250 // manager
2251 uint32_t strategy = AudioSystem::getStrategyForStream(streamType);
2252 for (size_t i = 0; i < mTracks.size(); ++i) {
2253 sp<Track> t = mTracks[i];
Eric Laurent83b88082014-06-20 18:31:16 -07002254 if (t != 0 && t->isExternalTrack()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002255 uint32_t actual = AudioSystem::getStrategyForStream(t->streamType());
2256 if (sessionId == t->sessionId() && strategy != actual) {
2257 ALOGE("createTrack_l() mismatched strategy; expected %u but found %u",
2258 strategy, actual);
2259 lStatus = BAD_VALUE;
2260 goto Exit;
2261 }
2262 }
2263 }
2264
Kevin Rocard1f564ac2018-03-29 13:53:10 -07002265 track = new Track(this, client, streamType, attr, sampleRate, format,
Andy Hung8fe68032017-06-05 16:17:51 -07002266 channelMask, frameCount,
2267 nullptr /* buffer */, (size_t)0 /* bufferSize */, sharedBuffer,
Eric Laurent09f1ed22019-04-24 17:45:17 -07002268 sessionId, creatorPid, uid, *flags, TrackBase::TYPE_DEFAULT, portId);
Glenn Kasten03003332013-08-06 15:40:54 -07002269
Glenn Kasten03003332013-08-06 15:40:54 -07002270 lStatus = track != 0 ? track->initCheck() : (status_t) NO_MEMORY;
2271 if (lStatus != NO_ERROR) {
Glenn Kasten0cde0762014-01-16 15:06:36 -08002272 ALOGE("createTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08002273 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08002274 goto Exit;
2275 }
2276 mTracks.add(track);
2277
2278 sp<EffectChain> chain = getEffectChain_l(sessionId);
2279 if (chain != 0) {
2280 ALOGV("createTrack_l() setting main buffer %p", chain->inBuffer());
2281 track->setMainBuffer(chain->inBuffer());
2282 chain->setStrategy(AudioSystem::getStrategyForStream(track->streamType()));
2283 chain->incTrackCnt();
2284 }
2285
Eric Laurent05067782016-06-01 18:27:28 -07002286 if ((*flags & AUDIO_OUTPUT_FLAG_FAST) && (tid != -1)) {
Eric Laurent81784c32012-11-19 14:55:58 -08002287 pid_t callingPid = IPCThreadState::self()->getCallingPid();
2288 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
2289 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07002290 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08002291 }
2292 }
2293
2294 lStatus = NO_ERROR;
2295
2296Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07002297 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08002298 return track;
2299}
2300
Andy Hung1bc088a2018-02-09 15:57:31 -08002301template<typename T>
Andy Hung1bc088a2018-02-09 15:57:31 -08002302ssize_t AudioFlinger::PlaybackThread::Tracks<T>::remove(const sp<T> &track)
2303{
Andy Hungc0691382018-09-12 18:01:57 -07002304 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08002305 const ssize_t index = mTracks.remove(track);
2306 if (index >= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07002307 if (mSaveDeletedTrackIds) {
Andy Hung1bc088a2018-02-09 15:57:31 -08002308 // We can't directly access mAudioMixer since the caller may be outside of threadLoop.
Andy Hungc0691382018-09-12 18:01:57 -07002309 // Instead, we add to mDeletedTrackIds which is solely used for mAudioMixer update,
Andy Hung1bc088a2018-02-09 15:57:31 -08002310 // to be handled when MixerThread::prepareTracks_l() next changes mAudioMixer.
Andy Hungc0691382018-09-12 18:01:57 -07002311 mDeletedTrackIds.emplace(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08002312 }
Andy Hung1bc088a2018-02-09 15:57:31 -08002313 }
2314 return index;
2315}
2316
Eric Laurent81784c32012-11-19 14:55:58 -08002317uint32_t AudioFlinger::PlaybackThread::correctLatency_l(uint32_t latency) const
2318{
2319 return latency;
2320}
2321
2322uint32_t AudioFlinger::PlaybackThread::latency() const
2323{
2324 Mutex::Autolock _l(mLock);
2325 return latency_l();
2326}
2327uint32_t AudioFlinger::PlaybackThread::latency_l() const
2328{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002329 uint32_t latency;
2330 if (initCheck() == NO_ERROR && mOutput->stream->getLatency(&latency) == OK) {
2331 return correctLatency_l(latency);
Eric Laurent81784c32012-11-19 14:55:58 -08002332 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002333 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08002334}
2335
2336void AudioFlinger::PlaybackThread::setMasterVolume(float value)
2337{
2338 Mutex::Autolock _l(mLock);
2339 // Don't apply master volume in SW if our HAL can do it for us.
2340 if (mOutput && mOutput->audioHwDev &&
2341 mOutput->audioHwDev->canSetMasterVolume()) {
2342 mMasterVolume = 1.0;
2343 } else {
2344 mMasterVolume = value;
2345 }
2346}
2347
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002348void AudioFlinger::PlaybackThread::setMasterBalance(float balance)
2349{
2350 mMasterBalance.store(balance);
2351}
2352
Eric Laurent81784c32012-11-19 14:55:58 -08002353void AudioFlinger::PlaybackThread::setMasterMute(bool muted)
2354{
Eric Laurent6acd1d42017-01-04 14:23:29 -08002355 if (isDuplicating()) {
2356 return;
2357 }
Eric Laurent81784c32012-11-19 14:55:58 -08002358 Mutex::Autolock _l(mLock);
2359 // Don't apply master mute in SW if our HAL can do it for us.
2360 if (mOutput && mOutput->audioHwDev &&
2361 mOutput->audioHwDev->canSetMasterMute()) {
2362 mMasterMute = false;
2363 } else {
2364 mMasterMute = muted;
2365 }
2366}
2367
2368void AudioFlinger::PlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
2369{
2370 Mutex::Autolock _l(mLock);
2371 mStreamTypes[stream].volume = value;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002372 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002373}
2374
2375void AudioFlinger::PlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
2376{
2377 Mutex::Autolock _l(mLock);
2378 mStreamTypes[stream].mute = muted;
Eric Laurentede6c3b2013-09-19 14:37:46 -07002379 broadcast_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002380}
2381
2382float AudioFlinger::PlaybackThread::streamVolume(audio_stream_type_t stream) const
2383{
2384 Mutex::Autolock _l(mLock);
2385 return mStreamTypes[stream].volume;
2386}
2387
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09002388void AudioFlinger::PlaybackThread::setVolumeForOutput_l(float left, float right) const
2389{
2390 mOutput->stream->setVolume(left, right);
2391}
2392
Eric Laurent81784c32012-11-19 14:55:58 -08002393// addTrack_l() must be called with ThreadBase::mLock held
2394status_t AudioFlinger::PlaybackThread::addTrack_l(const sp<Track>& track)
2395{
2396 status_t status = ALREADY_EXISTS;
2397
Eric Laurent81784c32012-11-19 14:55:58 -08002398 if (mActiveTracks.indexOf(track) < 0) {
2399 // the track is newly added, make sure it fills up all its
2400 // buffers before playing. This is to ensure the client will
2401 // effectively get the latency it requested.
Eric Laurent83b88082014-06-20 18:31:16 -07002402 if (track->isExternalTrack()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002403 TrackBase::track_state state = track->mState;
2404 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002405 status = AudioSystem::startOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002406 mLock.lock();
2407 // abort track was stopped/paused while we released the lock
2408 if (state != track->mState) {
2409 if (status == NO_ERROR) {
2410 mLock.unlock();
Eric Laurentd7fe0862018-07-14 16:48:01 -07002411 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002412 mLock.lock();
2413 }
2414 return INVALID_OPERATION;
2415 }
2416 // abort if start is rejected by audio policy manager
2417 if (status != NO_ERROR) {
2418 return PERMISSION_DENIED;
2419 }
2420#ifdef ADD_BATTERY_DATA
2421 // to track the speaker usage
2422 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStart);
2423#endif
Eric Laurent09f1ed22019-04-24 17:45:17 -07002424 sendIoConfigEvent_l(AUDIO_CLIENT_STARTED, track->creatorPid(), track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08002425 }
2426
Eric Laurent51716182016-02-29 18:00:56 -08002427 // set retry count for buffer fill
2428 if (track->isOffloaded()) {
Eric Laurente93cc032016-05-05 10:15:10 -07002429 if (track->isStopping_1()) {
2430 track->mRetryCount = kMaxTrackStopRetriesOffload;
2431 } else {
2432 track->mRetryCount = kMaxTrackStartupRetriesOffload;
2433 }
2434 track->mFillingUpStatus = mStandby ? Track::FS_FILLING : Track::FS_FILLED;
Eric Laurent51716182016-02-29 18:00:56 -08002435 } else {
2436 track->mRetryCount = kMaxTrackStartupRetries;
Eric Laurente93cc032016-05-05 10:15:10 -07002437 track->mFillingUpStatus =
2438 track->sharedBuffer() != 0 ? Track::FS_FILLED : Track::FS_FILLING;
Eric Laurent51716182016-02-29 18:00:56 -08002439 }
2440
jiabin245cdd92018-12-07 17:55:15 -08002441 if ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
2442 && mHapticChannelMask != AUDIO_CHANNEL_NONE) {
jiabin57303cc2018-12-18 15:45:57 -08002443 // Unlock due to VibratorService will lock for this call and will
2444 // call Tracks.mute/unmute which also require thread's lock.
2445 mLock.unlock();
2446 const int intensity = AudioFlinger::onExternalVibrationStart(
2447 track->getExternalVibration());
2448 mLock.lock();
jiabinbf6b0ec2019-02-12 12:30:12 -08002449 track->setHapticIntensity(static_cast<AudioMixer::haptic_intensity_t>(intensity));
jiabin57303cc2018-12-18 15:45:57 -08002450 // Haptic playback should be enabled by vibrator service.
2451 if (track->getHapticPlaybackEnabled()) {
2452 // Disable haptic playback of all active track to ensure only
2453 // one track playing haptic if current track should play haptic.
2454 for (const auto &t : mActiveTracks) {
2455 t->setHapticPlaybackEnabled(false);
2456 }
jiabin245cdd92018-12-07 17:55:15 -08002457 }
jiabin245cdd92018-12-07 17:55:15 -08002458 }
2459
Eric Laurent81784c32012-11-19 14:55:58 -08002460 track->mResetDone = false;
2461 track->mPresentationCompleteFrames = 0;
2462 mActiveTracks.add(track);
Eric Laurentd0107bc2013-06-11 14:38:48 -07002463 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2464 if (chain != 0) {
2465 ALOGV("addTrack_l() starting track on chain %p for session %d", chain.get(),
2466 track->sessionId());
2467 chain->incActiveTrackCnt();
Eric Laurent81784c32012-11-19 14:55:58 -08002468 }
2469
2470 status = NO_ERROR;
2471 }
2472
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08002473 onAddNewTrack_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002474 return status;
2475}
2476
Eric Laurentbfb1b832013-01-07 09:53:42 -08002477bool AudioFlinger::PlaybackThread::destroyTrack_l(const sp<Track>& track)
Eric Laurent81784c32012-11-19 14:55:58 -08002478{
Eric Laurentbfb1b832013-01-07 09:53:42 -08002479 track->terminate();
Eric Laurent81784c32012-11-19 14:55:58 -08002480 // active tracks are removed by threadLoop()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002481 bool trackActive = (mActiveTracks.indexOf(track) >= 0);
2482 track->mState = TrackBase::STOPPED;
2483 if (!trackActive) {
Eric Laurent81784c32012-11-19 14:55:58 -08002484 removeTrack_l(track);
Eric Laurentab5cdba2014-06-09 17:22:27 -07002485 } else if (track->isFastTrack() || track->isOffloaded() || track->isDirect()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002486 track->mState = TrackBase::STOPPING_1;
Eric Laurent81784c32012-11-19 14:55:58 -08002487 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08002488
2489 return trackActive;
Eric Laurent81784c32012-11-19 14:55:58 -08002490}
2491
2492void AudioFlinger::PlaybackThread::removeTrack_l(const sp<Track>& track)
2493{
2494 track->triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
Andy Hung2148bf02016-11-28 19:01:02 -08002495
Andy Hung2c6c3bb2017-06-16 14:01:45 -07002496 String8 result;
2497 track->appendDump(result, false /* active */);
2498 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
Andy Hung2148bf02016-11-28 19:01:02 -08002499
Eric Laurent81784c32012-11-19 14:55:58 -08002500 mTracks.remove(track);
Eric Laurent81784c32012-11-19 14:55:58 -08002501 if (track->isFastTrack()) {
2502 int index = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07002503 ALOG_ASSERT(0 < index && index < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08002504 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << index)));
2505 mFastTrackAvailMask |= 1 << index;
2506 // redundant as track is about to be destroyed, for dumpsys only
2507 track->mFastIndex = -1;
2508 }
2509 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
2510 if (chain != 0) {
2511 chain->decTrackCnt();
2512 }
2513}
2514
2515String8 AudioFlinger::PlaybackThread::getParameters(const String8& keys)
2516{
Eric Laurent81784c32012-11-19 14:55:58 -08002517 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002518 String8 out_s8;
2519 if (initCheck() == NO_ERROR && mOutput->stream->getParameters(keys, &out_s8) == OK) {
2520 return out_s8;
Eric Laurent81784c32012-11-19 14:55:58 -08002521 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002522 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08002523}
2524
Mikhail Naganovac917ac2018-11-28 14:03:52 -08002525status_t AudioFlinger::DirectOutputThread::selectPresentation(int presentationId, int programId) {
2526 Mutex::Autolock _l(mLock);
2527 if (mOutput == nullptr || mOutput->stream == nullptr) {
2528 return NO_INIT;
2529 }
2530 return mOutput->stream->selectPresentation(presentationId, programId);
2531}
2532
Eric Laurent09f1ed22019-04-24 17:45:17 -07002533void AudioFlinger::PlaybackThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
2534 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002535 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
2536 ALOGV("PlaybackThread::ioConfigChanged, thread %p, event %d", this, event);
Eric Laurent81784c32012-11-19 14:55:58 -08002537
Eric Laurent73e26b62015-04-27 16:55:58 -07002538 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08002539
2540 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07002541 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002542 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07002543 case AUDIO_OUTPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07002544 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07002545 desc->mChannelMask = mChannelMask;
2546 desc->mSamplingRate = mSampleRate;
2547 desc->mFormat = mFormat;
2548 desc->mFrameCount = mNormalFrameCount; // FIXME see
Eric Laurent81784c32012-11-19 14:55:58 -08002549 // AudioFlinger::frameCount(audio_io_handle_t)
Glenn Kasten4a8308b2016-04-18 14:10:01 -07002550 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07002551 desc->mLatency = latency_l();
Eric Laurent81784c32012-11-19 14:55:58 -08002552 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07002553 case AUDIO_CLIENT_STARTED:
2554 desc->mPatch = mPatch;
2555 desc->mPortId = portId;
2556 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07002557 case AUDIO_OUTPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08002558 default:
2559 break;
2560 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002561 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08002562}
2563
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002564void AudioFlinger::PlaybackThread::onWriteReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002565{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002566 mCallbackThread->resetWriteBlocked();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002567}
2568
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002569void AudioFlinger::PlaybackThread::onDrainReady()
Eric Laurentbfb1b832013-01-07 09:53:42 -08002570{
Eric Laurent3b4529e2013-09-05 18:09:19 -07002571 mCallbackThread->resetDraining();
Eric Laurentbfb1b832013-01-07 09:53:42 -08002572}
2573
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002574void AudioFlinger::PlaybackThread::onError()
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002575{
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07002576 mCallbackThread->setAsyncError();
2577}
2578
Eric Laurent3b4529e2013-09-05 18:09:19 -07002579void AudioFlinger::PlaybackThread::resetWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002580{
2581 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002582 // reject out of sequence requests
2583 if ((mWriteAckSequence & 1) && (sequence == mWriteAckSequence)) {
2584 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002585 mWaitWorkCV.signal();
2586 }
2587}
2588
Eric Laurent3b4529e2013-09-05 18:09:19 -07002589void AudioFlinger::PlaybackThread::resetDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08002590{
2591 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002592 // reject out of sequence requests
2593 if ((mDrainSequence & 1) && (sequence == mDrainSequence)) {
Andy Hungf3234512018-07-03 14:51:47 -07002594 // Register discontinuity when HW drain is completed because that can cause
2595 // the timestamp frame position to reset to 0 for direct and offload threads.
2596 // (Out of sequence requests are ignored, since the discontinuity would be handled
2597 // elsewhere, e.g. in flush).
2598 mTimestampVerifier.discontinuity();
Eric Laurent3b4529e2013-09-05 18:09:19 -07002599 mDrainSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002600 mWaitWorkCV.signal();
2601 }
2602}
2603
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002604void AudioFlinger::PlaybackThread::readOutputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08002605{
Glenn Kastenadad3d72014-02-21 14:51:43 -08002606 // unfortunately we have no way of recovering from errors here, hence the LOG_ALWAYS_FATAL
Phil Burkca5e6142015-07-14 09:42:29 -07002607 mSampleRate = mOutput->getSampleRate();
2608 mChannelMask = mOutput->getChannelMask();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002609 if (!audio_is_output_channel(mChannelMask)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002610 LOG_ALWAYS_FATAL("HAL channel mask %#x not valid for output", mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002611 }
Andy Hung9a592762014-07-21 21:56:01 -07002612 if ((mType == MIXER || mType == DUPLICATING)
2613 && !isValidPcmSinkChannelMask(mChannelMask)) {
2614 LOG_ALWAYS_FATAL("HAL channel mask %#x not supported for mixed output",
2615 mChannelMask);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002616 }
Andy Hunge5412692014-05-16 11:25:07 -07002617 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002618 mBalance.setChannelMask(mChannelMask);
Phil Burkca5e6142015-07-14 09:42:29 -07002619
2620 // Get actual HAL format.
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002621 status_t result = mOutput->stream->getFormat(&mHALFormat);
2622 LOG_ALWAYS_FATAL_IF(result != OK, "Error when retrieving output stream format: %d", result);
Phil Burkca5e6142015-07-14 09:42:29 -07002623 // Get format from the shim, which will be different than the HAL format
2624 // if playing compressed audio over HDMI passthrough.
2625 mFormat = mOutput->getFormat();
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002626 if (!audio_is_valid_format(mFormat)) {
Glenn Kastenadad3d72014-02-21 14:51:43 -08002627 LOG_ALWAYS_FATAL("HAL format %#x not valid for output", mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002628 }
Andy Hung6146c082014-03-18 11:56:15 -07002629 if ((mType == MIXER || mType == DUPLICATING)
2630 && !isValidPcmSinkFormat(mFormat)) {
2631 LOG_FATAL("HAL format %#x not supported for mixed output",
2632 mFormat);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -07002633 }
Phil Burk062e67a2015-02-11 13:40:50 -08002634 mFrameSize = mOutput->getFrameSize();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002635 result = mOutput->stream->getBufferSize(&mBufferSize);
2636 LOG_ALWAYS_FATAL_IF(result != OK,
2637 "Error when retrieving output stream buffer size: %d", result);
Glenn Kasten70949c42013-08-06 07:40:12 -07002638 mFrameCount = mBufferSize / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002639 if (mFrameCount & 15) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002640 ALOGW("HAL output buffer size is %zu frames but AudioMixer requires multiples of 16 frames",
Eric Laurent81784c32012-11-19 14:55:58 -08002641 mFrameCount);
2642 }
2643
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002644 if (mOutput->flags & AUDIO_OUTPUT_FLAG_NON_BLOCKING) {
2645 if (mOutput->stream->setCallback(this) == OK) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002646 mUseAsyncWrite = true;
Eric Laurent4de95592013-09-26 15:28:21 -07002647 mCallbackThread = new AudioFlinger::AsyncCallbackThread(this);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002648 }
2649 }
2650
Eric Laurentd1f69b02014-12-15 14:33:13 -08002651 mHwSupportsPause = false;
2652 if (mOutput->flags & AUDIO_OUTPUT_FLAG_DIRECT) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002653 bool supportsPause = false, supportsResume = false;
2654 if (mOutput->stream->supportsPauseAndResume(&supportsPause, &supportsResume) == OK) {
2655 if (supportsPause && supportsResume) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002656 mHwSupportsPause = true;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002657 } else if (supportsPause) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08002658 ALOGW("direct output implements pause but not resume");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002659 } else if (supportsResume) {
2660 ALOGW("direct output implements resume but not pause");
Eric Laurentd1f69b02014-12-15 14:33:13 -08002661 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002662 }
2663 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07002664 if (!mHwSupportsPause && mOutput->flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) {
2665 LOG_ALWAYS_FATAL("HW_AV_SYNC requested but HAL does not implement pause and resume");
2666 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08002667
Andy Hungfbfc3952015-01-15 13:33:51 -08002668 if (mType == DUPLICATING && mMixerBufferEnabled && mEffectBufferEnabled) {
2669 // For best precision, we use float instead of the associated output
2670 // device format (typically PCM 16 bit).
2671
2672 mFormat = AUDIO_FORMAT_PCM_FLOAT;
2673 mFrameSize = mChannelCount * audio_bytes_per_sample(mFormat);
2674 mBufferSize = mFrameSize * mFrameCount;
2675
2676 // TODO: We currently use the associated output device channel mask and sample rate.
2677 // (1) Perhaps use the ORed channel mask of all downstream MixerThreads
2678 // (if a valid mask) to avoid premature downmix.
2679 // (2) Perhaps use the maximum sample rate of all downstream MixerThreads
2680 // instead of the output device sample rate to avoid loss of high frequency information.
2681 // This may need to be updated as MixerThread/OutputTracks are added and not here.
2682 }
2683
Andy Hung09a50072014-02-27 14:30:47 -08002684 // Calculate size of normal sink buffer relative to the HAL output buffer size
Eric Laurent81784c32012-11-19 14:55:58 -08002685 double multiplier = 1.0;
2686 if (mType == MIXER && (kUseFastMixer == FastMixer_Static ||
2687 kUseFastMixer == FastMixer_Dynamic)) {
Andy Hung09a50072014-02-27 14:30:47 -08002688 size_t minNormalFrameCount = (kMinNormalSinkBufferSizeMs * mSampleRate) / 1000;
2689 size_t maxNormalFrameCount = (kMaxNormalSinkBufferSizeMs * mSampleRate) / 1000;
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002690
Eric Laurent81784c32012-11-19 14:55:58 -08002691 // round up minimum and round down maximum to nearest 16 frames to satisfy AudioMixer
2692 minNormalFrameCount = (minNormalFrameCount + 15) & ~15;
2693 maxNormalFrameCount = maxNormalFrameCount & ~15;
2694 if (maxNormalFrameCount < minNormalFrameCount) {
2695 maxNormalFrameCount = minNormalFrameCount;
2696 }
2697 multiplier = (double) minNormalFrameCount / (double) mFrameCount;
2698 if (multiplier <= 1.0) {
2699 multiplier = 1.0;
2700 } else if (multiplier <= 2.0) {
2701 if (2 * mFrameCount <= maxNormalFrameCount) {
2702 multiplier = 2.0;
2703 } else {
2704 multiplier = (double) maxNormalFrameCount / (double) mFrameCount;
2705 }
2706 } else {
Haynes Mathew George227a14b2016-05-09 12:45:48 -07002707 multiplier = floor(multiplier);
Eric Laurent81784c32012-11-19 14:55:58 -08002708 }
2709 }
2710 mNormalFrameCount = multiplier * mFrameCount;
2711 // round up to nearest 16 frames to satisfy AudioMixer
Eric Laurentab5cdba2014-06-09 17:22:27 -07002712 if (mType == MIXER || mType == DUPLICATING) {
2713 mNormalFrameCount = (mNormalFrameCount + 15) & ~15;
2714 }
Glenn Kastenc42e9b42016-03-21 11:35:03 -07002715 ALOGI("HAL output buffer size %zu frames, normal sink buffer size %zu frames", mFrameCount,
Eric Laurent81784c32012-11-19 14:55:58 -08002716 mNormalFrameCount);
2717
Andy Hung08fb1742015-05-31 23:22:10 -07002718 // Check if we want to throttle the processing to no more than 2x normal rate
2719 mThreadThrottle = property_get_bool("af.thread.throttle", true /* default_value */);
Andy Hung40eb1a12015-06-18 13:42:02 -07002720 mThreadThrottleTimeMs = 0;
2721 mThreadThrottleEndMs = 0;
Andy Hung08fb1742015-05-31 23:22:10 -07002722 mHalfBufferMs = mNormalFrameCount * 1000 / (2 * mSampleRate);
2723
Andy Hung010a1a12014-03-13 13:57:33 -07002724 // mSinkBuffer is the sink buffer. Size is always multiple-of-16 frames.
2725 // Originally this was int16_t[] array, need to remove legacy implications.
2726 free(mSinkBuffer);
2727 mSinkBuffer = NULL;
Andy Hung5b10a202014-03-13 13:59:29 -07002728 // For sink buffer size, we use the frame size from the downstream sink to avoid problems
2729 // with non PCM formats for compressed music, e.g. AAC, and Offload threads.
2730 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
Andy Hung010a1a12014-03-13 13:57:33 -07002731 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08002732
Andy Hung69aed5f2014-02-25 17:24:40 -08002733 // We resize the mMixerBuffer according to the requirements of the sink buffer which
2734 // drives the output.
2735 free(mMixerBuffer);
2736 mMixerBuffer = NULL;
2737 if (mMixerBufferEnabled) {
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01002738 mMixerBufferFormat = AUDIO_FORMAT_PCM_FLOAT; // no longer valid: AUDIO_FORMAT_PCM_16_BIT.
Andy Hung69aed5f2014-02-25 17:24:40 -08002739 mMixerBufferSize = mNormalFrameCount * mChannelCount
2740 * audio_bytes_per_sample(mMixerBufferFormat);
2741 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
2742 }
Andy Hung98ef9782014-03-04 14:46:50 -08002743 free(mEffectBuffer);
2744 mEffectBuffer = NULL;
2745 if (mEffectBufferEnabled) {
rago94a1ee82017-07-21 15:11:02 -07002746 mEffectBufferFormat = EFFECT_BUFFER_FORMAT;
Andy Hung98ef9782014-03-04 14:46:50 -08002747 mEffectBufferSize = mNormalFrameCount * mChannelCount
2748 * audio_bytes_per_sample(mEffectBufferFormat);
2749 (void)posix_memalign(&mEffectBuffer, 32, mEffectBufferSize);
2750 }
Andy Hung69aed5f2014-02-25 17:24:40 -08002751
jiabin245cdd92018-12-07 17:55:15 -08002752 mHapticChannelMask = mChannelMask & AUDIO_CHANNEL_HAPTIC_ALL;
2753 mChannelMask &= ~mHapticChannelMask;
2754 mHapticChannelCount = audio_channel_count_from_out_mask(mHapticChannelMask);
2755 mChannelCount -= mHapticChannelCount;
2756
Eric Laurent81784c32012-11-19 14:55:58 -08002757 // force reconfiguration of effect chains and engines to take new buffer size and audio
2758 // parameters into account
Glenn Kastendeca2ae2014-02-07 10:25:56 -08002759 // Note that mLock is not held when readOutputParameters_l() is called from the constructor
Eric Laurent81784c32012-11-19 14:55:58 -08002760 // but in this case nothing is done below as no audio sessions have effect yet so it doesn't
2761 // matter.
2762 // create a copy of mEffectChains as calling moveEffectChain_l() can reorder some effect chains
2763 Vector< sp<EffectChain> > effectChains = mEffectChains;
2764 for (size_t i = 0; i < effectChains.size(); i ++) {
Eric Laurent6c796322019-04-09 14:13:17 -07002765 mAudioFlinger->moveEffectChain_l(effectChains[i]->sessionId(),
2766 this/* srcThread */, this/* dstThread */);
Eric Laurent81784c32012-11-19 14:55:58 -08002767 }
2768}
2769
Kevin Rocard069c2712018-03-29 19:09:14 -07002770void AudioFlinger::PlaybackThread::updateMetadata_l()
2771{
Kevin Rocard12381092018-04-11 09:19:59 -07002772 if (mOutput == nullptr || mOutput->stream == nullptr ) {
2773 return; // That should not happen
2774 }
2775 bool hasChanged = mActiveTracks.readAndClearHasChanged();
2776 for (const sp<Track> &track : mActiveTracks) {
2777 // Do not short-circuit as all hasChanged states must be reset
2778 // as all the metadata are going to be sent
2779 hasChanged |= track->readAndClearHasChanged();
2780 }
2781 if (!hasChanged) {
2782 return; // nothing to do
Kevin Rocard069c2712018-03-29 19:09:14 -07002783 }
2784 StreamOutHalInterface::SourceMetadata metadata;
Kevin Rocard12381092018-04-11 09:19:59 -07002785 auto backInserter = std::back_inserter(metadata.tracks);
Kevin Rocard069c2712018-03-29 19:09:14 -07002786 for (const sp<Track> &track : mActiveTracks) {
2787 // No track is invalid as this is called after prepareTrack_l in the same critical section
Kevin Rocard12381092018-04-11 09:19:59 -07002788 track->copyMetadataTo(backInserter);
Kevin Rocard069c2712018-03-29 19:09:14 -07002789 }
Kevin Rocard12381092018-04-11 09:19:59 -07002790 sendMetadataToBackend_l(metadata);
Kevin Rocard80ee2722018-04-11 15:53:48 +00002791}
Kevin Rocardc86a7f72018-04-03 09:00:09 -07002792
Kevin Rocard12381092018-04-11 09:19:59 -07002793void AudioFlinger::PlaybackThread::sendMetadataToBackend_l(
2794 const StreamOutHalInterface::SourceMetadata& metadata)
2795{
2796 mOutput->stream->updateSourceMetadata(metadata);
2797};
2798
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002799status_t AudioFlinger::PlaybackThread::getRenderPosition(uint32_t *halFrames, uint32_t *dspFrames)
Eric Laurent81784c32012-11-19 14:55:58 -08002800{
2801 if (halFrames == NULL || dspFrames == NULL) {
2802 return BAD_VALUE;
2803 }
2804 Mutex::Autolock _l(mLock);
2805 if (initCheck() != NO_ERROR) {
2806 return INVALID_OPERATION;
2807 }
Andy Hung818e7a32016-02-16 18:08:07 -08002808 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08002809 *halFrames = framesWritten;
2810
2811 if (isSuspended()) {
2812 // return an estimation of rendered frames when the output is suspended
2813 size_t latencyFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08002814 *dspFrames = (uint32_t)
2815 (framesWritten >= (int64_t)latencyFrames ? framesWritten - latencyFrames : 0);
Eric Laurent81784c32012-11-19 14:55:58 -08002816 return NO_ERROR;
2817 } else {
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002818 status_t status;
2819 uint32_t frames;
Phil Burk062e67a2015-02-11 13:40:50 -08002820 status = mOutput->getRenderPosition(&frames);
Kévin PETIT377b2ec2014-02-03 12:35:36 +00002821 *dspFrames = (size_t)frames;
2822 return status;
Eric Laurent81784c32012-11-19 14:55:58 -08002823 }
2824}
2825
Glenn Kastend848eb42016-03-08 13:42:11 -08002826uint32_t AudioFlinger::PlaybackThread::getStrategyForSession_l(audio_session_t sessionId)
Eric Laurent81784c32012-11-19 14:55:58 -08002827{
2828 // session AUDIO_SESSION_OUTPUT_MIX is placed in same strategy as MUSIC stream so that
2829 // it is moved to correct output by audio policy manager when A2DP is connected or disconnected
2830 if (sessionId == AUDIO_SESSION_OUTPUT_MIX) {
2831 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2832 }
2833 for (size_t i = 0; i < mTracks.size(); i++) {
2834 sp<Track> track = mTracks[i];
Glenn Kasten5736c352012-12-04 12:12:34 -08002835 if (sessionId == track->sessionId() && !track->isInvalid()) {
Eric Laurent81784c32012-11-19 14:55:58 -08002836 return AudioSystem::getStrategyForStream(track->streamType());
2837 }
2838 }
2839 return AudioSystem::getStrategyForStream(AUDIO_STREAM_MUSIC);
2840}
2841
2842
Phil Burk062e67a2015-02-11 13:40:50 -08002843AudioStreamOut* AudioFlinger::PlaybackThread::getOutput() const
Eric Laurent81784c32012-11-19 14:55:58 -08002844{
2845 Mutex::Autolock _l(mLock);
2846 return mOutput;
2847}
2848
Phil Burk062e67a2015-02-11 13:40:50 -08002849AudioStreamOut* AudioFlinger::PlaybackThread::clearOutput()
Eric Laurent81784c32012-11-19 14:55:58 -08002850{
2851 Mutex::Autolock _l(mLock);
2852 AudioStreamOut *output = mOutput;
2853 mOutput = NULL;
2854 // FIXME FastMixer might also have a raw ptr to mOutputSink;
2855 // must push a NULL and wait for ack
2856 mOutputSink.clear();
2857 mPipeSink.clear();
2858 mNormalSink.clear();
2859 return output;
2860}
2861
2862// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002863sp<StreamHalInterface> AudioFlinger::PlaybackThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08002864{
2865 if (mOutput == NULL) {
2866 return NULL;
2867 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07002868 return mOutput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08002869}
2870
2871uint32_t AudioFlinger::PlaybackThread::activeSleepTimeUs() const
2872{
2873 return (uint32_t)((uint32_t)((mNormalFrameCount * 1000) / mSampleRate) * 1000);
2874}
2875
2876status_t AudioFlinger::PlaybackThread::setSyncEvent(const sp<SyncEvent>& event)
2877{
2878 if (!isValidSyncEvent(event)) {
2879 return BAD_VALUE;
2880 }
2881
2882 Mutex::Autolock _l(mLock);
2883
2884 for (size_t i = 0; i < mTracks.size(); ++i) {
2885 sp<Track> track = mTracks[i];
2886 if (event->triggerSession() == track->sessionId()) {
2887 (void) track->setSyncEvent(event);
2888 return NO_ERROR;
2889 }
2890 }
2891
2892 return NAME_NOT_FOUND;
2893}
2894
2895bool AudioFlinger::PlaybackThread::isValidSyncEvent(const sp<SyncEvent>& event) const
2896{
2897 return event->type() == AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE;
2898}
2899
2900void AudioFlinger::PlaybackThread::threadLoop_removeTracks(
2901 const Vector< sp<Track> >& tracksToRemove)
2902{
Andy Hungfe726a62018-09-27 15:17:25 -07002903 // Miscellaneous track cleanup when removed from the active list,
2904 // called without Thread lock but synchronized with threadLoop processing.
Eric Laurentbfb1b832013-01-07 09:53:42 -08002905#ifdef ADD_BATTERY_DATA
Andy Hungfe726a62018-09-27 15:17:25 -07002906 for (const auto& track : tracksToRemove) {
2907 if (track->isExternalTrack()) {
2908 // to track the speaker usage
2909 addBatteryData(IMediaPlayerService::kBatteryDataAudioFlingerStop);
Eric Laurent81784c32012-11-19 14:55:58 -08002910 }
2911 }
Andy Hungfe726a62018-09-27 15:17:25 -07002912#else
2913 (void)tracksToRemove; // suppress unused warning
2914#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002915}
2916
2917void AudioFlinger::PlaybackThread::checkSilentMode_l()
2918{
2919 if (!mMasterMute) {
2920 char value[PROPERTY_VALUE_MAX];
jiabin10d86fd2019-10-31 17:20:42 -07002921 if (isSingleDeviceType(outDeviceTypes(), AUDIO_DEVICE_OUT_REMOTE_SUBMIX)) {
Jean-Michel Trivi32f37c22016-03-31 16:00:32 -07002922 ALOGD("ro.audio.silent will be ignored for threads on AUDIO_DEVICE_OUT_REMOTE_SUBMIX");
2923 return;
2924 }
Eric Laurent81784c32012-11-19 14:55:58 -08002925 if (property_get("ro.audio.silent", value, "0") > 0) {
2926 char *endptr;
2927 unsigned long ul = strtoul(value, &endptr, 0);
2928 if (*endptr == '\0' && ul != 0) {
2929 ALOGD("Silence is golden");
2930 // The setprop command will not allow a property to be changed after
2931 // the first time it is set, so we don't have to worry about un-muting.
2932 setMasterMute_l(true);
2933 }
2934 }
2935 }
2936}
2937
2938// shared by MIXER and DIRECT, overridden by DUPLICATING
Eric Laurentbfb1b832013-01-07 09:53:42 -08002939ssize_t AudioFlinger::PlaybackThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08002940{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07002941 LOG_HIST_TS();
Eric Laurent81784c32012-11-19 14:55:58 -08002942 mInWrite = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002943 ssize_t bytesWritten;
Andy Hung010a1a12014-03-13 13:57:33 -07002944 const size_t offset = mCurrentWriteLength - mBytesRemaining;
Eric Laurent81784c32012-11-19 14:55:58 -08002945
2946 // If an NBAIO sink is present, use it to write the normal mixer's submix
2947 if (mNormalSink != 0) {
Glenn Kasten4c053ea2014-09-28 14:41:07 -07002948
Andy Hung010a1a12014-03-13 13:57:33 -07002949 const size_t count = mBytesRemaining / mFrameSize;
2950
Simon Wilson2d590962012-11-29 15:18:50 -08002951 ATRACE_BEGIN("write");
Eric Laurent81784c32012-11-19 14:55:58 -08002952 // update the setpoint when AudioFlinger::mScreenState changes
2953 uint32_t screenState = AudioFlinger::mScreenState;
2954 if (screenState != mScreenState) {
2955 mScreenState = screenState;
2956 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
2957 if (pipe != NULL) {
2958 pipe->setAvgFrames((mScreenState & 1) ?
2959 (pipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
2960 }
2961 }
Andy Hung010a1a12014-03-13 13:57:33 -07002962 ssize_t framesWritten = mNormalSink->write((char *)mSinkBuffer + offset, count);
Simon Wilson2d590962012-11-29 15:18:50 -08002963 ATRACE_END();
Eric Laurent81784c32012-11-19 14:55:58 -08002964 if (framesWritten > 0) {
Andy Hung010a1a12014-03-13 13:57:33 -07002965 bytesWritten = framesWritten * mFrameSize;
Andy Hung8946a282018-04-19 20:04:56 -07002966#ifdef TEE_SINK
2967 mTee.write((char *)mSinkBuffer + offset, framesWritten);
2968#endif
Eric Laurent81784c32012-11-19 14:55:58 -08002969 } else {
2970 bytesWritten = framesWritten;
2971 }
2972 // otherwise use the HAL / AudioStreamOut directly
2973 } else {
Eric Laurentbfb1b832013-01-07 09:53:42 -08002974 // Direct output and offload threads
Andy Hung010a1a12014-03-13 13:57:33 -07002975
Eric Laurentbfb1b832013-01-07 09:53:42 -08002976 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07002977 ALOGW_IF(mWriteAckSequence & 1, "threadLoop_write(): out of sequence write request");
2978 mWriteAckSequence += 2;
2979 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002980 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002981 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002982 }
Mikhail Naganov76e89c32019-08-15 20:18:47 -07002983 ATRACE_BEGIN("write");
Glenn Kasten767094d2013-08-23 13:51:43 -07002984 // FIXME We should have an implementation of timestamps for direct output threads.
2985 // They are used e.g for multichannel PCM playback over HDMI.
Phil Burk062e67a2015-02-11 13:40:50 -08002986 bytesWritten = mOutput->write((char *)mSinkBuffer + offset, mBytesRemaining);
Mikhail Naganov76e89c32019-08-15 20:18:47 -07002987 ATRACE_END();
Eric Laurent51716182016-02-29 18:00:56 -08002988
Eric Laurentbfb1b832013-01-07 09:53:42 -08002989 if (mUseAsyncWrite &&
2990 ((bytesWritten < 0) || (bytesWritten == (ssize_t)mBytesRemaining))) {
2991 // do not wait for async callback in case of error of full write
Eric Laurent3b4529e2013-09-05 18:09:19 -07002992 mWriteAckSequence &= ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08002993 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07002994 mCallbackThread->setWriteBlocked(mWriteAckSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08002995 }
Eric Laurent81784c32012-11-19 14:55:58 -08002996 }
2997
Eric Laurent81784c32012-11-19 14:55:58 -08002998 mNumWrites++;
2999 mInWrite = false;
Eric Laurentfd477972013-10-25 18:10:40 -07003000 mStandby = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003001 return bytesWritten;
3002}
3003
3004void AudioFlinger::PlaybackThread::threadLoop_drain()
3005{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003006 bool supportsDrain = false;
3007 if (mOutput->stream->supportsDrain(&supportsDrain) == OK && supportsDrain) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003008 ALOGV("draining %s", (mMixerStatus == MIXER_DRAIN_TRACK) ? "early" : "full");
3009 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07003010 ALOGW_IF(mDrainSequence & 1, "threadLoop_drain(): out of sequence drain request");
3011 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003012 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07003013 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003014 }
Mikhail Naganovcbc8f612016-10-11 18:05:13 -07003015 status_t result = mOutput->stream->drain(mMixerStatus == MIXER_DRAIN_TRACK);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003016 ALOGE_IF(result != OK, "Error when draining stream: %d", result);
Eric Laurentbfb1b832013-01-07 09:53:42 -08003017 }
3018}
3019
3020void AudioFlinger::PlaybackThread::threadLoop_exit()
3021{
Eric Laurent275e8e92014-11-30 15:14:47 -08003022 {
3023 Mutex::Autolock _l(mLock);
3024 for (size_t i = 0; i < mTracks.size(); i++) {
3025 sp<Track> track = mTracks[i];
3026 track->invalidate();
3027 }
Andy Hungdae27702016-10-31 14:01:16 -07003028 // Clear ActiveTracks to update BatteryNotifier in case active tracks remain.
3029 // After we exit there are no more track changes sent to BatteryNotifier
3030 // because that requires an active threadLoop.
3031 // TODO: should we decActiveTrackCnt() of the cleared track effect chain?
3032 mActiveTracks.clear();
Eric Laurent275e8e92014-11-30 15:14:47 -08003033 }
Eric Laurent81784c32012-11-19 14:55:58 -08003034}
3035
3036/*
3037The derived values that are cached:
Andy Hung25c2dac2014-02-27 14:56:00 -08003038 - mSinkBufferSize from frame count * frame size
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003039 - mActiveSleepTimeUs from activeSleepTimeUs()
3040 - mIdleSleepTimeUs from idleSleepTimeUs()
Eric Laurent42537be2016-01-08 17:16:42 -08003041 - mStandbyDelayNs from mActiveSleepTimeUs (DIRECT only) or forced to at least
3042 kDefaultStandbyTimeInNsecs when connected to an A2DP device.
Eric Laurent81784c32012-11-19 14:55:58 -08003043 - maxPeriod from frame count and sample rate (MIXER only)
3044
3045The parameters that affect these derived values are:
3046 - frame count
3047 - frame size
3048 - sample rate
3049 - device type: A2DP or not
3050 - device latency
3051 - format: PCM or not
3052 - active sleep time
3053 - idle sleep time
3054*/
3055
3056void AudioFlinger::PlaybackThread::cacheParameters_l()
3057{
Andy Hung25c2dac2014-02-27 14:56:00 -08003058 mSinkBufferSize = mNormalFrameCount * mFrameSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003059 mActiveSleepTimeUs = activeSleepTimeUs();
3060 mIdleSleepTimeUs = idleSleepTimeUs();
Eric Laurent42537be2016-01-08 17:16:42 -08003061
3062 // make sure standby delay is not too short when connected to an A2DP sink to avoid
3063 // truncating audio when going to standby.
3064 mStandbyDelayNs = AudioFlinger::mStandbyTimeInNsecs;
jiabin10d86fd2019-10-31 17:20:42 -07003065 if (!Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty()) {
Eric Laurent42537be2016-01-08 17:16:42 -08003066 if (mStandbyDelayNs < kDefaultStandbyTimeInNsecs) {
3067 mStandbyDelayNs = kDefaultStandbyTimeInNsecs;
3068 }
3069 }
Eric Laurent81784c32012-11-19 14:55:58 -08003070}
3071
Eric Laurent13084622016-05-17 10:51:49 -07003072bool AudioFlinger::PlaybackThread::invalidateTracks_l(audio_stream_type_t streamType)
Eric Laurent81784c32012-11-19 14:55:58 -08003073{
Glenn Kastenc42e9b42016-03-21 11:35:03 -07003074 ALOGV("MixerThread::invalidateTracks() mixer %p, streamType %d, mTracks.size %zu",
Eric Laurent81784c32012-11-19 14:55:58 -08003075 this, streamType, mTracks.size());
Eric Laurent13084622016-05-17 10:51:49 -07003076 bool trackMatch = false;
Eric Laurent81784c32012-11-19 14:55:58 -08003077 size_t size = mTracks.size();
3078 for (size_t i = 0; i < size; i++) {
3079 sp<Track> t = mTracks[i];
Eric Laurentd60560a2015-04-10 11:31:20 -07003080 if (t->streamType() == streamType && t->isExternalTrack()) {
Glenn Kasten5736c352012-12-04 12:12:34 -08003081 t->invalidate();
Eric Laurent13084622016-05-17 10:51:49 -07003082 trackMatch = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003083 }
3084 }
Eric Laurent13084622016-05-17 10:51:49 -07003085 return trackMatch;
Eric Laurent81784c32012-11-19 14:55:58 -08003086}
3087
Haynes Mathew George05317d22016-05-03 16:34:26 -07003088void AudioFlinger::PlaybackThread::invalidateTracks(audio_stream_type_t streamType)
3089{
3090 Mutex::Autolock _l(mLock);
3091 invalidateTracks_l(streamType);
3092}
3093
Eric Laurent81784c32012-11-19 14:55:58 -08003094status_t AudioFlinger::PlaybackThread::addEffectChain_l(const sp<EffectChain>& chain)
3095{
Glenn Kastend848eb42016-03-08 13:42:11 -08003096 audio_session_t session = chain->sessionId();
Mikhail Naganov022b9952017-01-04 16:36:51 -08003097 sp<EffectBufferHalInterface> halInBuffer, halOutBuffer;
Kevin Rocard7588ff42018-01-08 11:11:30 -08003098 status_t result = mAudioFlinger->mEffectsFactoryHal->mirrorBuffer(
Mikhail Naganov022b9952017-01-04 16:36:51 -08003099 mEffectBufferEnabled ? mEffectBuffer : mSinkBuffer,
3100 mEffectBufferEnabled ? mEffectBufferSize : mSinkBufferSize,
3101 &halInBuffer);
3102 if (result != OK) return result;
3103 halOutBuffer = halInBuffer;
rago94a1ee82017-07-21 15:11:02 -07003104 effect_buffer_t *buffer = reinterpret_cast<effect_buffer_t*>(halInBuffer->externalData());
Eric Laurent81784c32012-11-19 14:55:58 -08003105 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
Glenn Kastend848eb42016-03-08 13:42:11 -08003106 if (session > AUDIO_SESSION_OUTPUT_MIX) {
Eric Laurent81784c32012-11-19 14:55:58 -08003107 // Only one effect chain can be present in direct output thread and it uses
Andy Hung2098f272014-02-27 14:00:06 -08003108 // the sink buffer as input
Eric Laurent81784c32012-11-19 14:55:58 -08003109 if (mType != DIRECT) {
jiabin245cdd92018-12-07 17:55:15 -08003110 size_t numSamples = mNormalFrameCount * (mChannelCount + mHapticChannelCount);
Kevin Rocard7588ff42018-01-08 11:11:30 -08003111 status_t result = mAudioFlinger->mEffectsFactoryHal->allocateBuffer(
rago94a1ee82017-07-21 15:11:02 -07003112 numSamples * sizeof(effect_buffer_t),
Mikhail Naganov022b9952017-01-04 16:36:51 -08003113 &halInBuffer);
3114 if (result != OK) return result;
rago94a1ee82017-07-21 15:11:02 -07003115#ifdef FLOAT_EFFECT_CHAIN
3116 buffer = halInBuffer->audioBuffer()->f32;
3117#else
Mikhail Naganov022b9952017-01-04 16:36:51 -08003118 buffer = halInBuffer->audioBuffer()->s16;
rago94a1ee82017-07-21 15:11:02 -07003119#endif
Mikhail Naganov022b9952017-01-04 16:36:51 -08003120 ALOGV("addEffectChain_l() creating new input buffer %p session %d",
3121 buffer, session);
Eric Laurent81784c32012-11-19 14:55:58 -08003122 }
3123
3124 // Attach all tracks with same session ID to this chain.
3125 for (size_t i = 0; i < mTracks.size(); ++i) {
3126 sp<Track> track = mTracks[i];
3127 if (session == track->sessionId()) {
3128 ALOGV("addEffectChain_l() track->setMainBuffer track %p buffer %p", track.get(),
3129 buffer);
3130 track->setMainBuffer(buffer);
3131 chain->incTrackCnt();
3132 }
3133 }
3134
3135 // indicate all active tracks in the chain
Andy Hungdae27702016-10-31 14:01:16 -07003136 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003137 if (session == track->sessionId()) {
3138 ALOGV("addEffectChain_l() activating track %p on session %d", track.get(), session);
3139 chain->incActiveTrackCnt();
3140 }
3141 }
3142 }
Eric Laurentaaa44472014-09-12 17:41:50 -07003143 chain->setThread(this);
Mikhail Naganov022b9952017-01-04 16:36:51 -08003144 chain->setInBuffer(halInBuffer);
3145 chain->setOutBuffer(halOutBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08003146 // Effect chain for session AUDIO_SESSION_OUTPUT_STAGE is inserted at end of effect
Glenn Kastend848eb42016-03-08 13:42:11 -08003147 // chains list in order to be processed last as it contains output stage effects.
Eric Laurent81784c32012-11-19 14:55:58 -08003148 // Effect chain for session AUDIO_SESSION_OUTPUT_MIX is inserted before
3149 // session AUDIO_SESSION_OUTPUT_STAGE to be processed
Glenn Kastend848eb42016-03-08 13:42:11 -08003150 // after track specific effects and before output stage.
Eric Laurent81784c32012-11-19 14:55:58 -08003151 // It is therefore mandatory that AUDIO_SESSION_OUTPUT_MIX == 0 and
Glenn Kastend848eb42016-03-08 13:42:11 -08003152 // that AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX.
Eric Laurent81784c32012-11-19 14:55:58 -08003153 // Effect chain for other sessions are inserted at beginning of effect
3154 // chains list to be processed before output mix effects. Relative order between other
Glenn Kastend848eb42016-03-08 13:42:11 -08003155 // sessions is not important.
3156 static_assert(AUDIO_SESSION_OUTPUT_MIX == 0 &&
3157 AUDIO_SESSION_OUTPUT_STAGE < AUDIO_SESSION_OUTPUT_MIX,
3158 "audio_session_t constants misdefined");
Eric Laurent81784c32012-11-19 14:55:58 -08003159 size_t size = mEffectChains.size();
3160 size_t i = 0;
3161 for (i = 0; i < size; i++) {
3162 if (mEffectChains[i]->sessionId() < session) {
3163 break;
3164 }
3165 }
3166 mEffectChains.insertAt(chain, i);
3167 checkSuspendOnAddEffectChain_l(chain);
3168
3169 return NO_ERROR;
3170}
3171
3172size_t AudioFlinger::PlaybackThread::removeEffectChain_l(const sp<EffectChain>& chain)
3173{
Glenn Kastend848eb42016-03-08 13:42:11 -08003174 audio_session_t session = chain->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08003175
3176 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
3177
3178 for (size_t i = 0; i < mEffectChains.size(); i++) {
3179 if (chain == mEffectChains[i]) {
3180 mEffectChains.removeAt(i);
3181 // detach all active tracks from the chain
Andy Hungdae27702016-10-31 14:01:16 -07003182 for (const sp<Track> &track : mActiveTracks) {
Eric Laurent81784c32012-11-19 14:55:58 -08003183 if (session == track->sessionId()) {
3184 ALOGV("removeEffectChain_l(): stopping track on chain %p for session Id: %d",
3185 chain.get(), session);
3186 chain->decActiveTrackCnt();
3187 }
3188 }
3189
3190 // detach all tracks with same session ID from this chain
3191 for (size_t i = 0; i < mTracks.size(); ++i) {
3192 sp<Track> track = mTracks[i];
3193 if (session == track->sessionId()) {
rago94a1ee82017-07-21 15:11:02 -07003194 track->setMainBuffer(reinterpret_cast<effect_buffer_t*>(mSinkBuffer));
Eric Laurent81784c32012-11-19 14:55:58 -08003195 chain->decTrackCnt();
3196 }
3197 }
3198 break;
3199 }
3200 }
3201 return mEffectChains.size();
3202}
3203
3204status_t AudioFlinger::PlaybackThread::attachAuxEffect(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003205 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003206{
3207 Mutex::Autolock _l(mLock);
3208 return attachAuxEffect_l(track, EffectId);
3209}
3210
3211status_t AudioFlinger::PlaybackThread::attachAuxEffect_l(
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003212 const sp<AudioFlinger::PlaybackThread::Track>& track, int EffectId)
Eric Laurent81784c32012-11-19 14:55:58 -08003213{
3214 status_t status = NO_ERROR;
3215
3216 if (EffectId == 0) {
3217 track->setAuxBuffer(0, NULL);
3218 } else {
3219 // Auxiliary effects are always in audio session AUDIO_SESSION_OUTPUT_MIX
3220 sp<EffectModule> effect = getEffect_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
3221 if (effect != 0) {
3222 if ((effect->desc().flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_AUXILIARY) {
3223 track->setAuxBuffer(EffectId, (int32_t *)effect->inBuffer());
3224 } else {
3225 status = INVALID_OPERATION;
3226 }
3227 } else {
3228 status = BAD_VALUE;
3229 }
3230 }
3231 return status;
3232}
3233
3234void AudioFlinger::PlaybackThread::detachAuxEffect_l(int effectId)
3235{
3236 for (size_t i = 0; i < mTracks.size(); ++i) {
3237 sp<Track> track = mTracks[i];
3238 if (track->auxEffectId() == effectId) {
3239 attachAuxEffect_l(track, 0);
3240 }
3241 }
3242}
3243
3244bool AudioFlinger::PlaybackThread::threadLoop()
3245{
Glenn Kasten388d5712017-04-07 14:38:41 -07003246 tlNBLogWriter = mNBLogWriter.get();
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003247
Eric Laurent81784c32012-11-19 14:55:58 -08003248 Vector< sp<Track> > tracksToRemove;
3249
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003250 mStandbyTimeNs = systemTime();
Andy Hung446f4df2019-02-21 12:26:41 -08003251 int64_t lastLoopCountWritten = -2; // never matches "previous" loop, when loopCount = 0.
3252 int64_t lastFramesWritten = -1; // track changes in timestamp server frames written
Eric Laurent81784c32012-11-19 14:55:58 -08003253
3254 // MIXER
3255 nsecs_t lastWarning = 0;
3256
3257 // DUPLICATING
3258 // FIXME could this be made local to while loop?
3259 writeFrames = 0;
3260
3261 cacheParameters_l();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003262 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003263
3264 if (mType == MIXER) {
3265 sleepTimeShift = 0;
3266 }
3267
3268 CpuStats cpuStats;
3269 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
3270
3271 acquireWakeLock();
3272
Glenn Kasteneef598c2017-04-03 14:41:13 -07003273 // mNBLogWriter logging APIs can only be called by a single thread, typically the
3274 // thread associated with this PlaybackThread.
3275 // If you want to share the mNBLogWriter with other threads (for example, binder threads)
3276 // then all such threads must agree to hold a common mutex before logging.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003277 // So if you need to log when mutex is unlocked, set logString to a non-NULL string,
3278 // and then that string will be logged at the next convenient opportunity.
Glenn Kasteneef598c2017-04-03 14:41:13 -07003279 // See reference to logString below.
Glenn Kasten9e58b552013-01-18 15:09:48 -08003280 const char *logString = NULL;
3281
rago1bb90822017-05-02 18:31:48 -07003282 // Estimated time for next buffer to be written to hal. This is used only on
3283 // suspended mode (for now) to help schedule the wait time until next iteration.
3284 nsecs_t timeLoopNextNs = 0;
3285
Eric Laurent664539d2013-09-23 18:24:31 -07003286 checkSilentMode_l();
Glenn Kasteneef598c2017-04-03 14:41:13 -07003287
Andy Hungf3234512018-07-03 14:51:47 -07003288 // DIRECT and OFFLOAD threads should reset frame count to zero on stop/flush
3289 // TODO: add confirmation checks:
3290 // 1) DIRECT threads and linear PCM format really resets to 0?
3291 // 2) Is frame count really valid if not linear pcm?
3292 // 3) Are all 64 bits of position returned, not just lowest 32 bits?
3293 if (mType == OFFLOAD || mType == DIRECT) {
3294 mTimestampVerifier.setDiscontinuityMode(mTimestampVerifier.DISCONTINUITY_MODE_ZERO);
3295 }
Andy Hung2dbffc22018-08-08 18:50:41 -07003296 audio_patch_handle_t lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
Andy Hungf3234512018-07-03 14:51:47 -07003297
Andy Hung446f4df2019-02-21 12:26:41 -08003298 // loopCount is used for statistics and diagnostics.
3299 for (int64_t loopCount = 0; !exitPending(); ++loopCount)
Eric Laurent81784c32012-11-19 14:55:58 -08003300 {
Nicolas Rouletdcdfaec2017-02-14 10:18:39 -08003301 // Log merge requests are performed during AudioFlinger binder transactions, but
3302 // that does not cover audio playback. It's requested here for that reason.
3303 mAudioFlinger->requestLogMerge();
3304
Eric Laurent81784c32012-11-19 14:55:58 -08003305 cpuStats.sample(myName);
3306
3307 Vector< sp<EffectChain> > effectChains;
Andy Hung6e6a2e62019-04-30 16:38:41 -07003308 audio_session_t activeHapticSessionId = AUDIO_SESSION_NONE;
Andy Hungc1646382019-04-30 16:12:10 -07003309 std::vector<sp<Track>> activeTracks;
Eric Laurent81784c32012-11-19 14:55:58 -08003310
Andy Hung2dbffc22018-08-08 18:50:41 -07003311 // If the device is AUDIO_DEVICE_OUT_BUS, check for downstream latency.
3312 //
jiabin10d86fd2019-10-31 17:20:42 -07003313 // Note: we access outDeviceTypes() outside of mLock.
3314 if (isMsdDevice() && outDeviceTypes().count(AUDIO_DEVICE_OUT_BUS) != 0) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003315 // Here, we try for the AF lock, but do not block on it as the latency
3316 // is more informational.
3317 if (mAudioFlinger->mLock.tryLock() == NO_ERROR) {
3318 std::vector<PatchPanel::SoftwarePatch> swPatches;
3319 double latencyMs;
3320 status_t status = INVALID_OPERATION;
3321 audio_patch_handle_t downstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3322 if (mAudioFlinger->mPatchPanel.getDownstreamSoftwarePatches(id(), &swPatches) == OK
3323 && swPatches.size() > 0) {
3324 status = swPatches[0].getLatencyMs_l(&latencyMs);
3325 downstreamPatchHandle = swPatches[0].getPatchHandle();
3326 }
3327 if (downstreamPatchHandle != lastDownstreamPatchHandle) {
Dean Wheatley30d28422018-11-06 10:27:40 +11003328 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003329 lastDownstreamPatchHandle = downstreamPatchHandle;
3330 }
3331 if (status == OK) {
3332 // verify downstream latency (we assume a max reasonable
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003333 // latency of 5 seconds).
3334 const double minLatency = 0., maxLatency = 5000.;
3335 if (latencyMs >= minLatency && latencyMs <= maxLatency) {
Andy Hung2dbffc22018-08-08 18:50:41 -07003336 ALOGV("new downstream latency %lf ms", latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003337 } else {
3338 ALOGD("out of range downstream latency %lf ms", latencyMs);
Mikhail Naganov6aa0a312018-11-09 11:00:01 -08003339 if (latencyMs < minLatency) latencyMs = minLatency;
3340 else if (latencyMs > maxLatency) latencyMs = maxLatency;
Andy Hung2dbffc22018-08-08 18:50:41 -07003341 }
Dean Wheatley30d28422018-11-06 10:27:40 +11003342 mDownstreamLatencyStatMs.add(latencyMs);
Andy Hung2dbffc22018-08-08 18:50:41 -07003343 }
3344 mAudioFlinger->mLock.unlock();
3345 }
3346 } else {
3347 if (lastDownstreamPatchHandle != AUDIO_PATCH_HANDLE_NONE) {
3348 // our device is no longer AUDIO_DEVICE_OUT_BUS, reset patch handle and stats.
Dean Wheatley30d28422018-11-06 10:27:40 +11003349 mDownstreamLatencyStatMs.reset();
Andy Hung2dbffc22018-08-08 18:50:41 -07003350 lastDownstreamPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3351 }
3352 }
3353
Eric Laurent81784c32012-11-19 14:55:58 -08003354 { // scope for mLock
3355
3356 Mutex::Autolock _l(mLock);
3357
Eric Laurent021cf962014-05-13 10:18:14 -07003358 processConfigEvents_l();
Eric Laurent10351942014-05-08 18:49:52 -07003359
Glenn Kasteneef598c2017-04-03 14:41:13 -07003360 // See comment at declaration of logString for why this is done under mLock
Glenn Kasten9e58b552013-01-18 15:09:48 -08003361 if (logString != NULL) {
3362 mNBLogWriter->logTimestamp();
3363 mNBLogWriter->log(logString);
3364 logString = NULL;
3365 }
3366
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003367 // Collect timestamp statistics for the Playback Thread types that support it.
3368 if (mType == MIXER
3369 || mType == DUPLICATING
Andy Hungf3234512018-07-03 14:51:47 -07003370 || mType == DIRECT
3371 || mType == OFFLOAD) { // no indentation
Glenn Kasten4c053ea2014-09-28 14:41:07 -07003372 // Gather the framesReleased counters for all active tracks,
Andy Hunge10393e2015-06-12 13:59:33 -07003373 // and associate with the sink frames written out. We need
3374 // this to convert the sink timestamp to the track timestamp.
Andy Hung69488c42016-05-16 18:43:33 -07003375 bool kernelLocationUpdate = false;
Andy Hung1c86ebe2018-05-29 20:29:08 -07003376 ExtendedTimestamp timestamp; // use private copy to fetch
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003377 if (mStandby) {
3378 mTimestampVerifier.discontinuity();
3379 } else if (threadloop_getHalTimestamp_l(&timestamp) == OK) {
3380 mTimestampVerifier.add(timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
3381 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3382 mSampleRate);
Andy Hungc8fddf32018-08-08 18:32:37 -07003383
3384 if (isTimestampCorrectionEnabled()) {
3385 ALOGV("TS_BEFORE: %d %lld %lld", id(),
3386 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3387 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
3388 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
3389 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3390 = correctedTimestamp.mFrames;
3391 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]
3392 = correctedTimestamp.mTimeNs;
3393 ALOGV("TS_AFTER: %d %lld %lld", id(),
3394 (long long)timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
3395 (long long)timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]);
Andy Hung2dbffc22018-08-08 18:50:41 -07003396
3397 // Note: Downstream latency only added if timestamp correction enabled.
Dean Wheatley30d28422018-11-06 10:27:40 +11003398 if (mDownstreamLatencyStatMs.getN() > 0) { // we have latency info.
Andy Hung2dbffc22018-08-08 18:50:41 -07003399 const int64_t newPosition =
3400 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
Dean Wheatley30d28422018-11-06 10:27:40 +11003401 - int64_t(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
Andy Hung2dbffc22018-08-08 18:50:41 -07003402 // prevent retrograde
3403 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = max(
3404 newPosition,
3405 (mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3406 - mSuspendedFrames));
3407 }
Andy Hungc8fddf32018-08-08 18:32:37 -07003408 }
3409
Andy Hung818e7a32016-02-16 18:08:07 -08003410 // We always fetch the timestamp here because often the downstream
Andy Hung69488c42016-05-16 18:43:33 -07003411 // sink will block while writing.
Andy Hung6d7b1192016-05-07 22:59:48 -07003412
3413 // We keep track of the last valid kernel position in case we are in underrun
3414 // and the normal mixer period is the same as the fast mixer period, or there
3415 // is some error from the HAL.
3416 if (mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3417 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3418 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
3419 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL_LASTKERNELOK] =
3420 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
3421
3422 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3423 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER];
3424 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER_LASTKERNELOK] =
3425 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER];
Andy Hung69488c42016-05-16 18:43:33 -07003426 }
3427
3428 if (timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] >= 0) {
3429 kernelLocationUpdate = true;
Andy Hung6d7b1192016-05-07 22:59:48 -07003430 } else {
Eric Laurent122f7e72016-06-29 11:53:29 -07003431 ALOGVV("getTimestamp error - no valid kernel position");
Andy Hung6d7b1192016-05-07 22:59:48 -07003432 }
3433
Andy Hung818e7a32016-02-16 18:08:07 -08003434 // copy over kernel info
3435 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
Andy Hung238fa3d2016-07-28 10:53:22 -07003436 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL]
3437 + mSuspendedFrames; // add frames discarded when suspended
Andy Hung818e7a32016-02-16 18:08:07 -08003438 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
3439 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003440 } else {
3441 mTimestampVerifier.error();
Andy Hungc54b1ff2016-02-23 14:07:07 -08003442 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003443
Andy Hungc54b1ff2016-02-23 14:07:07 -08003444 // mFramesWritten for non-offloaded tracks are contiguous
3445 // even after standby() is called. This is useful for the track frame
3446 // to sink frame mapping.
Andy Hung69488c42016-05-16 18:43:33 -07003447 bool serverLocationUpdate = false;
3448 if (mFramesWritten != lastFramesWritten) {
3449 serverLocationUpdate = true;
3450 lastFramesWritten = mFramesWritten;
3451 }
3452 // Only update timestamps if there is a meaningful change.
3453 // Either the kernel timestamp must be valid or we have written something.
3454 if (kernelLocationUpdate || serverLocationUpdate) {
3455 if (serverLocationUpdate) {
3456 // use the time before we called the HAL write - it is a bit more accurate
3457 // to when the server last read data than the current time here.
3458 //
Andy Hung446f4df2019-02-21 12:26:41 -08003459 // If we haven't written anything, mLastIoBeginNs will be -1
Andy Hung69488c42016-05-16 18:43:33 -07003460 // and we use systemTime().
3461 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = mFramesWritten;
Andy Hung446f4df2019-02-21 12:26:41 -08003462 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = mLastIoBeginNs == -1
3463 ? systemTime() : mLastIoBeginNs;
Andy Hung69488c42016-05-16 18:43:33 -07003464 }
Andy Hungdae27702016-10-31 14:01:16 -07003465
3466 for (const sp<Track> &t : mActiveTracks) {
3467 if (!t->isFastTrack()) {
Andy Hung69488c42016-05-16 18:43:33 -07003468 t->updateTrackFrameInfo(
3469 t->mAudioTrackServerProxy->framesReleased(),
3470 mFramesWritten,
Andy Hungcef2daa2018-06-01 15:31:49 -07003471 mSampleRate,
Andy Hung69488c42016-05-16 18:43:33 -07003472 mTimestamp);
3473 }
Andy Hunge10393e2015-06-12 13:59:33 -07003474 }
Glenn Kastenbd096fd2013-08-23 13:53:56 -07003475 }
Andy Hunge6c37112019-02-26 17:38:10 -08003476
3477 if (audio_has_proportional_frames(mFormat)) {
3478 const double latencyMs = mTimestamp.getOutputServerLatencyMs(mSampleRate);
3479 if (latencyMs != 0.) { // note 0. means timestamp is empty.
3480 mLatencyMs.add(latencyMs);
3481 }
3482 }
3483
Andy Hung2e2c0bb2018-06-11 19:13:11 -07003484 } // if (mType ... ) { // no indentation
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003485#if 0
3486 // logFormat example
Nicolas Rouletc20cb502017-02-01 12:35:24 -08003487 if (z % 100 == 0) {
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003488 timespec ts;
3489 clock_gettime(CLOCK_MONOTONIC, &ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003490 LOGT("This is an integer %d, this is a float %f, this is my "
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003491 "pid %p %% %s %t", 42, 3.14, "and this is a timestamp", ts);
Nicolas Roulet4da78202017-02-03 12:53:39 -08003492 LOGT("A deceptive null-terminated string %\0");
Nicolas Rouletfe1e1442017-01-30 12:02:03 -08003493 }
3494 ++z;
3495#endif
Eric Laurent81784c32012-11-19 14:55:58 -08003496 saveOutputTracks();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003497 if (mSignalPending) {
3498 // A signal was raised while we were unlocked
3499 mSignalPending = false;
3500 } else if (waitingAsyncCallback_l()) {
3501 if (exitPending()) {
3502 break;
3503 }
Marco Nelissen078538c2015-05-12 09:17:57 -07003504 bool released = false;
Eric Laurent64667972016-03-30 18:19:46 -07003505 if (!keepWakeLock()) {
Marco Nelissen078538c2015-05-12 09:17:57 -07003506 releaseWakeLock_l();
3507 released = true;
3508 }
Andy Hung10cbff12017-02-21 17:30:14 -08003509
3510 const int64_t waitNs = computeWaitTimeNs_l();
3511 ALOGV("wait async completion (wait time: %lld)", (long long)waitNs);
3512 status_t status = mWaitWorkCV.waitRelative(mLock, waitNs);
3513 if (status == TIMED_OUT) {
3514 mSignalPending = true; // if timeout recheck everything
3515 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003516 ALOGV("async completion/wake");
Marco Nelissen078538c2015-05-12 09:17:57 -07003517 if (released) {
3518 acquireWakeLock_l();
3519 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003520 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3521 mSleepTimeUs = 0;
Eric Laurentede6c3b2013-09-19 14:37:46 -07003522
3523 continue;
3524 }
Eric Tan39ec8d62018-07-24 09:49:29 -07003525 if ((mActiveTracks.isEmpty() && systemTime() > mStandbyTimeNs) ||
Eric Laurentbfb1b832013-01-07 09:53:42 -08003526 isSuspended()) {
3527 // put audio hardware into standby after short delay
3528 if (shouldStandby_l()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003529
3530 threadLoop_standby();
3531
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07003532 // This is where we go into standby
3533 if (!mStandby) {
3534 LOG_AUDIO_STATE();
3535 }
Eric Laurent81784c32012-11-19 14:55:58 -08003536 mStandby = true;
Andy Hungd0979812019-02-21 15:51:44 -08003537 sendStatistics(false /* force */);
Eric Laurent81784c32012-11-19 14:55:58 -08003538 }
3539
Eric Tan39ec8d62018-07-24 09:49:29 -07003540 if (mActiveTracks.isEmpty() && mConfigEvents.isEmpty()) {
Eric Laurent81784c32012-11-19 14:55:58 -08003541 // we're about to wait, flush the binder command buffer
3542 IPCThreadState::self()->flushCommands();
3543
3544 clearOutputTracks();
3545
3546 if (exitPending()) {
3547 break;
3548 }
3549
3550 releaseWakeLock_l();
3551 // wait until we have something to do...
3552 ALOGV("%s going to sleep", myName.string());
3553 mWaitWorkCV.wait(mLock);
3554 ALOGV("%s waking up", myName.string());
3555 acquireWakeLock_l();
3556
3557 mMixerStatus = MIXER_IDLE;
3558 mMixerStatusIgnoringFastTracks = MIXER_IDLE;
3559 mBytesWritten = 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003560 mBytesRemaining = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08003561 checkSilentMode_l();
3562
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003563 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
3564 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08003565 if (mType == MIXER) {
3566 sleepTimeShift = 0;
3567 }
3568
3569 continue;
3570 }
3571 }
Eric Laurent81784c32012-11-19 14:55:58 -08003572 // mMixerStatusIgnoringFastTracks is also updated internally
3573 mMixerStatus = prepareTracks_l(&tracksToRemove);
3574
Andy Hungdae27702016-10-31 14:01:16 -07003575 mActiveTracks.updatePowerState(this);
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003576
Kevin Rocard069c2712018-03-29 19:09:14 -07003577 updateMetadata_l();
3578
Eric Laurent81784c32012-11-19 14:55:58 -08003579 // prevent any changes in effect chain list and in each effect chain
3580 // during mixing and effect process as the audio buffers could be deleted
3581 // or modified if an effect is created or deleted
3582 lockEffectChains_l(effectChains);
Andy Hung6e6a2e62019-04-30 16:38:41 -07003583
3584 // Determine which session to pick up haptic data.
3585 // This must be done under the same lock as prepareTracks_l().
3586 // TODO: Write haptic data directly to sink buffer when mixing.
3587 if (mHapticChannelCount > 0 && effectChains.size() > 0) {
3588 for (const auto& track : mActiveTracks) {
3589 if (track->getHapticPlaybackEnabled()) {
3590 activeHapticSessionId = track->sessionId();
3591 break;
3592 }
3593 }
3594 }
3595
Andy Hungc1646382019-04-30 16:12:10 -07003596 // Acquire a local copy of active tracks with lock (release w/o lock).
3597 //
3598 // Control methods on the track acquire the ThreadBase lock (e.g. start()
3599 // stop(), pause(), etc.), but the threadLoop is entitled to call audio
3600 // data / buffer methods on tracks from activeTracks without the ThreadBase lock.
3601 activeTracks.insert(activeTracks.end(), mActiveTracks.begin(), mActiveTracks.end());
Marco Nelissen462fd2f2013-01-14 14:12:05 -08003602 } // mLock scope ends
Eric Laurent81784c32012-11-19 14:55:58 -08003603
Eric Laurentbfb1b832013-01-07 09:53:42 -08003604 if (mBytesRemaining == 0) {
3605 mCurrentWriteLength = 0;
3606 if (mMixerStatus == MIXER_TRACKS_READY) {
3607 // threadLoop_mix() sets mCurrentWriteLength
3608 threadLoop_mix();
3609 } else if ((mMixerStatus != MIXER_DRAIN_TRACK)
3610 && (mMixerStatus != MIXER_DRAIN_ALL)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003611 // threadLoop_sleepTime sets mSleepTimeUs to 0 if data
Eric Laurentbfb1b832013-01-07 09:53:42 -08003612 // must be written to HAL
3613 threadLoop_sleepTime();
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003614 if (mSleepTimeUs == 0) {
Andy Hung25c2dac2014-02-27 14:56:00 -08003615 mCurrentWriteLength = mSinkBufferSize;
Andy Hungc1646382019-04-30 16:12:10 -07003616
3617 // Tally underrun frames as we are inserting 0s here.
3618 for (const auto& track : activeTracks) {
3619 if (track->mFillingUpStatus == Track::FS_ACTIVE) {
3620 track->mAudioTrackServerProxy->tallyUnderrunFrames(mNormalFrameCount);
3621 }
3622 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003623 }
3624 }
Andy Hung98ef9782014-03-04 14:46:50 -08003625 // Either threadLoop_mix() or threadLoop_sleepTime() should have set
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003626 // mMixerBuffer with data if mMixerBufferValid is true and mSleepTimeUs == 0.
Andy Hung98ef9782014-03-04 14:46:50 -08003627 // Merge mMixerBuffer data into mEffectBuffer (if any effects are valid)
3628 // or mSinkBuffer (if there are no effects).
3629 //
3630 // This is done pre-effects computation; if effects change to
3631 // support higher precision, this needs to move.
3632 //
3633 // mMixerBufferValid is only set true by MixerThread::prepareTracks_l().
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003634 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003635 if (mMixerBufferValid) {
3636 void *buffer = mEffectBufferValid ? mEffectBuffer : mSinkBuffer;
3637 audio_format_t format = mEffectBufferValid ? mEffectBufferFormat : mFormat;
3638
Andy Hung2ddee192015-12-18 17:34:44 -08003639 // mono blend occurs for mixer threads only (not direct or offloaded)
3640 // and is handled here if we're going directly to the sink.
3641 if (requireMonoBlend() && !mEffectBufferValid) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003642 mono_blend(mMixerBuffer, mMixerBufferFormat, mChannelCount, mNormalFrameCount,
3643 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003644 }
3645
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003646 if (!hasFastMixer()) {
3647 // Balance must take effect after mono conversion.
3648 // We do it here if there is no FastMixer.
3649 // mBalance detects zero balance within the class for speed (not needed here).
3650 mBalance.setBalance(mMasterBalance.load());
3651 mBalance.process((float *)mMixerBuffer, mNormalFrameCount);
3652 }
3653
Andy Hung98ef9782014-03-04 14:46:50 -08003654 memcpy_by_audio_format(buffer, format, mMixerBuffer, mMixerBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003655 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3656
3657 // If we're going directly to the sink and there are haptic channels,
3658 // we should adjust channels as the sample data is partially interleaved
3659 // in this case.
3660 if (!mEffectBufferValid && mHapticChannelCount > 0) {
3661 adjust_channels_non_destructive(buffer, mChannelCount, buffer,
3662 mChannelCount + mHapticChannelCount,
3663 audio_bytes_per_sample(format),
3664 audio_bytes_per_frame(mChannelCount, format) * mNormalFrameCount);
3665 }
Andy Hung98ef9782014-03-04 14:46:50 -08003666 }
3667
Eric Laurentbfb1b832013-01-07 09:53:42 -08003668 mBytesRemaining = mCurrentWriteLength;
3669 if (isSuspended()) {
Andy Hung238fa3d2016-07-28 10:53:22 -07003670 // Simulate write to HAL when suspended (e.g. BT SCO phone call).
3671 mSleepTimeUs = suspendSleepTimeUs(); // assumes full buffer.
3672 const size_t framesRemaining = mBytesRemaining / mFrameSize;
3673 mBytesWritten += mBytesRemaining;
3674 mFramesWritten += framesRemaining;
3675 mSuspendedFrames += framesRemaining; // to adjust kernel HAL position
Eric Laurentbfb1b832013-01-07 09:53:42 -08003676 mBytesRemaining = 0;
3677 }
Eric Laurent81784c32012-11-19 14:55:58 -08003678
Eric Laurentbfb1b832013-01-07 09:53:42 -08003679 // only process effects if we're going to write
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003680 if (mSleepTimeUs == 0 && mType != OFFLOAD) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003681 for (size_t i = 0; i < effectChains.size(); i ++) {
3682 effectChains[i]->process_l();
jiabin47affe52019-04-04 18:02:07 -07003683 // TODO: Write haptic data directly to sink buffer when mixing.
Andy Hung6e6a2e62019-04-30 16:38:41 -07003684 if (activeHapticSessionId != AUDIO_SESSION_NONE
3685 && activeHapticSessionId == effectChains[i]->sessionId()) {
jiabin47affe52019-04-04 18:02:07 -07003686 // Haptic data is active in this case, copy it directly from
3687 // in buffer to out buffer.
3688 const size_t audioBufferSize = mNormalFrameCount
3689 * audio_bytes_per_frame(mChannelCount, EFFECT_BUFFER_FORMAT);
3690 memcpy_by_audio_format(
3691 (uint8_t*)effectChains[i]->outBuffer() + audioBufferSize,
3692 EFFECT_BUFFER_FORMAT,
3693 (const uint8_t*)effectChains[i]->inBuffer() + audioBufferSize,
3694 EFFECT_BUFFER_FORMAT, mNormalFrameCount * mHapticChannelCount);
3695 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003696 }
Eric Laurent81784c32012-11-19 14:55:58 -08003697 }
3698 }
Eric Laurent59fe0102013-09-27 18:48:26 -07003699 // Process effect chains for offloaded thread even if no audio
3700 // was read from audio track: process only updates effect state
3701 // and thus does have to be synchronized with audio writes but may have
3702 // to be called while waiting for async write callback
3703 if (mType == OFFLOAD) {
3704 for (size_t i = 0; i < effectChains.size(); i ++) {
3705 effectChains[i]->process_l();
3706 }
3707 }
Eric Laurent81784c32012-11-19 14:55:58 -08003708
Andy Hung98ef9782014-03-04 14:46:50 -08003709 // Only if the Effects buffer is enabled and there is data in the
3710 // Effects buffer (buffer valid), we need to
3711 // copy into the sink buffer.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003712 // TODO use mSleepTimeUs == 0 as an additional condition.
Andy Hung98ef9782014-03-04 14:46:50 -08003713 if (mEffectBufferValid) {
3714 //ALOGV("writing effect buffer to sink buffer format %#x", mFormat);
Andy Hung2ddee192015-12-18 17:34:44 -08003715
3716 if (requireMonoBlend()) {
Glenn Kasten03c48d52016-01-27 17:25:17 -08003717 mono_blend(mEffectBuffer, mEffectBufferFormat, mChannelCount, mNormalFrameCount,
3718 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -08003719 }
3720
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01003721 if (!hasFastMixer()) {
3722 // Balance must take effect after mono conversion.
3723 // We do it here if there is no FastMixer.
3724 // mBalance detects zero balance within the class for speed (not needed here).
3725 mBalance.setBalance(mMasterBalance.load());
3726 mBalance.process((float *)mEffectBuffer, mNormalFrameCount);
3727 }
3728
Andy Hung98ef9782014-03-04 14:46:50 -08003729 memcpy_by_audio_format(mSinkBuffer, mFormat, mEffectBuffer, mEffectBufferFormat,
jiabin245cdd92018-12-07 17:55:15 -08003730 mNormalFrameCount * (mChannelCount + mHapticChannelCount));
3731 // The sample data is partially interleaved when haptic channels exist,
3732 // we need to adjust channels here.
3733 if (mHapticChannelCount > 0) {
3734 adjust_channels_non_destructive(mSinkBuffer, mChannelCount, mSinkBuffer,
3735 mChannelCount + mHapticChannelCount,
3736 audio_bytes_per_sample(mFormat),
3737 audio_bytes_per_frame(mChannelCount, mFormat) * mNormalFrameCount);
3738 }
Andy Hung98ef9782014-03-04 14:46:50 -08003739 }
3740
Eric Laurent81784c32012-11-19 14:55:58 -08003741 // enable changes in effect chain
3742 unlockEffectChains(effectChains);
3743
Eric Laurentbfb1b832013-01-07 09:53:42 -08003744 if (!waitingAsyncCallback()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07003745 // mSleepTimeUs == 0 means we must write to audio hardware
3746 if (mSleepTimeUs == 0) {
Andy Hung08fb1742015-05-31 23:22:10 -07003747 ssize_t ret = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003748 // writePeriodNs is updated >= 0 when ret > 0.
3749 int64_t writePeriodNs = -1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003750 if (mBytesRemaining) {
Andy Hung69488c42016-05-16 18:43:33 -07003751 // FIXME rewrite to reduce number of system calls
Andy Hung446f4df2019-02-21 12:26:41 -08003752 const int64_t lastIoBeginNs = systemTime();
Andy Hung08fb1742015-05-31 23:22:10 -07003753 ret = threadLoop_write();
Andy Hung446f4df2019-02-21 12:26:41 -08003754 const int64_t lastIoEndNs = systemTime();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003755 if (ret < 0) {
3756 mBytesRemaining = 0;
Andy Hung446f4df2019-02-21 12:26:41 -08003757 } else if (ret > 0) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08003758 mBytesWritten += ret;
3759 mBytesRemaining -= ret;
Andy Hung446f4df2019-02-21 12:26:41 -08003760 const int64_t frames = ret / mFrameSize;
3761 mFramesWritten += frames;
3762
3763 writePeriodNs = lastIoEndNs - mLastIoEndNs;
3764 // process information relating to write time.
3765 if (audio_has_proportional_frames(mFormat)) {
3766 // we are in a continuous mixing cycle
3767 if (mMixerStatus == MIXER_TRACKS_READY &&
3768 loopCount == lastLoopCountWritten + 1) {
3769
3770 const double jitterMs =
3771 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
3772 {frames, writePeriodNs},
3773 {0, 0} /* lastTimestamp */, mSampleRate);
3774 const double processMs =
3775 (lastIoBeginNs - mLastIoEndNs) * 1e-6;
3776
3777 Mutex::Autolock _l(mLock);
3778 mIoJitterMs.add(jitterMs);
3779 mProcessTimeMs.add(processMs);
3780 }
3781
3782 // write blocked detection
3783 const int64_t deltaWriteNs = lastIoEndNs - lastIoBeginNs;
3784 if (mType == MIXER && deltaWriteNs > maxPeriod) {
3785 mNumDelayedWrites++;
3786 if ((lastIoEndNs - lastWarning) > kWarningThrottleNs) {
3787 ATRACE_NAME("underrun");
3788 ALOGW("write blocked for %lld msecs, "
3789 "%d delayed writes, thread %d",
3790 (long long)deltaWriteNs / NANOS_PER_MILLISECOND,
3791 mNumDelayedWrites, mId);
3792 lastWarning = lastIoEndNs;
3793 }
3794 }
3795 }
3796 // update timing info.
3797 mLastIoBeginNs = lastIoBeginNs;
3798 mLastIoEndNs = lastIoEndNs;
3799 lastLoopCountWritten = loopCount;
Eric Laurentbfb1b832013-01-07 09:53:42 -08003800 }
3801 } else if ((mMixerStatus == MIXER_DRAIN_TRACK) ||
3802 (mMixerStatus == MIXER_DRAIN_ALL)) {
3803 threadLoop_drain();
Eric Laurent81784c32012-11-19 14:55:58 -08003804 }
Andy Hung08fb1742015-05-31 23:22:10 -07003805 if (mType == MIXER && !mStandby) {
Andy Hung08fb1742015-05-31 23:22:10 -07003806
3807 if (mThreadThrottle
3808 && mMixerStatus == MIXER_TRACKS_READY // we are mixing (active tracks)
Andy Hung446f4df2019-02-21 12:26:41 -08003809 && writePeriodNs > 0) { // we have write period info
Andy Hung08fb1742015-05-31 23:22:10 -07003810 // Limit MixerThread data processing to no more than twice the
3811 // expected processing rate.
3812 //
3813 // This helps prevent underruns with NuPlayer and other applications
3814 // which may set up buffers that are close to the minimum size, or use
3815 // deep buffers, and rely on a double-buffering sleep strategy to fill.
3816 //
3817 // The throttle smooths out sudden large data drains from the device,
3818 // e.g. when it comes out of standby, which often causes problems with
3819 // (1) mixer threads without a fast mixer (which has its own warm-up)
3820 // (2) minimum buffer sized tracks (even if the track is full,
3821 // the app won't fill fast enough to handle the sudden draw).
Haynes Mathew Georgef92b2172016-05-09 11:34:15 -07003822 //
3823 // Total time spent in last processing cycle equals time spent in
3824 // 1. threadLoop_write, as well as time spent in
3825 // 2. threadLoop_mix (significant for heavy mixing, especially
3826 // on low tier processors)
Andy Hung08fb1742015-05-31 23:22:10 -07003827
Andy Hung446f4df2019-02-21 12:26:41 -08003828 // it's OK if deltaMs is an overestimate.
3829
3830 const int32_t deltaMs = writePeriodNs / NANOS_PER_MILLISECOND;
Ivan Lozanoe02bc542017-10-26 09:51:54 -07003831
Ivan Lozanoea04d392017-11-07 14:37:07 -08003832 const int32_t throttleMs = (int32_t)mHalfBufferMs - deltaMs;
Andy Hung08fb1742015-05-31 23:22:10 -07003833 if ((signed)mHalfBufferMs >= throttleMs && throttleMs > 0) {
3834 usleep(throttleMs * 1000);
Andy Hung40eb1a12015-06-18 13:42:02 -07003835 // notify of throttle start on verbose log
3836 ALOGV_IF(mThreadThrottleEndMs == mThreadThrottleTimeMs,
3837 "mixer(%p) throttle begin:"
3838 " ret(%zd) deltaMs(%d) requires sleep %d ms",
Andy Hung08fb1742015-05-31 23:22:10 -07003839 this, ret, deltaMs, throttleMs);
Andy Hung40eb1a12015-06-18 13:42:02 -07003840 mThreadThrottleTimeMs += throttleMs;
Andy Hung0a31ddd2016-07-06 19:10:29 -07003841 // Throttle must be attributed to the previous mixer loop's write time
3842 // to allow back-to-back throttling.
Andy Hung446f4df2019-02-21 12:26:41 -08003843 // This also ensures proper timing statistics.
3844 mLastIoEndNs = systemTime(); // we fetch the write end time again.
Andy Hung40eb1a12015-06-18 13:42:02 -07003845 } else {
3846 uint32_t diff = mThreadThrottleTimeMs - mThreadThrottleEndMs;
3847 if (diff > 0) {
3848 // notify of throttle end on debug log
Andy Hung3ea004d2016-05-05 16:48:37 -07003849 // but prevent spamming for bluetooth
jiabin10d86fd2019-10-31 17:20:42 -07003850 ALOGD_IF(!isSingleDeviceType(
3851 outDeviceTypes(), audio_is_a2dp_out_device) &&
3852 !isSingleDeviceType(
3853 outDeviceTypes(), audio_is_hearing_aid_out_device),
Andy Hung3ea004d2016-05-05 16:48:37 -07003854 "mixer(%p) throttle end: throttle time(%u)", this, diff);
Andy Hung40eb1a12015-06-18 13:42:02 -07003855 mThreadThrottleEndMs = mThreadThrottleTimeMs;
3856 }
Andy Hung08fb1742015-05-31 23:22:10 -07003857 }
3858 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003859 }
Eric Laurent81784c32012-11-19 14:55:58 -08003860
Eric Laurentbfb1b832013-01-07 09:53:42 -08003861 } else {
Glenn Kastene7754022014-10-31 12:11:26 -07003862 ATRACE_BEGIN("sleep");
Eric Laurente93cc032016-05-05 10:15:10 -07003863 Mutex::Autolock _l(mLock);
rago1bb90822017-05-02 18:31:48 -07003864 // suspended requires accurate metering of sleep time.
3865 if (isSuspended()) {
3866 // advance by expected sleepTime
3867 timeLoopNextNs += microseconds((nsecs_t)mSleepTimeUs);
3868 const nsecs_t nowNs = systemTime();
3869
3870 // compute expected next time vs current time.
3871 // (negative deltas are treated as delays).
3872 nsecs_t deltaNs = timeLoopNextNs - nowNs;
3873 if (deltaNs < -kMaxNextBufferDelayNs) {
3874 // Delays longer than the max allowed trigger a reset.
3875 ALOGV("DelayNs: %lld, resetting timeLoopNextNs", (long long) deltaNs);
3876 deltaNs = microseconds((nsecs_t)mSleepTimeUs);
3877 timeLoopNextNs = nowNs + deltaNs;
3878 } else if (deltaNs < 0) {
3879 // Delays within the max delay allowed: zero the delta/sleepTime
3880 // to help the system catch up in the next iteration(s)
3881 ALOGV("DelayNs: %lld, catching-up", (long long) deltaNs);
3882 deltaNs = 0;
3883 }
3884 // update sleep time (which is >= 0)
3885 mSleepTimeUs = deltaNs / 1000;
3886 }
Eric Laurente93cc032016-05-05 10:15:10 -07003887 if (!mSignalPending && mConfigEvents.isEmpty() && !exitPending()) {
3888 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)mSleepTimeUs));
Eric Laurent51716182016-02-29 18:00:56 -08003889 }
Glenn Kastene7754022014-10-31 12:11:26 -07003890 ATRACE_END();
Eric Laurentbfb1b832013-01-07 09:53:42 -08003891 }
Eric Laurent81784c32012-11-19 14:55:58 -08003892 }
3893
3894 // Finally let go of removed track(s), without the lock held
3895 // since we can't guarantee the destructors won't acquire that
3896 // same lock. This will also mutate and push a new fast mixer state.
3897 threadLoop_removeTracks(tracksToRemove);
3898 tracksToRemove.clear();
3899
3900 // FIXME I don't understand the need for this here;
3901 // it was in the original code but maybe the
3902 // assignment in saveOutputTracks() makes this unnecessary?
3903 clearOutputTracks();
3904
3905 // Effect chains will be actually deleted here if they were removed from
3906 // mEffectChains list during mixing or effects processing
3907 effectChains.clear();
3908
3909 // FIXME Note that the above .clear() is no longer necessary since effectChains
3910 // is now local to this block, but will keep it for now (at least until merge done).
3911 }
3912
Eric Laurentbfb1b832013-01-07 09:53:42 -08003913 threadLoop_exit();
3914
Eric Laurentcf817a22014-08-04 20:36:31 -07003915 if (!mStandby) {
3916 threadLoop_standby();
3917 mStandby = true;
Eric Laurent81784c32012-11-19 14:55:58 -08003918 }
3919
3920 releaseWakeLock();
3921
3922 ALOGV("Thread %p type %d exiting", this, mType);
3923 return false;
3924}
3925
Eric Laurentbfb1b832013-01-07 09:53:42 -08003926// removeTracks_l() must be called with ThreadBase::mLock held
3927void AudioFlinger::PlaybackThread::removeTracks_l(const Vector< sp<Track> >& tracksToRemove)
3928{
Andy Hungfe726a62018-09-27 15:17:25 -07003929 for (const auto& track : tracksToRemove) {
3930 mActiveTracks.remove(track);
3931 ALOGV("%s(%d): removing track on session %d", __func__, track->id(), track->sessionId());
3932 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
3933 if (chain != 0) {
3934 ALOGV("%s(%d): stopping track on chain %p for session Id: %d",
3935 __func__, track->id(), chain.get(), track->sessionId());
3936 chain->decActiveTrackCnt();
3937 }
3938 // If an external client track, inform APM we're no longer active, and remove if needed.
3939 // We do this under lock so that the state is consistent if the Track is destroyed.
3940 if (track->isExternalTrack()) {
3941 AudioSystem::stopOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08003942 if (track->isTerminated()) {
Andy Hungfe726a62018-09-27 15:17:25 -07003943 AudioSystem::releaseOutput(track->portId());
Eric Laurentbfb1b832013-01-07 09:53:42 -08003944 }
3945 }
Andy Hungfe726a62018-09-27 15:17:25 -07003946 if (track->isTerminated()) {
3947 // remove from our tracks vector
3948 removeTrack_l(track);
3949 }
jiabin57303cc2018-12-18 15:45:57 -08003950 if ((track->channelMask() & AUDIO_CHANNEL_HAPTIC_ALL) != AUDIO_CHANNEL_NONE
3951 && mHapticChannelCount > 0) {
3952 mLock.unlock();
3953 // Unlock due to VibratorService will lock for this call and will
3954 // call Tracks.mute/unmute which also require thread's lock.
3955 AudioFlinger::onExternalVibrationStop(track->getExternalVibration());
3956 mLock.lock();
jiabin245cdd92018-12-07 17:55:15 -08003957 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003958 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08003959}
Eric Laurent81784c32012-11-19 14:55:58 -08003960
Eric Laurentaccc1472013-09-20 09:36:34 -07003961status_t AudioFlinger::PlaybackThread::getTimestamp_l(AudioTimestamp& timestamp)
3962{
3963 if (mNormalSink != 0) {
Andy Hung818e7a32016-02-16 18:08:07 -08003964 ExtendedTimestamp ets;
3965 status_t status = mNormalSink->getTimestamp(ets);
3966 if (status == NO_ERROR) {
3967 status = ets.getBestTimestamp(&timestamp);
3968 }
3969 return status;
Eric Laurentaccc1472013-09-20 09:36:34 -07003970 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003971 if ((mType == OFFLOAD || mType == DIRECT) && mOutput != NULL) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003972 uint64_t position64;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07003973 if (mOutput->getPresentationPosition(&position64, &timestamp.mTime) == OK) {
Eric Laurentaccc1472013-09-20 09:36:34 -07003974 timestamp.mPosition = (uint32_t)position64;
Dean Wheatley30d28422018-11-06 10:27:40 +11003975 if (mDownstreamLatencyStatMs.getN() > 0) {
3976 const uint32_t positionOffset =
3977 (uint32_t)(mDownstreamLatencyStatMs.getMean() * mSampleRate * 1e-3);
3978 if (positionOffset > timestamp.mPosition) {
3979 timestamp.mPosition = 0;
3980 } else {
3981 timestamp.mPosition -= positionOffset;
3982 }
3983 }
Eric Laurentaccc1472013-09-20 09:36:34 -07003984 return NO_ERROR;
3985 }
3986 }
3987 return INVALID_OPERATION;
3988}
Eric Laurent1c333e22014-05-20 10:48:17 -07003989
Eric Laurenteab90452019-06-24 15:17:46 -07003990// For dedicated VoIP outputs, let the HAL apply the stream volume. Track volume is
3991// still applied by the mixer.
3992// All tracks attached to a mixer with flag VOIP_RX are tied to the same
3993// stream type STREAM_VOICE_CALL so this will only change the HAL volume once even
3994// if more than one track are active
3995status_t AudioFlinger::PlaybackThread::handleVoipVolume_l(float *volume)
3996{
3997 status_t result = NO_ERROR;
3998 if ((mOutput->flags & AUDIO_OUTPUT_FLAG_VOIP_RX) != 0) {
3999 if (*volume != mLeftVolFloat) {
4000 result = mOutput->stream->setVolume(*volume, *volume);
4001 ALOGE_IF(result != OK,
4002 "Error when setting output stream volume: %d", result);
4003 if (result == NO_ERROR) {
4004 mLeftVolFloat = *volume;
4005 }
4006 }
4007 // if stream volume was successfully sent to the HAL, mLeftVolFloat == v here and we
4008 // remove stream volume contribution from software volume.
4009 if (mLeftVolFloat == *volume) {
4010 *volume = 1.0f;
4011 }
4012 }
4013 return result;
4014}
4015
Eric Laurent054d9d32015-04-24 08:48:48 -07004016status_t AudioFlinger::MixerThread::createAudioPatch_l(const struct audio_patch *patch,
4017 audio_patch_handle_t *handle)
4018{
Andy Hungf60abce2016-08-26 11:37:54 -07004019 status_t status;
4020 if (property_get_bool("af.patch_park", false /* default_value */)) {
4021 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4022 // or if HAL does not properly lock against access.
4023 AutoPark<FastMixer> park(mFastMixer);
4024 status = PlaybackThread::createAudioPatch_l(patch, handle);
4025 } else {
4026 status = PlaybackThread::createAudioPatch_l(patch, handle);
4027 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004028 return status;
4029}
4030
Eric Laurent1c333e22014-05-20 10:48:17 -07004031status_t AudioFlinger::PlaybackThread::createAudioPatch_l(const struct audio_patch *patch,
4032 audio_patch_handle_t *handle)
4033{
4034 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004035
4036 // store new device and send to effects
4037 audio_devices_t type = AUDIO_DEVICE_NONE;
jiabin10d86fd2019-10-31 17:20:42 -07004038 AudioDeviceTypeAddrVector deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004039 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabin10d86fd2019-10-31 17:20:42 -07004040 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
4041 && !mOutput->audioHwDev->supportsAudioPatches(),
4042 "Enumerated device type(%#x) must not be used "
4043 "as it does not support audio patches",
4044 patch->sinks[i].ext.device.type);
Eric Laurent054d9d32015-04-24 08:48:48 -07004045 type |= patch->sinks[i].ext.device.type;
jiabin10d86fd2019-10-31 17:20:42 -07004046 deviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
4047 patch->sinks[i].ext.device.address));
Eric Laurent054d9d32015-04-24 08:48:48 -07004048 }
4049
François Gaffie0c280aa2018-07-25 10:02:15 +02004050 audio_port_handle_t sinkPortId = patch->sinks[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07004051#ifdef ADD_BATTERY_DATA
4052 // when changing the audio output device, call addBatteryData to notify
4053 // the change
jiabin10d86fd2019-10-31 17:20:42 -07004054 if (outDeviceTypes() != deviceTypes) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004055 uint32_t params = 0;
4056 // check whether speaker is on
jiabin10d86fd2019-10-31 17:20:42 -07004057 if (deviceTypes.count(AUDIO_DEVICE_OUT_SPEAKER) > 0) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004058 params |= IMediaPlayerService::kBatteryDataSpeakerOn;
Eric Laurent1c333e22014-05-20 10:48:17 -07004059 }
4060
Eric Laurent054d9d32015-04-24 08:48:48 -07004061 // check if any other device (except speaker) is on
jiabin10d86fd2019-10-31 17:20:42 -07004062 if (!isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_SPEAKER)) {
Eric Laurent054d9d32015-04-24 08:48:48 -07004063 params |= IMediaPlayerService::kBatteryDataOtherAudioDeviceOn;
4064 }
4065
4066 if (params != 0) {
4067 addBatteryData(params);
4068 }
4069 }
4070#endif
4071
4072 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabinb8269fd2019-11-11 12:16:27 -08004073 mEffectChains[i]->setDevices_l(deviceTypeAddrs);
Eric Laurent054d9d32015-04-24 08:48:48 -07004074 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07004075
jiabin10d86fd2019-10-31 17:20:42 -07004076 // mPatch.num_sinks is not set when the thread is created so that
4077 // the first patch creation triggers an ioConfigChanged callback
4078 bool configChanged = (mPatch.num_sinks == 0) ||
4079 (mPatch.sinks[0].id != sinkPortId);
Eric Laurent296fb132015-05-01 11:38:42 -07004080 mPatch = *patch;
jiabin10d86fd2019-10-31 17:20:42 -07004081 mOutDeviceTypeAddrs = deviceTypeAddrs;
Eric Laurent054d9d32015-04-24 08:48:48 -07004082
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004083 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004084 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4085 status = hwDevice->createAudioPatch(patch->num_sources,
4086 patch->sources,
4087 patch->num_sinks,
4088 patch->sinks,
4089 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004090 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004091 char *address;
4092 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
4093 //FIXME: we only support address on first sink with HAL version < 3.0
4094 address = audio_device_address_to_parameter(
4095 patch->sinks[0].ext.device.type,
4096 patch->sinks[0].ext.device.address);
4097 } else {
4098 address = (char *)calloc(1, 1);
4099 }
4100 AudioParameter param = AudioParameter(String8(address));
4101 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07004102 param.addInt(String8(AudioParameter::keyRouting), (int)type);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004103 status = mOutput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07004104 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07004105 }
Eric Laurente8726fe2015-06-26 09:39:24 -07004106 if (configChanged) {
4107 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
4108 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004109 return status;
4110}
4111
Eric Laurent054d9d32015-04-24 08:48:48 -07004112status_t AudioFlinger::MixerThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4113{
Andy Hungf60abce2016-08-26 11:37:54 -07004114 status_t status;
4115 if (property_get_bool("af.patch_park", false /* default_value */)) {
4116 // Park FastMixer to avoid potential DOS issues with writing to the HAL
4117 // or if HAL does not properly lock against access.
4118 AutoPark<FastMixer> park(mFastMixer);
4119 status = PlaybackThread::releaseAudioPatch_l(handle);
4120 } else {
4121 status = PlaybackThread::releaseAudioPatch_l(handle);
4122 }
Eric Laurent054d9d32015-04-24 08:48:48 -07004123 return status;
4124}
4125
Eric Laurent1c333e22014-05-20 10:48:17 -07004126status_t AudioFlinger::PlaybackThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
4127{
4128 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07004129
jiabin10d86fd2019-10-31 17:20:42 -07004130 mPatch = audio_patch{};
4131 mOutDeviceTypeAddrs.clear();
Eric Laurent054d9d32015-04-24 08:48:48 -07004132
Mikhail Naganov9ee05402016-10-13 15:58:17 -07004133 if (mOutput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07004134 sp<DeviceHalInterface> hwDevice = mOutput->audioHwDev->hwDevice();
4135 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004136 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07004137 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07004138 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004139 status = mOutput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07004140 }
4141 return status;
4142}
4143
Eric Laurent83b88082014-06-20 18:31:16 -07004144void AudioFlinger::PlaybackThread::addPatchTrack(const sp<PatchTrack>& track)
4145{
4146 Mutex::Autolock _l(mLock);
4147 mTracks.add(track);
4148}
4149
4150void AudioFlinger::PlaybackThread::deletePatchTrack(const sp<PatchTrack>& track)
4151{
4152 Mutex::Autolock _l(mLock);
4153 destroyTrack_l(track);
4154}
4155
Mikhail Naganovdc769682018-05-04 15:34:08 -07004156void AudioFlinger::PlaybackThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07004157{
Mikhail Naganovdc769682018-05-04 15:34:08 -07004158 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07004159 config->role = AUDIO_PORT_ROLE_SOURCE;
4160 config->ext.mix.hw_module = mOutput->audioHwDev->handle();
4161 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07004162 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
4163 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
4164 config->flags.output = mOutput->flags;
4165 }
Eric Laurent83b88082014-06-20 18:31:16 -07004166}
4167
Eric Laurent81784c32012-11-19 14:55:58 -08004168// ----------------------------------------------------------------------------
4169
4170AudioFlinger::MixerThread::MixerThread(const sp<AudioFlinger>& audioFlinger, AudioStreamOut* output,
jiabin10d86fd2019-10-31 17:20:42 -07004171 audio_io_handle_t id, bool systemReady, type_t type)
4172 : PlaybackThread(audioFlinger, output, id, type, systemReady),
Eric Laurent81784c32012-11-19 14:55:58 -08004173 // mAudioMixer below
4174 // mFastMixer below
Andy Hung2ddee192015-12-18 17:34:44 -08004175 mFastMixerFutex(0),
4176 mMasterMono(false)
Eric Laurent81784c32012-11-19 14:55:58 -08004177 // mOutputSink below
4178 // mPipeSink below
4179 // mNormalSink below
4180{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01004181 setMasterBalance(audioFlinger->getMasterBalance_l());
jiabin10d86fd2019-10-31 17:20:42 -07004182 ALOGV("MixerThread() id=%d type=%d", id, type);
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004183 ALOGV("mSampleRate=%u, mChannelMask=%#x, mChannelCount=%u, mFormat=%#x, mFrameSize=%zu, "
Glenn Kastenc42e9b42016-03-21 11:35:03 -07004184 "mFrameCount=%zu, mNormalFrameCount=%zu",
Eric Laurent81784c32012-11-19 14:55:58 -08004185 mSampleRate, mChannelMask, mChannelCount, mFormat, mFrameSize, mFrameCount,
4186 mNormalFrameCount);
4187 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
4188
Andy Hungfbfc3952015-01-15 13:33:51 -08004189 if (type == DUPLICATING) {
4190 // The Duplicating thread uses the AudioMixer and delivers data to OutputTracks
4191 // (downstream MixerThreads) in DuplicatingThread::threadLoop_write().
4192 // Do not create or use mFastMixer, mOutputSink, mPipeSink, or mNormalSink.
4193 return;
4194 }
Eric Laurent81784c32012-11-19 14:55:58 -08004195 // create an NBAIO sink for the HAL output stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07004196 mOutputSink = new AudioStreamOutSink(output->stream);
Eric Laurent81784c32012-11-19 14:55:58 -08004197 size_t numCounterOffers = 0;
jiabin245cdd92018-12-07 17:55:15 -08004198 const NBAIO_Format offers[1] = {Format_from_SR_C(
4199 mSampleRate, mChannelCount + mHapticChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004200#if !LOG_NDEBUG
4201 ssize_t index =
4202#else
4203 (void)
4204#endif
4205 mOutputSink->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004206 ALOG_ASSERT(index == 0);
4207
4208 // initialize fast mixer depending on configuration
4209 bool initFastMixer;
4210 switch (kUseFastMixer) {
4211 case FastMixer_Never:
4212 initFastMixer = false;
4213 break;
4214 case FastMixer_Always:
4215 initFastMixer = true;
4216 break;
4217 case FastMixer_Static:
4218 case FastMixer_Dynamic:
Andy Hungfda69402017-02-15 14:33:12 -08004219 // FastMixer was designed to operate with a HAL that pulls at a regular rate,
4220 // where the period is less than an experimentally determined threshold that can be
4221 // scheduled reliably with CFS. However, the BT A2DP HAL is
4222 // bursty (does not pull at a regular rate) and so cannot operate with FastMixer.
4223 initFastMixer = mFrameCount < mNormalFrameCount
jiabin10d86fd2019-10-31 17:20:42 -07004224 && Intersection(outDeviceTypes(), getAudioDeviceOutAllA2dpSet()).empty();
Eric Laurent81784c32012-11-19 14:55:58 -08004225 break;
4226 }
Andy Hungfda69402017-02-15 14:33:12 -08004227 ALOGW_IF(initFastMixer == false && mFrameCount < mNormalFrameCount,
4228 "FastMixer is preferred for this sink as frameCount %zu is less than threshold %zu",
4229 mFrameCount, mNormalFrameCount);
Eric Laurent81784c32012-11-19 14:55:58 -08004230 if (initFastMixer) {
Andy Hung1258c1a2014-05-23 21:22:17 -07004231 audio_format_t fastMixerFormat;
4232 if (mMixerBufferEnabled && mEffectBufferEnabled) {
4233 fastMixerFormat = AUDIO_FORMAT_PCM_FLOAT;
4234 } else {
4235 fastMixerFormat = AUDIO_FORMAT_PCM_16_BIT;
4236 }
4237 if (mFormat != fastMixerFormat) {
4238 // change our Sink format to accept our intermediate precision
4239 mFormat = fastMixerFormat;
4240 free(mSinkBuffer);
jiabin245cdd92018-12-07 17:55:15 -08004241 mFrameSize = audio_bytes_per_frame(mChannelCount + mHapticChannelCount, mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004242 const size_t sinkBufferSize = mNormalFrameCount * mFrameSize;
4243 (void)posix_memalign(&mSinkBuffer, 32, sinkBufferSize);
4244 }
Eric Laurent81784c32012-11-19 14:55:58 -08004245
4246 // create a MonoPipe to connect our submix to FastMixer
4247 NBAIO_Format format = mOutputSink->format();
Andy Hung8946a282018-04-19 20:04:56 -07004248
Andy Hung1258c1a2014-05-23 21:22:17 -07004249 // adjust format to match that of the Fast Mixer
Glenn Kasten49f36ba2017-12-06 13:02:02 -08004250 ALOGV("format changed from %#x to %#x", format.mFormat, fastMixerFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -07004251 format.mFormat = fastMixerFormat;
4252 format.mFrameSize = audio_bytes_per_sample(format.mFormat) * format.mChannelCount;
4253
Eric Laurent81784c32012-11-19 14:55:58 -08004254 // This pipe depth compensates for scheduling latency of the normal mixer thread.
4255 // When it wakes up after a maximum latency, it runs a few cycles quickly before
4256 // finally blocking. Note the pipe implementation rounds up the request to a power of 2.
4257 MonoPipe *monoPipe = new MonoPipe(mNormalFrameCount * 4, format, true /*writeCanBlock*/);
4258 const NBAIO_Format offers[1] = {format};
4259 size_t numCounterOffers = 0;
Andy Hung8946a282018-04-19 20:04:56 -07004260#if !LOG_NDEBUG
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07004261 ssize_t index =
4262#else
4263 (void)
4264#endif
4265 monoPipe->negotiate(offers, 1, NULL, numCounterOffers);
Eric Laurent81784c32012-11-19 14:55:58 -08004266 ALOG_ASSERT(index == 0);
4267 monoPipe->setAvgFrames((mScreenState & 1) ?
4268 (monoPipe->maxFrames() * 7) / 8 : mNormalFrameCount * 2);
4269 mPipeSink = monoPipe;
4270
Eric Laurent81784c32012-11-19 14:55:58 -08004271 // create fast mixer and configure it initially with just one fast track for our submix
Andy Hung8946a282018-04-19 20:04:56 -07004272 mFastMixer = new FastMixer(mId);
Eric Laurent81784c32012-11-19 14:55:58 -08004273 FastMixerStateQueue *sq = mFastMixer->sq();
4274#ifdef STATE_QUEUE_DUMP
4275 sq->setObserverDump(&mStateQueueObserverDump);
4276 sq->setMutatorDump(&mStateQueueMutatorDump);
4277#endif
4278 FastMixerState *state = sq->begin();
4279 FastTrack *fastTrack = &state->mFastTracks[0];
4280 // wrap the source side of the MonoPipe to make it an AudioBufferProvider
4281 fastTrack->mBufferProvider = new SourceAudioBufferProvider(new MonoPipeReader(monoPipe));
4282 fastTrack->mVolumeProvider = NULL;
jiabin245cdd92018-12-07 17:55:15 -08004283 fastTrack->mChannelMask = mChannelMask | mHapticChannelMask; // mPipeSink channel mask for
4284 // audio to FastMixer
Andy Hunge8a1ced2014-05-09 15:02:21 -07004285 fastTrack->mFormat = mFormat; // mPipeSink format for audio to FastMixer
jiabin245cdd92018-12-07 17:55:15 -08004286 fastTrack->mHapticPlaybackEnabled = mHapticChannelMask != AUDIO_CHANNEL_NONE;
jiabin84114c32019-04-10 16:38:07 -07004287 fastTrack->mHapticIntensity = AudioMixer::HAPTIC_SCALE_NONE;
Eric Laurent81784c32012-11-19 14:55:58 -08004288 fastTrack->mGeneration++;
4289 state->mFastTracksGen++;
4290 state->mTrackMask = 1;
4291 // fast mixer will use the HAL output sink
4292 state->mOutputSink = mOutputSink.get();
4293 state->mOutputSinkGen++;
4294 state->mFrameCount = mFrameCount;
jiabin245cdd92018-12-07 17:55:15 -08004295 // specify sink channel mask when haptic channel mask present as it can not
4296 // be calculated directly from channel count
4297 state->mSinkChannelMask = mHapticChannelMask == AUDIO_CHANNEL_NONE
4298 ? AUDIO_CHANNEL_NONE : mChannelMask | mHapticChannelMask;
Eric Laurent81784c32012-11-19 14:55:58 -08004299 state->mCommand = FastMixerState::COLD_IDLE;
4300 // already done in constructor initialization list
4301 //mFastMixerFutex = 0;
4302 state->mColdFutexAddr = &mFastMixerFutex;
4303 state->mColdGen++;
4304 state->mDumpState = &mFastMixerDumpState;
Glenn Kasten9e58b552013-01-18 15:09:48 -08004305 mFastMixerNBLogWriter = audioFlinger->newWriter_l(kFastMixerLogSize, "FastMixer");
4306 state->mNBLogWriter = mFastMixerNBLogWriter.get();
Eric Laurent81784c32012-11-19 14:55:58 -08004307 sq->end();
4308 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4309
Eric Tan0513b5d2018-09-17 10:32:48 -07004310 NBLog::thread_info_t info;
4311 info.id = mId;
4312 info.type = NBLog::FASTMIXER;
4313 mFastMixerNBLogWriter->log<NBLog::EVENT_THREAD_INFO>(info);
4314
Eric Laurent81784c32012-11-19 14:55:58 -08004315 // start the fast mixer
4316 mFastMixer->run("FastMixer", PRIORITY_URGENT_AUDIO);
4317 pid_t tid = mFastMixer->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004318 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08004319 stream()->setHalThreadPriority(kPriorityFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08004320
4321#ifdef AUDIO_WATCHDOG
4322 // create and start the watchdog
4323 mAudioWatchdog = new AudioWatchdog();
4324 mAudioWatchdog->setDump(&mAudioWatchdogDump);
4325 mAudioWatchdog->run("AudioWatchdog", PRIORITY_URGENT_AUDIO);
4326 tid = mAudioWatchdog->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07004327 sendPrioConfigEvent(getpid(), tid, kPriorityFastMixer, false /*forApp*/);
Eric Laurent81784c32012-11-19 14:55:58 -08004328#endif
Andy Hung8946a282018-04-19 20:04:56 -07004329 } else {
4330#ifdef TEE_SINK
4331 // Only use the MixerThread tee if there is no FastMixer.
4332 mTee.set(mOutputSink->format(), NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
4333 mTee.setId(std::string("_") + std::to_string(mId) + "_M");
4334#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004335 }
4336
4337 switch (kUseFastMixer) {
4338 case FastMixer_Never:
4339 case FastMixer_Dynamic:
4340 mNormalSink = mOutputSink;
4341 break;
4342 case FastMixer_Always:
4343 mNormalSink = mPipeSink;
4344 break;
4345 case FastMixer_Static:
4346 mNormalSink = initFastMixer ? mPipeSink : mOutputSink;
4347 break;
4348 }
4349}
4350
4351AudioFlinger::MixerThread::~MixerThread()
4352{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004353 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004354 FastMixerStateQueue *sq = mFastMixer->sq();
4355 FastMixerState *state = sq->begin();
4356 if (state->mCommand == FastMixerState::COLD_IDLE) {
4357 int32_t old = android_atomic_inc(&mFastMixerFutex);
4358 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004359 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004360 }
4361 }
4362 state->mCommand = FastMixerState::EXIT;
4363 sq->end();
4364 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4365 mFastMixer->join();
4366 // Though the fast mixer thread has exited, it's state queue is still valid.
4367 // We'll use that extract the final state which contains one remaining fast track
4368 // corresponding to our sub-mix.
4369 state = sq->begin();
4370 ALOG_ASSERT(state->mTrackMask == 1);
4371 FastTrack *fastTrack = &state->mFastTracks[0];
4372 ALOG_ASSERT(fastTrack->mBufferProvider != NULL);
4373 delete fastTrack->mBufferProvider;
4374 sq->end(false /*didModify*/);
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004375 mFastMixer.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08004376#ifdef AUDIO_WATCHDOG
4377 if (mAudioWatchdog != 0) {
4378 mAudioWatchdog->requestExit();
4379 mAudioWatchdog->requestExitAndWait();
4380 mAudioWatchdog.clear();
4381 }
4382#endif
4383 }
Glenn Kasten9e58b552013-01-18 15:09:48 -08004384 mAudioFlinger->unregisterWriter(mFastMixerNBLogWriter);
Eric Laurent81784c32012-11-19 14:55:58 -08004385 delete mAudioMixer;
4386}
4387
4388
4389uint32_t AudioFlinger::MixerThread::correctLatency_l(uint32_t latency) const
4390{
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004391 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004392 MonoPipe *pipe = (MonoPipe *)mPipeSink.get();
4393 latency += (pipe->getAvgFrames() * 1000) / mSampleRate;
4394 }
4395 return latency;
4396}
4397
Eric Laurentbfb1b832013-01-07 09:53:42 -08004398ssize_t AudioFlinger::MixerThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08004399{
4400 // FIXME we should only do one push per cycle; confirm this is true
4401 // Start the fast mixer if it's not already running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004402 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004403 FastMixerStateQueue *sq = mFastMixer->sq();
4404 FastMixerState *state = sq->begin();
4405 if (state->mCommand != FastMixerState::MIX_WRITE &&
4406 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)) {
4407 if (state->mCommand == FastMixerState::COLD_IDLE) {
Eric Laurenta2ab4502015-09-09 12:25:51 -07004408
4409 // FIXME workaround for first HAL write being CPU bound on some devices
4410 ATRACE_BEGIN("write");
4411 mOutput->write((char *)mSinkBuffer, 0);
4412 ATRACE_END();
4413
Eric Laurent81784c32012-11-19 14:55:58 -08004414 int32_t old = android_atomic_inc(&mFastMixerFutex);
4415 if (old == -1) {
Elliott Hughesee499292014-05-21 17:55:51 -07004416 (void) syscall(__NR_futex, &mFastMixerFutex, FUTEX_WAKE_PRIVATE, 1);
Eric Laurent81784c32012-11-19 14:55:58 -08004417 }
4418#ifdef AUDIO_WATCHDOG
4419 if (mAudioWatchdog != 0) {
4420 mAudioWatchdog->resume();
4421 }
4422#endif
4423 }
4424 state->mCommand = FastMixerState::MIX_WRITE;
Glenn Kastend797a9d2015-03-02 14:19:25 -08004425#ifdef FAST_THREAD_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -07004426 mFastMixerDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08004427 FastThreadDumpState::kSamplingNforLowRamDevice : FastThreadDumpState::kSamplingN);
Glenn Kastend797a9d2015-03-02 14:19:25 -08004428#endif
Eric Laurent81784c32012-11-19 14:55:58 -08004429 sq->end();
4430 sq->push(FastMixerStateQueue::BLOCK_UNTIL_PUSHED);
4431 if (kUseFastMixer == FastMixer_Dynamic) {
4432 mNormalSink = mPipeSink;
4433 }
4434 } else {
4435 sq->end(false /*didModify*/);
4436 }
4437 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08004438 return PlaybackThread::threadLoop_write();
Eric Laurent81784c32012-11-19 14:55:58 -08004439}
4440
4441void AudioFlinger::MixerThread::threadLoop_standby()
4442{
4443 // Idle the fast mixer if it's currently running
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004444 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004445 FastMixerStateQueue *sq = mFastMixer->sq();
4446 FastMixerState *state = sq->begin();
4447 if (!(state->mCommand & FastMixerState::IDLE)) {
Andy Hung2148bf02016-11-28 19:01:02 -08004448 // Report any frames trapped in the Monopipe
4449 MonoPipe *monoPipe = (MonoPipe *)mPipeSink.get();
4450 const long long pipeFrames = monoPipe->maxFrames() - monoPipe->availableToWrite();
4451 mLocalLog.log("threadLoop_standby: framesWritten:%lld suspendedFrames:%lld "
4452 "monoPipeWritten:%lld monoPipeLeft:%lld",
4453 (long long)mFramesWritten, (long long)mSuspendedFrames,
4454 (long long)mPipeSink->framesWritten(), pipeFrames);
4455 mLocalLog.log("threadLoop_standby: %s", mTimestamp.toString().c_str());
4456
Eric Laurent81784c32012-11-19 14:55:58 -08004457 state->mCommand = FastMixerState::COLD_IDLE;
4458 state->mColdFutexAddr = &mFastMixerFutex;
4459 state->mColdGen++;
4460 mFastMixerFutex = 0;
4461 sq->end();
4462 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
4463 sq->push(FastMixerStateQueue::BLOCK_UNTIL_ACKED);
4464 if (kUseFastMixer == FastMixer_Dynamic) {
4465 mNormalSink = mOutputSink;
4466 }
4467#ifdef AUDIO_WATCHDOG
4468 if (mAudioWatchdog != 0) {
4469 mAudioWatchdog->pause();
4470 }
4471#endif
4472 } else {
4473 sq->end(false /*didModify*/);
4474 }
4475 }
4476 PlaybackThread::threadLoop_standby();
4477}
4478
Eric Laurentbfb1b832013-01-07 09:53:42 -08004479bool AudioFlinger::PlaybackThread::waitingAsyncCallback_l()
4480{
4481 return false;
4482}
4483
4484bool AudioFlinger::PlaybackThread::shouldStandby_l()
4485{
4486 return !mStandby;
4487}
4488
4489bool AudioFlinger::PlaybackThread::waitingAsyncCallback()
4490{
4491 Mutex::Autolock _l(mLock);
4492 return waitingAsyncCallback_l();
4493}
4494
Eric Laurent81784c32012-11-19 14:55:58 -08004495// shared by MIXER and DIRECT, overridden by DUPLICATING
4496void AudioFlinger::PlaybackThread::threadLoop_standby()
4497{
4498 ALOGV("Audio hardware entering standby, mixer %p, suspend count %d", this, mSuspended);
Phil Burk062e67a2015-02-11 13:40:50 -08004499 mOutput->standby();
Eric Laurentbfb1b832013-01-07 09:53:42 -08004500 if (mUseAsyncWrite != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07004501 // discard any pending drain or write ack by incrementing sequence
4502 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
4503 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08004504 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07004505 mCallbackThread->setWriteBlocked(mWriteAckSequence);
4506 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08004507 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08004508 mHwPaused = false;
Eric Laurent81784c32012-11-19 14:55:58 -08004509}
4510
Haynes Mathew George4c6a4332014-01-15 12:31:39 -08004511void AudioFlinger::PlaybackThread::onAddNewTrack_l()
4512{
4513 ALOGV("signal playback thread");
4514 broadcast_l();
4515}
4516
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07004517void AudioFlinger::PlaybackThread::onAsyncError()
4518{
4519 for (int i = AUDIO_STREAM_SYSTEM; i < (int)AUDIO_STREAM_CNT; i++) {
4520 invalidateTracks((audio_stream_type_t)i);
4521 }
4522}
4523
Eric Laurent81784c32012-11-19 14:55:58 -08004524void AudioFlinger::MixerThread::threadLoop_mix()
4525{
Eric Laurent81784c32012-11-19 14:55:58 -08004526 // mix buffers...
Glenn Kastend79072e2016-01-06 08:41:20 -08004527 mAudioMixer->process();
Andy Hung25c2dac2014-02-27 14:56:00 -08004528 mCurrentWriteLength = mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004529 // increase sleep time progressively when application underrun condition clears.
4530 // Only increase sleep time if the mixer is ready for two consecutive times to avoid
4531 // that a steady state of alternating ready/not ready conditions keeps the sleep time
4532 // such that we would underrun the audio HAL.
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004533 if ((mSleepTimeUs == 0) && (sleepTimeShift > 0)) {
Eric Laurent81784c32012-11-19 14:55:58 -08004534 sleepTimeShift--;
4535 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004536 mSleepTimeUs = 0;
4537 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08004538 //TODO: delay standby when effects have a tail
Glenn Kasten4c053ea2014-09-28 14:41:07 -07004539
Eric Laurent81784c32012-11-19 14:55:58 -08004540}
4541
4542void AudioFlinger::MixerThread::threadLoop_sleepTime()
4543{
4544 // If no tracks are ready, sleep once for the duration of an output
4545 // buffer size, then write 0s to the output
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004546 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004547 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Andy Hung06d13222018-05-03 20:13:31 -07004548 if (mPipeSink.get() != nullptr && mPipeSink == mNormalSink) {
4549 // Using the Monopipe availableToWrite, we estimate the
4550 // sleep time to retry for more data (before we underrun).
4551 MonoPipe *monoPipe = static_cast<MonoPipe *>(mPipeSink.get());
4552 const ssize_t availableToWrite = mPipeSink->availableToWrite();
4553 const size_t pipeFrames = monoPipe->maxFrames();
4554 const size_t framesLeft = pipeFrames - max(availableToWrite, 0);
4555 // HAL_framecount <= framesDelay ~ framesLeft / 2 <= Normal_Mixer_framecount
4556 const size_t framesDelay = std::min(
4557 mNormalFrameCount, max(framesLeft / 2, mFrameCount));
4558 ALOGV("pipeFrames:%zu framesLeft:%zu framesDelay:%zu",
4559 pipeFrames, framesLeft, framesDelay);
4560 mSleepTimeUs = framesDelay * MICROS_PER_SECOND / mSampleRate;
4561 } else {
4562 mSleepTimeUs = mActiveSleepTimeUs >> sleepTimeShift;
4563 if (mSleepTimeUs < kMinThreadSleepTimeUs) {
4564 mSleepTimeUs = kMinThreadSleepTimeUs;
4565 }
4566 // reduce sleep time in case of consecutive application underruns to avoid
4567 // starving the audio HAL. As activeSleepTimeUs() is larger than a buffer
4568 // duration we would end up writing less data than needed by the audio HAL if
4569 // the condition persists.
4570 if (sleepTimeShift < kMaxThreadSleepTimeShift) {
4571 sleepTimeShift++;
4572 }
Eric Laurent81784c32012-11-19 14:55:58 -08004573 }
4574 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004575 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08004576 }
4577 } else if (mBytesWritten != 0 || (mMixerStatus == MIXER_TRACKS_ENABLED)) {
Andy Hung98ef9782014-03-04 14:46:50 -08004578 // clear out mMixerBuffer or mSinkBuffer, to ensure buffers are cleared
4579 // before effects processing or output.
4580 if (mMixerBufferValid) {
4581 memset(mMixerBuffer, 0, mMixerBufferSize);
4582 } else {
4583 memset(mSinkBuffer, 0, mSinkBufferSize);
4584 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07004585 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08004586 ALOGV_IF(mBytesWritten == 0 && (mMixerStatus == MIXER_TRACKS_ENABLED),
4587 "anticipated start");
4588 }
4589 // TODO add standby time extension fct of effect tail
4590}
4591
4592// prepareTracks_l() must be called with ThreadBase::mLock held
4593AudioFlinger::PlaybackThread::mixer_state AudioFlinger::MixerThread::prepareTracks_l(
4594 Vector< sp<Track> > *tracksToRemove)
4595{
Andy Hungc0691382018-09-12 18:01:57 -07004596 // clean up deleted track ids in AudioMixer before allocating new tracks
4597 (void)mTracks.processDeletedTrackIds([this](int trackId) {
4598 // for each trackId, destroy it in the AudioMixer
4599 if (mAudioMixer->exists(trackId)) {
4600 mAudioMixer->destroy(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004601 }
4602 });
Andy Hungc0691382018-09-12 18:01:57 -07004603 mTracks.clearDeletedTrackIds();
Eric Laurent81784c32012-11-19 14:55:58 -08004604
4605 mixer_state mixerStatus = MIXER_IDLE;
4606 // find out which tracks need to be processed
4607 size_t count = mActiveTracks.size();
4608 size_t mixedTracks = 0;
4609 size_t tracksWithEffect = 0;
4610 // counts only _active_ fast tracks
4611 size_t fastTracks = 0;
4612 uint32_t resetMask = 0; // bit mask of fast tracks that need to be reset
4613
4614 float masterVolume = mMasterVolume;
4615 bool masterMute = mMasterMute;
4616
4617 if (masterMute) {
4618 masterVolume = 0;
4619 }
4620 // Delegate master volume control to effect in output mix effect chain if needed
4621 sp<EffectChain> chain = getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
4622 if (chain != 0) {
4623 uint32_t v = (uint32_t)(masterVolume * (1 << 24));
4624 chain->setVolume_l(&v, &v);
4625 masterVolume = (float)((v + (1 << 23)) >> 24);
4626 chain.clear();
4627 }
4628
4629 // prepare a new state to push
4630 FastMixerStateQueue *sq = NULL;
4631 FastMixerState *state = NULL;
4632 bool didModify = false;
4633 FastMixerStateQueue::block_t block = FastMixerStateQueue::BLOCK_UNTIL_PUSHED;
Andy Hungf2285312017-02-14 18:31:59 -08004634 bool coldIdle = false;
Glenn Kasten4d23ca32014-05-13 10:39:51 -07004635 if (mFastMixer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004636 sq = mFastMixer->sq();
4637 state = sq->begin();
Andy Hungf2285312017-02-14 18:31:59 -08004638 coldIdle = state->mCommand == FastMixerState::COLD_IDLE;
Eric Laurent81784c32012-11-19 14:55:58 -08004639 }
4640
Andy Hung69aed5f2014-02-25 17:24:40 -08004641 mMixerBufferValid = false; // mMixerBuffer has no valid data until appropriate tracks found.
Andy Hung98ef9782014-03-04 14:46:50 -08004642 mEffectBufferValid = false; // mEffectBuffer has no valid data until tracks found.
Andy Hung69aed5f2014-02-25 17:24:40 -08004643
Andy Hungbd3b2b02018-05-21 10:53:11 -07004644 // DeferredOperations handles statistics after setting mixerStatus.
4645 class DeferredOperations {
4646 public:
4647 DeferredOperations(mixer_state *mixerStatus)
4648 : mMixerStatus(mixerStatus) { }
4649
4650 // when leaving scope, tally frames properly.
4651 ~DeferredOperations() {
4652 // Tally underrun frames only if we are actually mixing (MIXER_TRACKS_READY)
4653 // because that is when the underrun occurs.
4654 // We do not distinguish between FastTracks and NormalTracks here.
4655 if (*mMixerStatus == MIXER_TRACKS_READY) {
4656 for (const auto &underrun : mUnderrunFrames) {
4657 underrun.first->mAudioTrackServerProxy->tallyUnderrunFrames(
4658 underrun.second);
4659 }
4660 }
4661 }
4662
4663 // tallyUnderrunFrames() is called to update the track counters
4664 // with the number of underrun frames for a particular mixer period.
4665 // We defer tallying until we know the final mixer status.
4666 void tallyUnderrunFrames(sp<Track> track, size_t underrunFrames) {
4667 mUnderrunFrames.emplace_back(track, underrunFrames);
4668 }
4669
4670 private:
4671 const mixer_state * const mMixerStatus;
4672 std::vector<std::pair<sp<Track>, size_t>> mUnderrunFrames;
4673 } deferredOperations(&mixerStatus); // implicit nested scope for variable capture
4674
jiabin245cdd92018-12-07 17:55:15 -08004675 bool noFastHapticTrack = true;
Eric Laurent81784c32012-11-19 14:55:58 -08004676 for (size_t i=0 ; i<count ; i++) {
Andy Hungdae27702016-10-31 14:01:16 -07004677 const sp<Track> t = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08004678
4679 // this const just means the local variable doesn't change
4680 Track* const track = t.get();
4681
4682 // process fast tracks
4683 if (track->isFastTrack()) {
Andy Hungae22b482019-05-09 15:38:55 -07004684 LOG_ALWAYS_FATAL_IF(mFastMixer.get() == nullptr,
4685 "%s(%d): FastTrack(%d) present without FastMixer",
4686 __func__, id(), track->id());
4687
jiabin245cdd92018-12-07 17:55:15 -08004688 if (track->getHapticPlaybackEnabled()) {
4689 noFastHapticTrack = false;
4690 }
Eric Laurent81784c32012-11-19 14:55:58 -08004691
4692 // It's theoretically possible (though unlikely) for a fast track to be created
4693 // and then removed within the same normal mix cycle. This is not a problem, as
4694 // the track never becomes active so it's fast mixer slot is never touched.
4695 // The converse, of removing an (active) track and then creating a new track
4696 // at the identical fast mixer slot within the same normal mix cycle,
4697 // is impossible because the slot isn't marked available until the end of each cycle.
4698 int j = track->mFastIndex;
Glenn Kastendc2c50b2016-04-21 08:13:14 -07004699 ALOG_ASSERT(0 < j && j < (int)FastMixerState::sMaxFastTracks);
Eric Laurent81784c32012-11-19 14:55:58 -08004700 ALOG_ASSERT(!(mFastTrackAvailMask & (1 << j)));
4701 FastTrack *fastTrack = &state->mFastTracks[j];
4702
4703 // Determine whether the track is currently in underrun condition,
4704 // and whether it had a recent underrun.
4705 FastTrackDump *ftDump = &mFastMixerDumpState.mTracks[j];
4706 FastTrackUnderruns underruns = ftDump->mUnderruns;
4707 uint32_t recentFull = (underruns.mBitFields.mFull -
4708 track->mObservedUnderruns.mBitFields.mFull) & UNDERRUN_MASK;
4709 uint32_t recentPartial = (underruns.mBitFields.mPartial -
4710 track->mObservedUnderruns.mBitFields.mPartial) & UNDERRUN_MASK;
4711 uint32_t recentEmpty = (underruns.mBitFields.mEmpty -
4712 track->mObservedUnderruns.mBitFields.mEmpty) & UNDERRUN_MASK;
4713 uint32_t recentUnderruns = recentPartial + recentEmpty;
4714 track->mObservedUnderruns = underruns;
4715 // don't count underruns that occur while stopping or pausing
4716 // or stopped which can occur when flush() is called while active
Andy Hungbd3b2b02018-05-21 10:53:11 -07004717 size_t underrunFrames = 0;
Glenn Kasten82aaf942013-07-17 16:05:07 -07004718 if (!(track->isStopping() || track->isPausing() || track->isStopped()) &&
4719 recentUnderruns > 0) {
4720 // FIXME fast mixer will pull & mix partial buffers, but we count as a full underrun
Andy Hungbd3b2b02018-05-21 10:53:11 -07004721 underrunFrames = recentUnderruns * mFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08004722 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07004723 // Immediately account for FastTrack underruns.
4724 track->mAudioTrackServerProxy->tallyUnderrunFrames(underrunFrames);
Eric Laurent81784c32012-11-19 14:55:58 -08004725
4726 // This is similar to the state machine for normal tracks,
4727 // with a few modifications for fast tracks.
4728 bool isActive = true;
4729 switch (track->mState) {
4730 case TrackBase::STOPPING_1:
4731 // track stays active in STOPPING_1 state until first underrun
Eric Laurentbfb1b832013-01-07 09:53:42 -08004732 if (recentUnderruns > 0 || track->isTerminated()) {
Eric Laurent81784c32012-11-19 14:55:58 -08004733 track->mState = TrackBase::STOPPING_2;
4734 }
4735 break;
4736 case TrackBase::PAUSING:
4737 // ramp down is not yet implemented
4738 track->setPaused();
4739 break;
4740 case TrackBase::RESUMING:
4741 // ramp up is not yet implemented
4742 track->mState = TrackBase::ACTIVE;
4743 break;
4744 case TrackBase::ACTIVE:
4745 if (recentFull > 0 || recentPartial > 0) {
4746 // track has provided at least some frames recently: reset retry count
4747 track->mRetryCount = kMaxTrackRetries;
4748 }
4749 if (recentUnderruns == 0) {
4750 // no recent underruns: stay active
4751 break;
4752 }
4753 // there has recently been an underrun of some kind
4754 if (track->sharedBuffer() == 0) {
4755 // were any of the recent underruns "empty" (no frames available)?
4756 if (recentEmpty == 0) {
4757 // no, then ignore the partial underruns as they are allowed indefinitely
4758 break;
4759 }
4760 // there has recently been an "empty" underrun: decrement the retry counter
4761 if (--(track->mRetryCount) > 0) {
4762 break;
4763 }
4764 // indicate to client process that the track was disabled because of underrun;
4765 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08004766 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08004767 // remove from active list, but state remains ACTIVE [confusing but true]
4768 isActive = false;
4769 break;
4770 }
Chih-Hung Hsieh2b487032018-09-13 14:16:02 -07004771 FALLTHROUGH_INTENDED;
Eric Laurent81784c32012-11-19 14:55:58 -08004772 case TrackBase::STOPPING_2:
4773 case TrackBase::PAUSED:
Eric Laurent81784c32012-11-19 14:55:58 -08004774 case TrackBase::STOPPED:
4775 case TrackBase::FLUSHED: // flush() while active
4776 // Check for presentation complete if track is inactive
4777 // We have consumed all the buffers of this track.
4778 // This would be incomplete if we auto-paused on underrun
4779 {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07004780 uint32_t latency = 0;
4781 status_t result = mOutput->stream->getLatency(&latency);
4782 ALOGE_IF(result != OK,
4783 "Error when retrieving output stream latency: %d", result);
4784 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08004785 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08004786 if (!(mStandby || track->presentationComplete(framesWritten, audioHALFrames))) {
4787 // track stays in active list until presentation is complete
4788 break;
4789 }
4790 }
4791 if (track->isStopping_2()) {
4792 track->mState = TrackBase::STOPPED;
4793 }
4794 if (track->isStopped()) {
4795 // Can't reset directly, as fast mixer is still polling this track
4796 // track->reset();
4797 // So instead mark this track as needing to be reset after push with ack
4798 resetMask |= 1 << i;
4799 }
4800 isActive = false;
4801 break;
4802 case TrackBase::IDLE:
4803 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -08004804 LOG_ALWAYS_FATAL("unexpected track state %d", track->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08004805 }
4806
4807 if (isActive) {
4808 // was it previously inactive?
4809 if (!(state->mTrackMask & (1 << j))) {
4810 ExtendedAudioBufferProvider *eabp = track;
4811 VolumeProvider *vp = track;
4812 fastTrack->mBufferProvider = eabp;
4813 fastTrack->mVolumeProvider = vp;
Eric Laurent81784c32012-11-19 14:55:58 -08004814 fastTrack->mChannelMask = track->mChannelMask;
Andy Hunge8a1ced2014-05-09 15:02:21 -07004815 fastTrack->mFormat = track->mFormat;
jiabin245cdd92018-12-07 17:55:15 -08004816 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
jiabin77270b82018-12-18 15:41:29 -08004817 fastTrack->mHapticIntensity = track->getHapticIntensity();
Eric Laurent81784c32012-11-19 14:55:58 -08004818 fastTrack->mGeneration++;
4819 state->mTrackMask |= 1 << j;
4820 didModify = true;
4821 // no acknowledgement required for newly active tracks
4822 }
Kevin Rocard12381092018-04-11 09:19:59 -07004823 sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
Eric Laurenteab90452019-06-24 15:17:46 -07004824 float volume;
4825 if (track->isPlaybackRestricted() || mStreamTypes[track->streamType()].mute) {
4826 volume = 0.f;
4827 } else {
4828 volume = masterVolume * mStreamTypes[track->streamType()].volume;
4829 }
4830
4831 handleVoipVolume_l(&volume);
4832
Eric Laurent81784c32012-11-19 14:55:58 -08004833 // cache the combined master volume and stream type volume for fast mixer; this
4834 // lacks any synchronization or barrier so VolumeProvider may read a stale value
Andy Hung9fc8b5c2017-01-24 13:36:48 -08004835 const float vh = track->getVolumeHandler()->getVolume(
Eric Laurenteab90452019-06-24 15:17:46 -07004836 proxy->framesReleased()).first;
4837 volume *= vh;
Kevin Rocardb0eeaf122018-04-11 08:30:16 -07004838 track->mCachedVolume = volume;
Kevin Rocard12381092018-04-11 09:19:59 -07004839 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
4840 float vlf = volume * float_from_gain(gain_minifloat_unpack_left(vlr));
4841 float vrf = volume * float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurenteab90452019-06-24 15:17:46 -07004842
Kevin Rocard12381092018-04-11 09:19:59 -07004843 track->setFinalVolume((vlf + vrf) / 2.f);
Eric Laurent81784c32012-11-19 14:55:58 -08004844 ++fastTracks;
4845 } else {
4846 // was it previously active?
4847 if (state->mTrackMask & (1 << j)) {
4848 fastTrack->mBufferProvider = NULL;
4849 fastTrack->mGeneration++;
4850 state->mTrackMask &= ~(1 << j);
4851 didModify = true;
4852 // If any fast tracks were removed, we must wait for acknowledgement
4853 // because we're about to decrement the last sp<> on those tracks.
4854 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
4855 } else {
Glenn Kastenbf848af2017-12-22 11:55:01 -08004856 // ALOGW rather than LOG_ALWAYS_FATAL because it seems there are cases where an
4857 // AudioTrack may start (which may not be with a start() but with a write()
4858 // after underrun) and immediately paused or released. In that case the
4859 // FastTrack state hasn't had time to update.
4860 // TODO Remove the ALOGW when this theory is confirmed.
4861 ALOGW("fast track %d should have been active; "
Glenn Kastenf7d65ee2015-12-02 13:45:01 -08004862 "mState=%d, mTrackMask=%#x, recentUnderruns=%u, isShared=%d",
4863 j, track->mState, state->mTrackMask, recentUnderruns,
4864 track->sharedBuffer() != 0);
Glenn Kastenbf848af2017-12-22 11:55:01 -08004865 // Since the FastMixer state already has the track inactive, do nothing here.
Eric Laurent81784c32012-11-19 14:55:58 -08004866 }
4867 tracksToRemove->add(track);
4868 // Avoids a misleading display in dumpsys
4869 track->mObservedUnderruns.mBitFields.mMostRecent = UNDERRUN_FULL;
4870 }
jiabin245cdd92018-12-07 17:55:15 -08004871 if (fastTrack->mHapticPlaybackEnabled != track->getHapticPlaybackEnabled()) {
4872 fastTrack->mHapticPlaybackEnabled = track->getHapticPlaybackEnabled();
4873 didModify = true;
4874 }
Eric Laurent81784c32012-11-19 14:55:58 -08004875 continue;
4876 }
4877
4878 { // local variable scope to avoid goto warning
4879
4880 audio_track_cblk_t* cblk = track->cblk();
4881
4882 // The first time a track is added we wait
4883 // for all its buffers to be filled before processing it
Andy Hungc0691382018-09-12 18:01:57 -07004884 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08004885
4886 // if an active track doesn't exist in the AudioMixer, create it.
Andy Hungc0691382018-09-12 18:01:57 -07004887 // use the trackId as the AudioMixer name.
4888 if (!mAudioMixer->exists(trackId)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08004889 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07004890 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08004891 track->mChannelMask,
4892 track->mFormat,
4893 track->mSessionId);
4894 if (status != OK) {
Andy Hungc0691382018-09-12 18:01:57 -07004895 ALOGW("%s(): AudioMixer cannot create track(%d)"
4896 " mask %#x, format %#x, sessionId %d",
4897 __func__, trackId,
4898 track->mChannelMask, track->mFormat, track->mSessionId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004899 tracksToRemove->add(track);
4900 track->invalidate(); // consider it dead.
4901 continue;
4902 }
4903 }
4904
Eric Laurent81784c32012-11-19 14:55:58 -08004905 // make sure that we have enough frames to mix one full buffer.
4906 // enforce this condition only once to enable draining the buffer in case the client
4907 // app does not call stop() and relies on underrun to stop:
4908 // hence the test on (mMixerStatus == MIXER_TRACKS_READY) meaning the track was mixed
4909 // during last round
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004910 size_t desiredFrames;
Andy Hung8edb8dc2015-03-26 19:13:55 -07004911 const uint32_t sampleRate = track->mAudioTrackServerProxy->getSampleRate();
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004912 AudioPlaybackRate playbackRate = track->mAudioTrackServerProxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07004913
4914 desiredFrames = sourceFramesNeededWithTimestretch(
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07004915 sampleRate, mNormalFrameCount, mSampleRate, playbackRate.mSpeed);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004916 // TODO: ONLY USED FOR LEGACY RESAMPLERS, remove when they are removed.
4917 // add frames already consumed but not yet released by the resampler
4918 // because mAudioTrackServerProxy->framesReady() will include these frames
Andy Hungc0691382018-09-12 18:01:57 -07004919 desiredFrames += mAudioMixer->getUnreleasedFrames(trackId);
Andy Hung8edb8dc2015-03-26 19:13:55 -07004920
Eric Laurent81784c32012-11-19 14:55:58 -08004921 uint32_t minFrames = 1;
4922 if ((track->sharedBuffer() == 0) && !track->isStopped() && !track->isPausing() &&
4923 (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004924 minFrames = desiredFrames;
Eric Laurent81784c32012-11-19 14:55:58 -08004925 }
Eric Laurent13e4c962013-12-20 17:36:01 -08004926
4927 size_t framesReady = track->framesReady();
Glenn Kastene7754022014-10-31 12:11:26 -07004928 if (ATRACE_ENABLED()) {
4929 // I wish we had formatted trace names
Andy Hung1bc088a2018-02-09 15:57:31 -08004930 std::string traceName("nRdy");
Andy Hungc0691382018-09-12 18:01:57 -07004931 traceName += std::to_string(trackId);
Andy Hung1bc088a2018-02-09 15:57:31 -08004932 ATRACE_INT(traceName.c_str(), framesReady);
Glenn Kastene7754022014-10-31 12:11:26 -07004933 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08004934 if ((framesReady >= minFrames) && track->isReady() &&
Eric Laurent81784c32012-11-19 14:55:58 -08004935 !track->isPaused() && !track->isTerminated())
4936 {
Andy Hungc0691382018-09-12 18:01:57 -07004937 ALOGVV("track(%d) s=%08x [OK] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08004938
4939 mixedTracks++;
4940
Andy Hung69aed5f2014-02-25 17:24:40 -08004941 // track->mainBuffer() != mSinkBuffer or mMixerBuffer means
4942 // there is an effect chain connected to the track
Eric Laurent81784c32012-11-19 14:55:58 -08004943 chain.clear();
Andy Hung69aed5f2014-02-25 17:24:40 -08004944 if (track->mainBuffer() != mSinkBuffer &&
4945 track->mainBuffer() != mMixerBuffer) {
Andy Hung98ef9782014-03-04 14:46:50 -08004946 if (mEffectBufferEnabled) {
4947 mEffectBufferValid = true; // Later can set directly.
4948 }
Eric Laurent81784c32012-11-19 14:55:58 -08004949 chain = getEffectChain_l(track->sessionId());
4950 // Delegate volume control to effect in track effect chain if needed
4951 if (chain != 0) {
4952 tracksWithEffect++;
4953 } else {
Andy Hungc0691382018-09-12 18:01:57 -07004954 ALOGW("prepareTracks_l(): track(%d) attached to effect but no chain found on "
Eric Laurent81784c32012-11-19 14:55:58 -08004955 "session %d",
Andy Hungc0691382018-09-12 18:01:57 -07004956 trackId, track->sessionId());
Eric Laurent81784c32012-11-19 14:55:58 -08004957 }
4958 }
4959
4960
4961 int param = AudioMixer::VOLUME;
4962 if (track->mFillingUpStatus == Track::FS_FILLED) {
4963 // no ramp for the first volume setting
4964 track->mFillingUpStatus = Track::FS_ACTIVE;
4965 if (track->mState == TrackBase::RESUMING) {
4966 track->mState = TrackBase::ACTIVE;
Revathi Uddaraju453bcb52017-08-14 14:19:40 +08004967 // If a new track is paused immediately after start, do not ramp on resume.
4968 if (cblk->mServer != 0) {
4969 param = AudioMixer::RAMP_VOLUME;
4970 }
Eric Laurent81784c32012-11-19 14:55:58 -08004971 }
Andy Hungc0691382018-09-12 18:01:57 -07004972 mAudioMixer->setParameter(trackId, AudioMixer::RESAMPLE, AudioMixer::RESET, NULL);
Eric Laurent7c29ec92017-09-20 17:54:22 -07004973 mLeftVolFloat = -1.0;
Glenn Kastenf20e1d82013-07-12 09:45:18 -07004974 // FIXME should not make a decision based on mServer
4975 } else if (cblk->mServer != 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08004976 // If the track is stopped before the first frame was mixed,
4977 // do not apply ramp
4978 param = AudioMixer::RAMP_VOLUME;
4979 }
4980
4981 // compute volume for this track
Andy Hung6be49402014-05-30 10:42:03 -07004982 uint32_t vl, vr; // in U8.24 integer format
4983 float vlf, vrf, vaf; // in [0.0, 1.0] float format
Eric Laurent7c29ec92017-09-20 17:54:22 -07004984 // read original volumes with volume control
Eric Laurenteab90452019-06-24 15:17:46 -07004985 float v = masterVolume * mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07004986 // Always fetch volumeshaper volume to ensure state is updated.
4987 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
4988 const float vh = track->getVolumeHandler()->getVolume(
4989 track->mAudioTrackServerProxy->framesReleased()).first;
Eric Laurent7c29ec92017-09-20 17:54:22 -07004990
Eric Laurenteab90452019-06-24 15:17:46 -07004991 if (mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
4992 v = 0;
4993 }
4994
4995 handleVoipVolume_l(&v);
4996
4997 if (track->isPausing()) {
Andy Hung6be49402014-05-30 10:42:03 -07004998 vl = vr = 0;
4999 vlf = vrf = vaf = 0.;
Eric Laurenteab90452019-06-24 15:17:46 -07005000 track->setPaused();
Eric Laurent81784c32012-11-19 14:55:58 -08005001 } else {
Glenn Kastenc56f3422014-03-21 17:53:17 -07005002 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -07005003 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
5004 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
Eric Laurent81784c32012-11-19 14:55:58 -08005005 // track volumes come from shared memory, so can't be trusted and must be clamped
Glenn Kastenc56f3422014-03-21 17:53:17 -07005006 if (vlf > GAIN_FLOAT_UNITY) {
5007 ALOGV("Track left volume out of range: %.3g", vlf);
5008 vlf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005009 }
Glenn Kastenc56f3422014-03-21 17:53:17 -07005010 if (vrf > GAIN_FLOAT_UNITY) {
5011 ALOGV("Track right volume out of range: %.3g", vrf);
5012 vrf = GAIN_FLOAT_UNITY;
Eric Laurent81784c32012-11-19 14:55:58 -08005013 }
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005014 // now apply the master volume and stream type volume and shaper volume
5015 vlf *= v * vh;
5016 vrf *= v * vh;
Eric Laurent81784c32012-11-19 14:55:58 -08005017 // assuming master volume and stream type volume each go up to 1.0,
Andy Hung6be49402014-05-30 10:42:03 -07005018 // then derive vl and vr as U8.24 versions for the effect chain
5019 const float scaleto8_24 = MAX_GAIN_INT * MAX_GAIN_INT;
5020 vl = (uint32_t) (scaleto8_24 * vlf);
5021 vr = (uint32_t) (scaleto8_24 * vrf);
5022 // vl and vr are now in U8.24 format
Glenn Kastene3aa6592012-12-04 12:22:46 -08005023 uint16_t sendLevel = proxy->getSendLevel_U4_12();
Eric Laurent81784c32012-11-19 14:55:58 -08005024 // send level comes from shared memory and so may be corrupt
5025 if (sendLevel > MAX_GAIN_INT) {
5026 ALOGV("Track send level out of range: %04X", sendLevel);
5027 sendLevel = MAX_GAIN_INT;
5028 }
Andy Hung6be49402014-05-30 10:42:03 -07005029 // vaf is represented as [0.0, 1.0] float by rescaling sendLevel
5030 vaf = v * sendLevel * (1. / MAX_GAIN_INT);
Eric Laurent81784c32012-11-19 14:55:58 -08005031 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005032
Kevin Rocard12381092018-04-11 09:19:59 -07005033 track->setFinalVolume((vrf + vlf) / 2.f);
5034
Eric Laurent81784c32012-11-19 14:55:58 -08005035 // Delegate volume control to effect in track effect chain if needed
5036 if (chain != 0 && chain->setVolume_l(&vl, &vr)) {
5037 // Do not ramp volume if volume is controlled by effect
5038 param = AudioMixer::VOLUME;
Bryant Liub6be7f22014-06-12 22:02:41 +08005039 // Update remaining floating point volume levels
5040 vlf = (float)vl / (1 << 24);
5041 vrf = (float)vr / (1 << 24);
Eric Laurent81784c32012-11-19 14:55:58 -08005042 track->mHasVolumeController = true;
5043 } else {
5044 // force no volume ramp when volume controller was just disabled or removed
5045 // from effect chain to avoid volume spike
5046 if (track->mHasVolumeController) {
5047 param = AudioMixer::VOLUME;
5048 }
5049 track->mHasVolumeController = false;
5050 }
5051
Eric Laurent81784c32012-11-19 14:55:58 -08005052 // XXX: these things DON'T need to be done each time
Andy Hungc0691382018-09-12 18:01:57 -07005053 mAudioMixer->setBufferProvider(trackId, track);
5054 mAudioMixer->enable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005055
Andy Hungc0691382018-09-12 18:01:57 -07005056 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME0, &vlf);
5057 mAudioMixer->setParameter(trackId, param, AudioMixer::VOLUME1, &vrf);
5058 mAudioMixer->setParameter(trackId, param, AudioMixer::AUXLEVEL, &vaf);
Eric Laurent81784c32012-11-19 14:55:58 -08005059 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005060 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005061 AudioMixer::TRACK,
5062 AudioMixer::FORMAT, (void *)track->format());
5063 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005064 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005065 AudioMixer::TRACK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005066 AudioMixer::CHANNEL_MASK, (void *)(uintptr_t)track->channelMask());
Andy Hung9a592762014-07-21 21:56:01 -07005067 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005068 trackId,
Andy Hung9a592762014-07-21 21:56:01 -07005069 AudioMixer::TRACK,
jiabin245cdd92018-12-07 17:55:15 -08005070 AudioMixer::MIXER_CHANNEL_MASK,
5071 (void *)(uintptr_t)(mChannelMask | mHapticChannelMask));
Glenn Kastene3aa6592012-12-04 12:22:46 -08005072 // limit track sample rate to 2 x output sample rate, which changes at re-configuration
Andy Hungcd044842014-08-07 11:04:34 -07005073 uint32_t maxSampleRate = mSampleRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX;
Andy Hung333ab962019-05-28 20:23:35 -07005074 uint32_t reqSampleRate = proxy->getSampleRate();
Glenn Kastene3aa6592012-12-04 12:22:46 -08005075 if (reqSampleRate == 0) {
5076 reqSampleRate = mSampleRate;
5077 } else if (reqSampleRate > maxSampleRate) {
5078 reqSampleRate = maxSampleRate;
5079 }
Eric Laurent81784c32012-11-19 14:55:58 -08005080 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005081 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005082 AudioMixer::RESAMPLE,
5083 AudioMixer::SAMPLE_RATE,
Kévin PETIT377b2ec2014-02-03 12:35:36 +00005084 (void *)(uintptr_t)reqSampleRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005085
Andy Hung333ab962019-05-28 20:23:35 -07005086 AudioPlaybackRate playbackRate = proxy->getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -07005087 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005088 trackId,
Andy Hung8edb8dc2015-03-26 19:13:55 -07005089 AudioMixer::TIMESTRETCH,
5090 AudioMixer::PLAYBACK_RATE,
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07005091 &playbackRate);
Andy Hung8edb8dc2015-03-26 19:13:55 -07005092
Andy Hung69aed5f2014-02-25 17:24:40 -08005093 /*
5094 * Select the appropriate output buffer for the track.
5095 *
Andy Hung98ef9782014-03-04 14:46:50 -08005096 * Tracks with effects go into their own effects chain buffer
5097 * and from there into either mEffectBuffer or mSinkBuffer.
Andy Hung69aed5f2014-02-25 17:24:40 -08005098 *
5099 * Other tracks can use mMixerBuffer for higher precision
5100 * channel accumulation. If this buffer is enabled
5101 * (mMixerBufferEnabled true), then selected tracks will accumulate
5102 * into it.
5103 *
5104 */
5105 if (mMixerBufferEnabled
5106 && (track->mainBuffer() == mSinkBuffer
5107 || track->mainBuffer() == mMixerBuffer)) {
5108 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005109 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005110 AudioMixer::TRACK,
Andy Hung78820702014-02-28 16:23:02 -08005111 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hung69aed5f2014-02-25 17:24:40 -08005112 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005113 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005114 AudioMixer::TRACK,
5115 AudioMixer::MAIN_BUFFER, (void *)mMixerBuffer);
5116 // TODO: override track->mainBuffer()?
5117 mMixerBufferValid = true;
5118 } else {
5119 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005120 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005121 AudioMixer::TRACK,
rago94a1ee82017-07-21 15:11:02 -07005122 AudioMixer::MIXER_FORMAT, (void *)EFFECT_BUFFER_FORMAT);
Andy Hung69aed5f2014-02-25 17:24:40 -08005123 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005124 trackId,
Andy Hung69aed5f2014-02-25 17:24:40 -08005125 AudioMixer::TRACK,
5126 AudioMixer::MAIN_BUFFER, (void *)track->mainBuffer());
5127 }
Eric Laurent81784c32012-11-19 14:55:58 -08005128 mAudioMixer->setParameter(
Andy Hungc0691382018-09-12 18:01:57 -07005129 trackId,
Eric Laurent81784c32012-11-19 14:55:58 -08005130 AudioMixer::TRACK,
5131 AudioMixer::AUX_BUFFER, (void *)track->auxBuffer());
jiabin245cdd92018-12-07 17:55:15 -08005132 mAudioMixer->setParameter(
5133 trackId,
5134 AudioMixer::TRACK,
5135 AudioMixer::HAPTIC_ENABLED, (void *)(uintptr_t)track->getHapticPlaybackEnabled());
jiabin77270b82018-12-18 15:41:29 -08005136 mAudioMixer->setParameter(
5137 trackId,
5138 AudioMixer::TRACK,
5139 AudioMixer::HAPTIC_INTENSITY, (void *)(uintptr_t)track->getHapticIntensity());
Eric Laurent81784c32012-11-19 14:55:58 -08005140
5141 // reset retry count
5142 track->mRetryCount = kMaxTrackRetries;
5143
5144 // If one track is ready, set the mixer ready if:
5145 // - the mixer was not ready during previous round OR
5146 // - no other track is not ready
5147 if (mMixerStatusIgnoringFastTracks != MIXER_TRACKS_READY ||
5148 mixerStatus != MIXER_TRACKS_ENABLED) {
5149 mixerStatus = MIXER_TRACKS_READY;
5150 }
5151 } else {
Andy Hungbd3b2b02018-05-21 10:53:11 -07005152 size_t underrunFrames = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005153 if (framesReady < desiredFrames && !track->isStopped() && !track->isPaused()) {
Andy Hungc0691382018-09-12 18:01:57 -07005154 ALOGV("track(%d) underrun, framesReady(%zu) < framesDesired(%zd)",
5155 trackId, framesReady, desiredFrames);
Andy Hungbd3b2b02018-05-21 10:53:11 -07005156 underrunFrames = desiredFrames;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08005157 }
Andy Hungbd3b2b02018-05-21 10:53:11 -07005158 deferredOperations.tallyUnderrunFrames(track, underrunFrames);
Phil Burk2812d9e2016-01-04 10:34:30 -08005159
Eric Laurent81784c32012-11-19 14:55:58 -08005160 // clear effect chain input buffer if an active track underruns to avoid sending
5161 // previous audio buffer again to effects
5162 chain = getEffectChain_l(track->sessionId());
5163 if (chain != 0) {
5164 chain->clearInputBuffer();
5165 }
5166
Andy Hungc0691382018-09-12 18:01:57 -07005167 ALOGVV("track(%d) s=%08x [NOT READY] on thread %p", trackId, cblk->mServer, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005168 if ((track->sharedBuffer() != 0) || track->isTerminated() ||
5169 track->isStopped() || track->isPaused()) {
5170 // We have consumed all the buffers of this track.
5171 // Remove it from the list of active tracks.
5172 // TODO: use actual buffer filling status instead of latency when available from
5173 // audio HAL
5174 size_t audioHALFrames = (latency_l() * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08005175 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurent81784c32012-11-19 14:55:58 -08005176 if (mStandby || track->presentationComplete(framesWritten, audioHALFrames)) {
5177 if (track->isStopped()) {
5178 track->reset();
5179 }
5180 tracksToRemove->add(track);
5181 }
5182 } else {
Eric Laurent81784c32012-11-19 14:55:58 -08005183 // No buffers for this track. Give it a few chances to
5184 // fill a buffer, then remove it from active list.
5185 if (--(track->mRetryCount) <= 0) {
Andy Hungc0691382018-09-12 18:01:57 -07005186 ALOGI("BUFFER TIMEOUT: remove(%d) from active list on thread %p",
5187 trackId, this);
Eric Laurent81784c32012-11-19 14:55:58 -08005188 tracksToRemove->add(track);
5189 // indicate to client process that the track was disabled because of underrun;
5190 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005191 track->disable();
Eric Laurent81784c32012-11-19 14:55:58 -08005192 // If one track is not ready, mark the mixer also not ready if:
5193 // - the mixer was ready during previous round OR
5194 // - no other track is ready
5195 } else if (mMixerStatusIgnoringFastTracks == MIXER_TRACKS_READY ||
5196 mixerStatus != MIXER_TRACKS_READY) {
5197 mixerStatus = MIXER_TRACKS_ENABLED;
5198 }
5199 }
Andy Hungc0691382018-09-12 18:01:57 -07005200 mAudioMixer->disable(trackId);
Eric Laurent81784c32012-11-19 14:55:58 -08005201 }
5202
5203 } // local variable scope to avoid goto warning
Eric Laurent81784c32012-11-19 14:55:58 -08005204
5205 }
5206
jiabin245cdd92018-12-07 17:55:15 -08005207 if (mHapticChannelMask != AUDIO_CHANNEL_NONE && sq != NULL) {
5208 // When there is no fast track playing haptic and FastMixer exists,
5209 // enabling the first FastTrack, which provides mixed data from normal
5210 // tracks, to play haptic data.
5211 FastTrack *fastTrack = &state->mFastTracks[0];
5212 if (fastTrack->mHapticPlaybackEnabled != noFastHapticTrack) {
5213 fastTrack->mHapticPlaybackEnabled = noFastHapticTrack;
5214 didModify = true;
5215 }
5216 }
5217
Eric Laurent81784c32012-11-19 14:55:58 -08005218 // Push the new FastMixer state if necessary
5219 bool pauseAudioWatchdog = false;
5220 if (didModify) {
5221 state->mFastTracksGen++;
5222 // if the fast mixer was active, but now there are no fast tracks, then put it in cold idle
5223 if (kUseFastMixer == FastMixer_Dynamic &&
5224 state->mCommand == FastMixerState::MIX_WRITE && state->mTrackMask <= 1) {
5225 state->mCommand = FastMixerState::COLD_IDLE;
5226 state->mColdFutexAddr = &mFastMixerFutex;
5227 state->mColdGen++;
5228 mFastMixerFutex = 0;
5229 if (kUseFastMixer == FastMixer_Dynamic) {
5230 mNormalSink = mOutputSink;
5231 }
5232 // If we go into cold idle, need to wait for acknowledgement
5233 // so that fast mixer stops doing I/O.
5234 block = FastMixerStateQueue::BLOCK_UNTIL_ACKED;
5235 pauseAudioWatchdog = true;
5236 }
Eric Laurent81784c32012-11-19 14:55:58 -08005237 }
5238 if (sq != NULL) {
5239 sq->end(didModify);
Andy Hungf2285312017-02-14 18:31:59 -08005240 // No need to block if the FastMixer is in COLD_IDLE as the FastThread
5241 // is not active. (We BLOCK_UNTIL_ACKED when entering COLD_IDLE
5242 // when bringing the output sink into standby.)
5243 //
5244 // We will get the latest FastMixer state when we come out of COLD_IDLE.
5245 //
5246 // This occurs with BT suspend when we idle the FastMixer with
5247 // active tracks, which may be added or removed.
5248 sq->push(coldIdle ? FastMixerStateQueue::BLOCK_NEVER : block);
Eric Laurent81784c32012-11-19 14:55:58 -08005249 }
5250#ifdef AUDIO_WATCHDOG
5251 if (pauseAudioWatchdog && mAudioWatchdog != 0) {
5252 mAudioWatchdog->pause();
5253 }
5254#endif
5255
5256 // Now perform the deferred reset on fast tracks that have stopped
5257 while (resetMask != 0) {
5258 size_t i = __builtin_ctz(resetMask);
5259 ALOG_ASSERT(i < count);
5260 resetMask &= ~(1 << i);
Andy Hungdae27702016-10-31 14:01:16 -07005261 sp<Track> track = mActiveTracks[i];
Eric Laurent81784c32012-11-19 14:55:58 -08005262 ALOG_ASSERT(track->isFastTrack() && track->isStopped());
5263 track->reset();
5264 }
5265
Andy Hung80d03d22018-04-10 10:32:11 -07005266 // Track destruction may occur outside of threadLoop once it is removed from active tracks.
5267 // Ensure the AudioMixer doesn't have a raw "buffer provider" pointer to the track if
5268 // it ceases to be active, to allow safe removal from the AudioMixer at the start
5269 // of prepareTracks_l(); this releases any outstanding buffer back to the track.
5270 // See also the implementation of destroyTrack_l().
5271 for (const auto &track : *tracksToRemove) {
Andy Hungc0691382018-09-12 18:01:57 -07005272 const int trackId = track->id();
5273 if (mAudioMixer->exists(trackId)) { // Normal tracks here, fast tracks in FastMixer.
5274 mAudioMixer->setBufferProvider(trackId, nullptr /* bufferProvider */);
Andy Hung80d03d22018-04-10 10:32:11 -07005275 }
5276 }
5277
Eric Laurent81784c32012-11-19 14:55:58 -08005278 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005279 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005280
Eric Laurent97d547d2014-09-02 14:45:53 -07005281 if (getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX) != 0) {
5282 mEffectBufferValid = true;
Marco Nelissenac302142014-10-20 13:15:38 -07005283 }
5284
5285 if (mEffectBufferValid) {
Marco Nelissen57088b52014-10-17 16:39:39 -07005286 // as long as there are effects we should clear the effects buffer, to avoid
5287 // passing a non-clean buffer to the effect chain
5288 memset(mEffectBuffer, 0, mEffectBufferSize);
Eric Laurent97d547d2014-09-02 14:45:53 -07005289 }
Andy Hung69aed5f2014-02-25 17:24:40 -08005290 // sink or mix buffer must be cleared if all tracks are connected to an
5291 // effect chain as in this case the mixer will not write to the sink or mix buffer
5292 // and track effects will accumulate into it
Eric Laurentbfb1b832013-01-07 09:53:42 -08005293 if ((mBytesRemaining == 0) && ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5294 (mixedTracks == 0 && fastTracks > 0))) {
Eric Laurent81784c32012-11-19 14:55:58 -08005295 // FIXME as a performance optimization, should remember previous zero status
Andy Hung69aed5f2014-02-25 17:24:40 -08005296 if (mMixerBufferValid) {
5297 memset(mMixerBuffer, 0, mMixerBufferSize);
5298 // TODO: In testing, mSinkBuffer below need not be cleared because
5299 // the PlaybackThread::threadLoop() copies mMixerBuffer into mSinkBuffer
5300 // after mixing.
5301 //
5302 // To enforce this guarantee:
5303 // ((mixedTracks != 0 && mixedTracks == tracksWithEffect) ||
5304 // (mixedTracks == 0 && fastTracks > 0))
5305 // must imply MIXER_TRACKS_READY.
5306 // Later, we may clear buffers regardless, and skip much of this logic.
5307 }
Andy Hung98ef9782014-03-04 14:46:50 -08005308 // FIXME as a performance optimization, should remember previous zero status
Andy Hung5567aaf2014-07-17 14:00:07 -07005309 memset(mSinkBuffer, 0, mNormalFrameCount * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08005310 }
5311
5312 // if any fast tracks, then status is ready
5313 mMixerStatusIgnoringFastTracks = mixerStatus;
5314 if (fastTracks > 0) {
5315 mixerStatus = MIXER_TRACKS_READY;
5316 }
5317 return mixerStatus;
5318}
5319
Eric Laurentad7dd962016-09-22 12:38:37 -07005320// trackCountForUid_l() must be called with ThreadBase::mLock held
Andy Hung1bc088a2018-02-09 15:57:31 -08005321uint32_t AudioFlinger::PlaybackThread::trackCountForUid_l(uid_t uid) const
Eric Laurentad7dd962016-09-22 12:38:37 -07005322{
5323 uint32_t trackCount = 0;
5324 for (size_t i = 0; i < mTracks.size() ; i++) {
Andy Hung1f12a8a2016-11-07 16:10:30 -08005325 if (mTracks[i]->uid() == uid) {
Eric Laurentad7dd962016-09-22 12:38:37 -07005326 trackCount++;
5327 }
5328 }
5329 return trackCount;
5330}
5331
Andy Hung1bc088a2018-02-09 15:57:31 -08005332// isTrackAllowed_l() must be called with ThreadBase::mLock held
5333bool AudioFlinger::MixerThread::isTrackAllowed_l(
5334 audio_channel_mask_t channelMask, audio_format_t format,
5335 audio_session_t sessionId, uid_t uid) const
Eric Laurent81784c32012-11-19 14:55:58 -08005336{
Andy Hung1bc088a2018-02-09 15:57:31 -08005337 if (!PlaybackThread::isTrackAllowed_l(channelMask, format, sessionId, uid)) {
5338 return false;
Eric Laurentad7dd962016-09-22 12:38:37 -07005339 }
Andy Hung1bc088a2018-02-09 15:57:31 -08005340 // Check validity as we don't call AudioMixer::create() here.
Mikhail Naganov32f0d162019-07-30 14:42:32 -07005341 if (!mAudioMixer->isValidFormat(format)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005342 ALOGW("%s: invalid format: %#x", __func__, format);
5343 return false;
5344 }
Mikhail Naganov32f0d162019-07-30 14:42:32 -07005345 if (!mAudioMixer->isValidChannelMask(channelMask)) {
Andy Hung1bc088a2018-02-09 15:57:31 -08005346 ALOGW("%s: invalid channelMask: %#x", __func__, channelMask);
5347 return false;
5348 }
5349 return true;
Eric Laurent81784c32012-11-19 14:55:58 -08005350}
5351
Eric Laurent10351942014-05-08 18:49:52 -07005352// checkForNewParameter_l() must be called with ThreadBase::mLock held
5353bool AudioFlinger::MixerThread::checkForNewParameter_l(const String8& keyValuePair,
5354 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005355{
Eric Laurent81784c32012-11-19 14:55:58 -08005356 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005357 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005358
Eric Laurent10351942014-05-08 18:49:52 -07005359 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005360
Glenn Kastenc05b8d72016-03-24 09:48:17 -07005361 AutoPark<FastMixer> park(mFastMixer);
Eric Laurent81784c32012-11-19 14:55:58 -08005362
Eric Laurent10351942014-05-08 18:49:52 -07005363 AudioParameter param = AudioParameter(keyValuePair);
5364 int value;
5365 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
5366 reconfig = true;
5367 }
5368 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005369 if (!isValidPcmSinkFormat((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005370 status = BAD_VALUE;
5371 } else {
5372 // no need to save value, since it's constant
Eric Laurent81784c32012-11-19 14:55:58 -08005373 reconfig = true;
5374 }
Eric Laurent10351942014-05-08 18:49:52 -07005375 }
5376 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
Andy Hung9a592762014-07-21 21:56:01 -07005377 if (!isValidPcmSinkChannelMask((audio_channel_mask_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07005378 status = BAD_VALUE;
5379 } else {
5380 // no need to save value, since it's constant
5381 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005382 }
Eric Laurent10351942014-05-08 18:49:52 -07005383 }
5384 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5385 // do not accept frame count changes if tracks are open as the track buffer
5386 // size depends on frame count and correct behavior would not be guaranteed
5387 // if frame count is changed after track creation
5388 if (!mTracks.isEmpty()) {
5389 status = INVALID_OPERATION;
5390 } else {
5391 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08005392 }
Eric Laurent10351942014-05-08 18:49:52 -07005393 }
5394 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabin10d86fd2019-10-31 17:20:42 -07005395 LOG_FATAL("Should not set routing device in MixerThread");
Eric Laurent10351942014-05-08 18:49:52 -07005396 }
Eric Laurent81784c32012-11-19 14:55:58 -08005397
Eric Laurent10351942014-05-08 18:49:52 -07005398 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005399 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005400 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005401 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005402 mStandby = true;
5403 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005404 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent81784c32012-11-19 14:55:58 -08005405 }
Eric Laurent10351942014-05-08 18:49:52 -07005406 if (status == NO_ERROR && reconfig) {
5407 readOutputParameters_l();
5408 delete mAudioMixer;
5409 mAudioMixer = new AudioMixer(mNormalFrameCount, mSampleRate);
Andy Hung1bc088a2018-02-09 15:57:31 -08005410 for (const auto &track : mTracks) {
Andy Hungc0691382018-09-12 18:01:57 -07005411 const int trackId = track->id();
Andy Hung1bc088a2018-02-09 15:57:31 -08005412 status_t status = mAudioMixer->create(
Andy Hungc0691382018-09-12 18:01:57 -07005413 trackId,
Andy Hung1bc088a2018-02-09 15:57:31 -08005414 track->mChannelMask,
5415 track->mFormat,
5416 track->mSessionId);
5417 ALOGW_IF(status != NO_ERROR,
Andy Hungc0691382018-09-12 18:01:57 -07005418 "%s(): AudioMixer cannot create track(%d)"
5419 " mask %#x, format %#x, sessionId %d",
Andy Hung1bc088a2018-02-09 15:57:31 -08005420 __func__,
Andy Hungc0691382018-09-12 18:01:57 -07005421 trackId, track->mChannelMask, track->mFormat, track->mSessionId);
Eric Laurent10351942014-05-08 18:49:52 -07005422 }
Eric Laurent73e26b62015-04-27 16:55:58 -07005423 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005424 }
Eric Laurent81784c32012-11-19 14:55:58 -08005425 }
5426
Eric Laurent42537be2016-01-08 17:16:42 -08005427 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005428}
5429
5430
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005431void AudioFlinger::MixerThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent81784c32012-11-19 14:55:58 -08005432{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005433 PlaybackThread::dumpInternals_l(fd, args);
Andy Hung40eb1a12015-06-18 13:42:02 -07005434 dprintf(fd, " Thread throttle time (msecs): %u\n", mThreadThrottleTimeMs);
Andy Hung8ed196a2018-01-05 13:21:11 -08005435 dprintf(fd, " AudioMixer tracks: %s\n", mAudioMixer->trackNames().c_str());
Andy Hung2ddee192015-12-18 17:34:44 -08005436 dprintf(fd, " Master mono: %s\n", mMasterMono ? "on" : "off");
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005437 dprintf(fd, " Master balance: %f (%s)\n", mMasterBalance.load(),
5438 (hasFastMixer() ? std::to_string(mFastMixer->getMasterBalance())
5439 : mBalance.toString()).c_str());
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005440 if (hasFastMixer()) {
5441 dprintf(fd, " FastMixer thread %p tid=%d", mFastMixer.get(), mFastMixer->getTid());
5442
5443 // Make a non-atomic copy of fast mixer dump state so it won't change underneath us
5444 // while we are dumping it. It may be inconsistent, but it won't mutate!
5445 // This is a large object so we place it on the heap.
5446 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07005447 const std::unique_ptr<FastMixerDumpState> copy =
5448 std::make_unique<FastMixerDumpState>(mFastMixerDumpState);
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005449 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005450
5451#ifdef STATE_QUEUE_DUMP
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005452 // Similar for state queue
5453 StateQueueObserverDump observerCopy = mStateQueueObserverDump;
5454 observerCopy.dump(fd);
5455 StateQueueMutatorDump mutatorCopy = mStateQueueMutatorDump;
5456 mutatorCopy.dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08005457#endif
5458
Glenn Kasten1bfe09a2017-02-21 13:05:56 -08005459#ifdef AUDIO_WATCHDOG
5460 if (mAudioWatchdog != 0) {
5461 // Make a non-atomic copy of audio watchdog dump so it won't change underneath us
5462 AudioWatchdogDump wdCopy = mAudioWatchdogDump;
5463 wdCopy.dump(fd);
5464 }
5465#endif
5466
5467 } else {
5468 dprintf(fd, " No FastMixer\n");
5469 }
Eric Laurent81784c32012-11-19 14:55:58 -08005470}
5471
5472uint32_t AudioFlinger::MixerThread::idleSleepTimeUs() const
5473{
5474 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000) / 2;
5475}
5476
5477uint32_t AudioFlinger::MixerThread::suspendSleepTimeUs() const
5478{
5479 return (uint32_t)(((mNormalFrameCount * 1000) / mSampleRate) * 1000);
5480}
5481
5482void AudioFlinger::MixerThread::cacheParameters_l()
5483{
5484 PlaybackThread::cacheParameters_l();
5485
5486 // FIXME: Relaxed timing because of a certain device that can't meet latency
5487 // Should be reduced to 2x after the vendor fixes the driver issue
5488 // increase threshold again due to low power audio mode. The way this warning
5489 // threshold is calculated and its usefulness should be reconsidered anyway.
5490 maxPeriod = seconds(mNormalFrameCount) / mSampleRate * 15;
5491}
5492
5493// ----------------------------------------------------------------------------
5494
5495AudioFlinger::DirectOutputThread::DirectOutputThread(const sp<AudioFlinger>& audioFlinger,
jiabin10d86fd2019-10-31 17:20:42 -07005496 AudioStreamOut* output, audio_io_handle_t id, ThreadBase::type_t type, bool systemReady)
5497 : PlaybackThread(audioFlinger, output, id, type, systemReady)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005498{
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005499 setMasterBalance(audioFlinger->getMasterBalance_l());
Eric Laurentbfb1b832013-01-07 09:53:42 -08005500}
5501
Eric Laurent81784c32012-11-19 14:55:58 -08005502AudioFlinger::DirectOutputThread::~DirectOutputThread()
5503{
5504}
5505
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005506void AudioFlinger::DirectOutputThread::dumpInternals_l(int fd, const Vector<String16>& args)
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005507{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07005508 PlaybackThread::dumpInternals_l(fd, args);
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005509 dprintf(fd, " Master balance: %f Left: %f Right: %f\n",
5510 mMasterBalance.load(), mMasterBalanceLeft, mMasterBalanceRight);
5511}
5512
5513void AudioFlinger::DirectOutputThread::setMasterBalance(float balance)
5514{
5515 Mutex::Autolock _l(mLock);
5516 if (mMasterBalance != balance) {
5517 mMasterBalance.store(balance);
5518 mBalance.computeStereoBalance(balance, &mMasterBalanceLeft, &mMasterBalanceRight);
5519 broadcast_l();
5520 }
5521}
5522
Eric Laurent5850c4c2016-11-10 13:04:31 -08005523void AudioFlinger::DirectOutputThread::processVolume_l(Track *track, bool lastTrack)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005524{
Eric Laurentbfb1b832013-01-07 09:53:42 -08005525 float left, right;
5526
Andy Hung333ab962019-05-28 20:23:35 -07005527 // Ensure volumeshaper state always advances even when muted.
5528 const sp<AudioTrackServerProxy> proxy = track->mAudioTrackServerProxy;
5529 const auto [shaperVolume, shaperActive] = track->getVolumeHandler()->getVolume(
5530 proxy->framesReleased());
5531 mVolumeShaperActive = shaperActive;
5532
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08005533 if (mMasterMute || mStreamTypes[track->streamType()].mute || track->isPlaybackRestricted()) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08005534 left = right = 0;
5535 } else {
5536 float typeVolume = mStreamTypes[track->streamType()].volume;
Andy Hung333ab962019-05-28 20:23:35 -07005537 const float v = mMasterVolume * typeVolume * shaperVolume;
Andy Hung9fc8b5c2017-01-24 13:36:48 -08005538
Glenn Kastenc56f3422014-03-21 17:53:17 -07005539 gain_minifloat_packed_t vlr = proxy->getVolumeLR();
5540 left = float_from_gain(gain_minifloat_unpack_left(vlr));
5541 if (left > GAIN_FLOAT_UNITY) {
5542 left = GAIN_FLOAT_UNITY;
5543 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005544 left *= v * mMasterBalanceLeft; // DirectOutputThread balance applied as track volume
Glenn Kastenc56f3422014-03-21 17:53:17 -07005545 right = float_from_gain(gain_minifloat_unpack_right(vlr));
5546 if (right > GAIN_FLOAT_UNITY) {
5547 right = GAIN_FLOAT_UNITY;
5548 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +01005549 right *= v * mMasterBalanceRight;
Eric Laurentbfb1b832013-01-07 09:53:42 -08005550 }
5551
5552 if (lastTrack) {
Kevin Rocard12381092018-04-11 09:19:59 -07005553 track->setFinalVolume((left + right) / 2.f);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005554 if (left != mLeftVolFloat || right != mRightVolFloat) {
5555 mLeftVolFloat = left;
5556 mRightVolFloat = right;
5557
Eric Laurentbfb1b832013-01-07 09:53:42 -08005558 // Delegate volume control to effect in track effect chain if needed
5559 // only one effect chain can be present on DirectOutputThread, so if
5560 // there is one, the track is connected to it
5561 if (!mEffectChains.isEmpty()) {
Tomoharu Kasahara1990bd42014-12-12 14:04:11 +09005562 // if effect chain exists, volume is handled by it.
5563 // Convert volumes from float to 8.24
5564 uint32_t vl = (uint32_t)(left * (1 << 24));
5565 uint32_t vr = (uint32_t)(right * (1 << 24));
5566 // Direct/Offload effect chains set output volume in setVolume_l().
5567 (void)mEffectChains[0]->setVolume_l(&vl, &vr);
5568 } else {
5569 // otherwise we directly set the volume.
5570 setVolumeForOutput_l(left, right);
Eric Laurentbfb1b832013-01-07 09:53:42 -08005571 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005572 }
5573 }
5574}
5575
Phil Burk43b4dcc2015-06-09 16:53:44 -07005576void AudioFlinger::DirectOutputThread::onAddNewTrack_l()
5577{
5578 sp<Track> previousTrack = mPreviousTrack.promote();
Andy Hungdae27702016-10-31 14:01:16 -07005579 sp<Track> latestTrack = mActiveTracks.getLatest();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005580
Eric Laurent0f0631e2015-07-06 18:01:25 -07005581 if (previousTrack != 0 && latestTrack != 0) {
5582 if (mType == DIRECT) {
5583 if (previousTrack.get() != latestTrack.get()) {
5584 mFlushPending = true;
5585 }
5586 } else /* mType == OFFLOAD */ {
5587 if (previousTrack->sessionId() != latestTrack->sessionId()) {
5588 mFlushPending = true;
5589 }
5590 }
Revathi Uddaraju20413a92016-10-13 17:16:14 +08005591 } else if (previousTrack == 0) {
5592 // there could be an old track added back during track transition for direct
5593 // output, so always issues flush to flush data of the previous track if it
5594 // was already destroyed with HAL paused, then flush can resume the playback
5595 mFlushPending = true;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005596 }
5597 PlaybackThread::onAddNewTrack_l();
5598}
Eric Laurentbfb1b832013-01-07 09:53:42 -08005599
Eric Laurent81784c32012-11-19 14:55:58 -08005600AudioFlinger::PlaybackThread::mixer_state AudioFlinger::DirectOutputThread::prepareTracks_l(
5601 Vector< sp<Track> > *tracksToRemove
5602)
5603{
Eric Laurentd595b7c2013-04-03 17:27:56 -07005604 size_t count = mActiveTracks.size();
Eric Laurent81784c32012-11-19 14:55:58 -08005605 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005606 bool doHwPause = false;
5607 bool doHwResume = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005608
5609 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07005610 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08005611 if (t->isInvalid()) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005612 ALOGW("An invalidated track shouldn't be in active list");
Eric Laurent5850c4c2016-11-10 13:04:31 -08005613 tracksToRemove->add(t);
Phil Burk43b4dcc2015-06-09 16:53:44 -07005614 continue;
5615 }
5616
Eric Laurent5850c4c2016-11-10 13:04:31 -08005617 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005618#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurent81784c32012-11-19 14:55:58 -08005619 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07005620#endif
Eric Laurentfd477972013-10-25 18:10:40 -07005621 // Only consider last track started for volume and mixer state control.
5622 // In theory an older track could underrun and restart after the new one starts
5623 // but as we only care about the transition phase between two tracks on a
5624 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07005625 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08005626 bool last = l.get() == track;
Eric Laurent81784c32012-11-19 14:55:58 -08005627
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005628 if (track->isPausing()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005629 track->setPaused();
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005630 if (mHwSupportsPause && last && !mHwPaused) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005631 doHwPause = true;
5632 mHwPaused = true;
5633 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005634 } else if (track->isFlushPending()) {
5635 track->flushAck();
5636 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005637 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005638 }
Phil Burk6fc2a7c2015-04-30 16:08:10 -07005639 } else if (track->isResumePending()) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005640 track->resumeAck();
Eric Laurent3df841a2016-07-15 15:15:40 -07005641 if (last) {
5642 mLeftVolFloat = mRightVolFloat = -1.0;
5643 if (mHwPaused) {
5644 doHwResume = true;
5645 mHwPaused = false;
5646 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005647 }
5648 }
5649
Eric Laurent81784c32012-11-19 14:55:58 -08005650 // The first time a track is added we wait
Phil Burk99adee32014-12-10 16:46:30 -08005651 // for all its buffers to be filled before processing it.
5652 // Allow draining the buffer in case the client
5653 // app does not call stop() and relies on underrun to stop:
5654 // hence the test on (track->mRetryCount > 1).
5655 // If retryCount<=1 then track is about to underrun and be removed.
Phil Burkca5e6142015-07-14 09:42:29 -07005656 // Do not use a high threshold for compressed audio.
Eric Laurent81784c32012-11-19 14:55:58 -08005657 uint32_t minFrames;
Phil Burk99adee32014-12-10 16:46:30 -08005658 if ((track->sharedBuffer() == 0) && !track->isStopping_1() && !track->isPausing()
Phil Burkfdb3c072016-02-09 10:47:02 -08005659 && (track->mRetryCount > 1) && audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005660 minFrames = mNormalFrameCount;
5661 } else {
5662 minFrames = 1;
5663 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08005664
Mikhail Naganov76e89c32019-08-15 20:18:47 -07005665 const size_t framesReady = track->framesReady();
5666 const int trackId = track->id();
5667 if (ATRACE_ENABLED()) {
5668 std::string traceName("nRdy");
5669 traceName += std::to_string(trackId);
5670 ATRACE_INT(traceName.c_str(), framesReady);
5671 }
5672 if ((framesReady >= minFrames) && track->isReady() && !track->isPaused() &&
Eric Laurentab5cdba2014-06-09 17:22:27 -07005673 !track->isStopping_2() && !track->isStopped())
Eric Laurent81784c32012-11-19 14:55:58 -08005674 {
Mikhail Naganov76e89c32019-08-15 20:18:47 -07005675 ALOGVV("track(%d) s=%08x [OK]", trackId, cblk->mServer);
Eric Laurent81784c32012-11-19 14:55:58 -08005676
5677 if (track->mFillingUpStatus == Track::FS_FILLED) {
5678 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07005679 if (last) {
5680 // make sure processVolume_l() will apply new volume even if 0
5681 mLeftVolFloat = mRightVolFloat = -1.0;
5682 }
Eric Laurentd1f69b02014-12-15 14:33:13 -08005683 if (!mHwSupportsPause) {
5684 track->resumeAck();
Eric Laurent81784c32012-11-19 14:55:58 -08005685 }
5686 }
5687
5688 // compute volume for this track
Eric Laurentbfb1b832013-01-07 09:53:42 -08005689 processVolume_l(track, last);
5690 if (last) {
Phil Burk43b4dcc2015-06-09 16:53:44 -07005691 sp<Track> previousTrack = mPreviousTrack.promote();
5692 if (previousTrack != 0) {
5693 if (track != previousTrack.get()) {
5694 // Flush any data still being written from last track
5695 mBytesRemaining = 0;
Eric Laurent0f0631e2015-07-06 18:01:25 -07005696 // Invalidate previous track to force a seek when resuming.
5697 previousTrack->invalidate();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005698 }
5699 }
5700 mPreviousTrack = track;
5701
Eric Laurentd595b7c2013-04-03 17:27:56 -07005702 // reset retry count
5703 track->mRetryCount = kMaxTrackRetriesDirect;
Eric Laurent5850c4c2016-11-10 13:04:31 -08005704 mActiveTrack = t;
Eric Laurentd595b7c2013-04-03 17:27:56 -07005705 mixerStatus = MIXER_TRACKS_READY;
Eric Laurent5cff4032015-05-26 13:49:58 -07005706 if (mHwPaused) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005707 doHwResume = true;
5708 mHwPaused = false;
5709 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005710 }
Eric Laurent81784c32012-11-19 14:55:58 -08005711 } else {
Eric Laurentd595b7c2013-04-03 17:27:56 -07005712 // clear effect chain input buffer if the last active track started underruns
5713 // to avoid sending previous audio buffer again to effects
Eric Laurentfd477972013-10-25 18:10:40 -07005714 if (!mEffectChains.isEmpty() && last) {
Eric Laurent81784c32012-11-19 14:55:58 -08005715 mEffectChains[0]->clearInputBuffer();
5716 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005717 if (track->isStopping_1()) {
5718 track->mState = TrackBase::STOPPING_2;
Eric Laurentb369caf2015-03-30 20:51:47 -07005719 if (last && mHwPaused) {
5720 doHwResume = true;
5721 mHwPaused = false;
5722 }
Eric Laurentab5cdba2014-06-09 17:22:27 -07005723 }
5724 if ((track->sharedBuffer() != 0) || track->isStopped() ||
5725 track->isStopping_2() || track->isPaused()) {
Eric Laurent81784c32012-11-19 14:55:58 -08005726 // We have consumed all the buffers of this track.
5727 // Remove it from the list of active tracks.
Eric Laurentab5cdba2014-06-09 17:22:27 -07005728 size_t audioHALFrames;
Phil Burkfdb3c072016-02-09 10:47:02 -08005729 if (audio_has_proportional_frames(mFormat)) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005730 audioHALFrames = (latency_l() * mSampleRate) / 1000;
5731 } else {
5732 audioHALFrames = 0;
5733 }
5734
Andy Hung818e7a32016-02-16 18:08:07 -08005735 int64_t framesWritten = mBytesWritten / mFrameSize;
Eric Laurentfd477972013-10-25 18:10:40 -07005736 if (mStandby || !last ||
Aniket Kumar Lata179a0742019-01-30 14:16:16 -08005737 track->presentationComplete(framesWritten, audioHALFrames) ||
Jindong32dc26e2019-11-11 18:10:01 +08005738 track->isPaused() || mHwPaused) {
Eric Laurentab5cdba2014-06-09 17:22:27 -07005739 if (track->isStopping_2()) {
5740 track->mState = TrackBase::STOPPED;
5741 }
Eric Laurent81784c32012-11-19 14:55:58 -08005742 if (track->isStopped()) {
5743 track->reset();
5744 }
Eric Laurentd595b7c2013-04-03 17:27:56 -07005745 tracksToRemove->add(track);
Eric Laurent81784c32012-11-19 14:55:58 -08005746 }
5747 } else {
5748 // No buffers for this track. Give it a few chances to
5749 // fill a buffer, then remove it from active list.
Eric Laurentd595b7c2013-04-03 17:27:56 -07005750 // Only consider last track started for mixer state control
Eric Laurent81784c32012-11-19 14:55:58 -08005751 if (--(track->mRetryCount) <= 0) {
Mikhail Naganov76e89c32019-08-15 20:18:47 -07005752 ALOGV("BUFFER TIMEOUT: remove track(%d) from active list", trackId);
Eric Laurentd595b7c2013-04-03 17:27:56 -07005753 tracksToRemove->add(track);
Eric Laurenta23f17a2013-11-05 18:22:08 -08005754 // indicate to client process that the track was disabled because of underrun;
5755 // it will then automatically call start() when data is available
Eric Laurent4d231dc2016-03-11 18:38:23 -08005756 track->disable();
Eric Laurentbfb1b832013-01-07 09:53:42 -08005757 } else if (last) {
Phil Burkca5e6142015-07-14 09:42:29 -07005758 ALOGW("pause because of UNDERRUN, framesReady = %zu,"
5759 "minFrames = %u, mFormat = %#x",
Mikhail Naganov76e89c32019-08-15 20:18:47 -07005760 framesReady, minFrames, mFormat);
Eric Laurent81784c32012-11-19 14:55:58 -08005761 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurent5cff4032015-05-26 13:49:58 -07005762 if (mHwSupportsPause && !mHwPaused && !mStandby) {
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005763 doHwPause = true;
5764 mHwPaused = true;
5765 }
Eric Laurent81784c32012-11-19 14:55:58 -08005766 }
5767 }
5768 }
5769 }
5770
Eric Laurentd1f69b02014-12-15 14:33:13 -08005771 // if an active track did not command a flush, check for pending flush on stopped tracks
Phil Burk43b4dcc2015-06-09 16:53:44 -07005772 if (!mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005773 for (size_t i = 0; i < mTracks.size(); i++) {
5774 if (mTracks[i]->isFlushPending()) {
5775 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005776 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005777 }
5778 }
5779 }
5780
5781 // make sure the pause/flush/resume sequence is executed in the right order.
5782 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
5783 // before flush and then resume HW. This can happen in case of pause/flush/resume
5784 // if resume is received before pause is executed.
5785 if (mHwSupportsPause && !mStandby &&
Phil Burk43b4dcc2015-06-09 16:53:44 -07005786 (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005787 status_t result = mOutput->stream->pause();
5788 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005789 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005790 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005791 flushHw_l();
5792 }
5793 if (mHwSupportsPause && !mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005794 status_t result = mOutput->stream->resume();
5795 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005796 }
Eric Laurent81784c32012-11-19 14:55:58 -08005797 // remove all the tracks that need to be...
Eric Laurentbfb1b832013-01-07 09:53:42 -08005798 removeTracks_l(*tracksToRemove);
Eric Laurent81784c32012-11-19 14:55:58 -08005799
5800 return mixerStatus;
5801}
5802
5803void AudioFlinger::DirectOutputThread::threadLoop_mix()
5804{
Eric Laurent81784c32012-11-19 14:55:58 -08005805 size_t frameCount = mFrameCount;
Andy Hung2098f272014-02-27 14:00:06 -08005806 int8_t *curBuf = (int8_t *)mSinkBuffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005807 // output audio to hardware
5808 while (frameCount) {
Glenn Kasten34542ac2013-06-26 11:29:02 -07005809 AudioBufferProvider::Buffer buffer;
Eric Laurent81784c32012-11-19 14:55:58 -08005810 buffer.frameCount = frameCount;
Phil Burk062e67a2015-02-11 13:40:50 -08005811 status_t status = mActiveTrack->getNextBuffer(&buffer);
5812 if (status != NO_ERROR || buffer.raw == NULL) {
Eric Laurent51716182016-02-29 18:00:56 -08005813 // no need to pad with 0 for compressed audio
5814 if (audio_has_proportional_frames(mFormat)) {
5815 memset(curBuf, 0, frameCount * mFrameSize);
5816 }
Eric Laurent81784c32012-11-19 14:55:58 -08005817 break;
5818 }
5819 memcpy(curBuf, buffer.raw, buffer.frameCount * mFrameSize);
5820 frameCount -= buffer.frameCount;
5821 curBuf += buffer.frameCount * mFrameSize;
5822 mActiveTrack->releaseBuffer(&buffer);
5823 }
Andy Hung2098f272014-02-27 14:00:06 -08005824 mCurrentWriteLength = curBuf - (int8_t *)mSinkBuffer;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005825 mSleepTimeUs = 0;
5826 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08005827 mActiveTrack.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08005828}
5829
5830void AudioFlinger::DirectOutputThread::threadLoop_sleepTime()
5831{
Eric Laurentd1f69b02014-12-15 14:33:13 -08005832 // do not write to HAL when paused
Eric Laurent0f7b5f22014-12-19 10:43:21 -08005833 if (mHwPaused || (usesHwAvSync() && mStandby)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005834 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005835 return;
5836 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005837 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08005838 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurente93cc032016-05-05 10:15:10 -07005839 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005840 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005841 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005842 }
Phil Burkfdb3c072016-02-09 10:47:02 -08005843 } else if (mBytesWritten != 0 && audio_has_proportional_frames(mFormat)) {
Andy Hung2098f272014-02-27 14:00:06 -08005844 memset(mSinkBuffer, 0, mFrameCount * mFrameSize);
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005845 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08005846 }
5847}
5848
Eric Laurentd1f69b02014-12-15 14:33:13 -08005849void AudioFlinger::DirectOutputThread::threadLoop_exit()
5850{
5851 {
5852 Mutex::Autolock _l(mLock);
Eric Laurentd1f69b02014-12-15 14:33:13 -08005853 for (size_t i = 0; i < mTracks.size(); i++) {
5854 if (mTracks[i]->isFlushPending()) {
5855 mTracks[i]->flushAck();
Phil Burk43b4dcc2015-06-09 16:53:44 -07005856 mFlushPending = true;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005857 }
5858 }
Phil Burk43b4dcc2015-06-09 16:53:44 -07005859 if (mFlushPending) {
Eric Laurentd1f69b02014-12-15 14:33:13 -08005860 flushHw_l();
5861 }
5862 }
5863 PlaybackThread::threadLoop_exit();
5864}
5865
5866// must be called with thread mutex locked
5867bool AudioFlinger::DirectOutputThread::shouldStandby_l()
5868{
5869 bool trackPaused = false;
Eric Laurentb369caf2015-03-30 20:51:47 -07005870 bool trackStopped = false;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005871
vivek mehta9cd7ad12016-03-17 00:18:29 -07005872 if ((mType == DIRECT) && audio_is_linear_pcm(mFormat) && !usesHwAvSync()) {
5873 return !mStandby;
5874 }
5875
Eric Laurentd1f69b02014-12-15 14:33:13 -08005876 // do not put the HAL in standby when paused. AwesomePlayer clear the offloaded AudioTrack
5877 // after a timeout and we will enter standby then.
5878 if (mTracks.size() > 0) {
5879 trackPaused = mTracks[mTracks.size() - 1]->isPaused();
Eric Laurentb369caf2015-03-30 20:51:47 -07005880 trackStopped = mTracks[mTracks.size() - 1]->isStopped() ||
5881 mTracks[mTracks.size() - 1]->mState == TrackBase::IDLE;
Eric Laurentd1f69b02014-12-15 14:33:13 -08005882 }
5883
Eric Laurent5cff4032015-05-26 13:49:58 -07005884 return !mStandby && !(trackPaused || (mHwPaused && !trackStopped));
Eric Laurentd1f69b02014-12-15 14:33:13 -08005885}
5886
Eric Laurent10351942014-05-08 18:49:52 -07005887// checkForNewParameter_l() must be called with ThreadBase::mLock held
5888bool AudioFlinger::DirectOutputThread::checkForNewParameter_l(const String8& keyValuePair,
5889 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08005890{
5891 bool reconfig = false;
Eric Laurent42537be2016-01-08 17:16:42 -08005892 bool a2dpDeviceChanged = false;
Eric Laurent81784c32012-11-19 14:55:58 -08005893
Eric Laurent10351942014-05-08 18:49:52 -07005894 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08005895
Eric Laurent10351942014-05-08 18:49:52 -07005896 AudioParameter param = AudioParameter(keyValuePair);
5897 int value;
5898 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabin10d86fd2019-10-31 17:20:42 -07005899 LOG_FATAL("Should not set routing device in DirectOutputThread");
Eric Laurent81784c32012-11-19 14:55:58 -08005900 }
Eric Laurent10351942014-05-08 18:49:52 -07005901 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
5902 // do not accept frame count changes if tracks are open as the track buffer
5903 // size depends on frame count and correct behavior would not be garantied
5904 // if frame count is changed after track creation
5905 if (!mTracks.isEmpty()) {
5906 status = INVALID_OPERATION;
5907 } else {
5908 reconfig = true;
5909 }
5910 }
5911 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005912 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005913 if (!mStandby && status == INVALID_OPERATION) {
Phil Burk062e67a2015-02-11 13:40:50 -08005914 mOutput->standby();
Eric Laurent10351942014-05-08 18:49:52 -07005915 mStandby = true;
5916 mBytesWritten = 0;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07005917 status = mOutput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07005918 }
5919 if (status == NO_ERROR && reconfig) {
5920 readOutputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07005921 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
Eric Laurent10351942014-05-08 18:49:52 -07005922 }
5923 }
5924
Eric Laurent42537be2016-01-08 17:16:42 -08005925 return reconfig || a2dpDeviceChanged;
Eric Laurent81784c32012-11-19 14:55:58 -08005926}
5927
5928uint32_t AudioFlinger::DirectOutputThread::activeSleepTimeUs() const
5929{
5930 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005931 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005932 time = PlaybackThread::activeSleepTimeUs();
5933 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005934 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005935 }
5936 return time;
5937}
5938
5939uint32_t AudioFlinger::DirectOutputThread::idleSleepTimeUs() const
5940{
5941 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005942 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005943 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000) / 2;
5944 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005945 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005946 }
5947 return time;
5948}
5949
5950uint32_t AudioFlinger::DirectOutputThread::suspendSleepTimeUs() const
5951{
5952 uint32_t time;
Phil Burkfdb3c072016-02-09 10:47:02 -08005953 if (audio_has_proportional_frames(mFormat)) {
Eric Laurent81784c32012-11-19 14:55:58 -08005954 time = (uint32_t)(((mFrameCount * 1000) / mSampleRate) * 1000);
5955 } else {
Eric Laurent51716182016-02-29 18:00:56 -08005956 time = kDirectMinSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08005957 }
5958 return time;
5959}
5960
5961void AudioFlinger::DirectOutputThread::cacheParameters_l()
5962{
5963 PlaybackThread::cacheParameters_l();
5964
5965 // use shorter standby delay as on normal output to release
5966 // hardware resources as soon as possible
Eric Laurentb369caf2015-03-30 20:51:47 -07005967 // no delay on outputs with HW A/V sync
5968 if (usesHwAvSync()) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005969 mStandbyDelayNs = 0;
Phil Burkfdb3c072016-02-09 10:47:02 -08005970 } else if ((mType == OFFLOAD) && !audio_has_proportional_frames(mFormat)) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005971 mStandbyDelayNs = kOffloadStandbyDelayNs;
Eric Laurent5cff4032015-05-26 13:49:58 -07005972 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07005973 mStandbyDelayNs = microseconds(mActiveSleepTimeUs*2);
Eric Laurent972a1732013-09-04 09:42:59 -07005974 }
Eric Laurent81784c32012-11-19 14:55:58 -08005975}
5976
Eric Laurente659ef42014-09-29 13:06:46 -07005977void AudioFlinger::DirectOutputThread::flushHw_l()
5978{
Phil Burk062e67a2015-02-11 13:40:50 -08005979 mOutput->flush();
Eric Laurentd1f69b02014-12-15 14:33:13 -08005980 mHwPaused = false;
Phil Burk43b4dcc2015-06-09 16:53:44 -07005981 mFlushPending = false;
Andy Hungf3234512018-07-03 14:51:47 -07005982 mTimestampVerifier.discontinuity(); // DIRECT and OFFLOADED flush resets frame count.
Eric Laurente659ef42014-09-29 13:06:46 -07005983}
5984
Andy Hung10cbff12017-02-21 17:30:14 -08005985int64_t AudioFlinger::DirectOutputThread::computeWaitTimeNs_l() const {
5986 // If a VolumeShaper is active, we must wake up periodically to update volume.
5987 const int64_t NS_PER_MS = 1000000;
5988 return mVolumeShaperActive ?
5989 kMinNormalSinkBufferSizeMs * NS_PER_MS : PlaybackThread::computeWaitTimeNs_l();
5990}
5991
Eric Laurent81784c32012-11-19 14:55:58 -08005992// ----------------------------------------------------------------------------
5993
Eric Laurentbfb1b832013-01-07 09:53:42 -08005994AudioFlinger::AsyncCallbackThread::AsyncCallbackThread(
Eric Laurent4de95592013-09-26 15:28:21 -07005995 const wp<AudioFlinger::PlaybackThread>& playbackThread)
Eric Laurentbfb1b832013-01-07 09:53:42 -08005996 : Thread(false /*canCallJava*/),
Eric Laurent4de95592013-09-26 15:28:21 -07005997 mPlaybackThread(playbackThread),
Eric Laurent3b4529e2013-09-05 18:09:19 -07005998 mWriteAckSequence(0),
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07005999 mDrainSequence(0),
6000 mAsyncError(false)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006001{
6002}
6003
6004AudioFlinger::AsyncCallbackThread::~AsyncCallbackThread()
6005{
6006}
6007
6008void AudioFlinger::AsyncCallbackThread::onFirstRef()
6009{
6010 run("Offload Cbk", ANDROID_PRIORITY_URGENT_AUDIO);
6011}
6012
6013bool AudioFlinger::AsyncCallbackThread::threadLoop()
6014{
6015 while (!exitPending()) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006016 uint32_t writeAckSequence;
6017 uint32_t drainSequence;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006018 bool asyncError;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006019
6020 {
6021 Mutex::Autolock _l(mLock);
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006022 while (!((mWriteAckSequence & 1) ||
6023 (mDrainSequence & 1) ||
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006024 mAsyncError ||
Haynes Mathew George24a325d2013-12-03 21:26:02 -08006025 exitPending())) {
6026 mWaitWorkCV.wait(mLock);
6027 }
6028
Eric Laurentbfb1b832013-01-07 09:53:42 -08006029 if (exitPending()) {
6030 break;
6031 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006032 ALOGV("AsyncCallbackThread mWriteAckSequence %d mDrainSequence %d",
6033 mWriteAckSequence, mDrainSequence);
6034 writeAckSequence = mWriteAckSequence;
6035 mWriteAckSequence &= ~1;
6036 drainSequence = mDrainSequence;
6037 mDrainSequence &= ~1;
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006038 asyncError = mAsyncError;
6039 mAsyncError = false;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006040 }
6041 {
Eric Laurent4de95592013-09-26 15:28:21 -07006042 sp<AudioFlinger::PlaybackThread> playbackThread = mPlaybackThread.promote();
6043 if (playbackThread != 0) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006044 if (writeAckSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006045 playbackThread->resetWriteBlocked(writeAckSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006046 }
Eric Laurent3b4529e2013-09-05 18:09:19 -07006047 if (drainSequence & 1) {
Eric Laurent4de95592013-09-26 15:28:21 -07006048 playbackThread->resetDraining(drainSequence >> 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006049 }
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006050 if (asyncError) {
6051 playbackThread->onAsyncError();
6052 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006053 }
6054 }
6055 }
6056 return false;
6057}
6058
6059void AudioFlinger::AsyncCallbackThread::exit()
6060{
6061 ALOGV("AsyncCallbackThread::exit");
6062 Mutex::Autolock _l(mLock);
6063 requestExit();
6064 mWaitWorkCV.broadcast();
6065}
6066
Eric Laurent3b4529e2013-09-05 18:09:19 -07006067void AudioFlinger::AsyncCallbackThread::setWriteBlocked(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006068{
6069 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006070 // bit 0 is cleared
6071 mWriteAckSequence = sequence << 1;
6072}
6073
6074void AudioFlinger::AsyncCallbackThread::resetWriteBlocked()
6075{
6076 Mutex::Autolock _l(mLock);
6077 // ignore unexpected callbacks
6078 if (mWriteAckSequence & 2) {
6079 mWriteAckSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006080 mWaitWorkCV.signal();
6081 }
6082}
6083
Eric Laurent3b4529e2013-09-05 18:09:19 -07006084void AudioFlinger::AsyncCallbackThread::setDraining(uint32_t sequence)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006085{
6086 Mutex::Autolock _l(mLock);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006087 // bit 0 is cleared
6088 mDrainSequence = sequence << 1;
6089}
6090
6091void AudioFlinger::AsyncCallbackThread::resetDraining()
6092{
6093 Mutex::Autolock _l(mLock);
6094 // ignore unexpected callbacks
6095 if (mDrainSequence & 2) {
6096 mDrainSequence |= 1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006097 mWaitWorkCV.signal();
6098 }
6099}
6100
Haynes Mathew George4527b9e2016-07-07 19:54:17 -07006101void AudioFlinger::AsyncCallbackThread::setAsyncError()
6102{
6103 Mutex::Autolock _l(mLock);
6104 mAsyncError = true;
6105 mWaitWorkCV.signal();
6106}
6107
Eric Laurentbfb1b832013-01-07 09:53:42 -08006108
6109// ----------------------------------------------------------------------------
6110AudioFlinger::OffloadThread::OffloadThread(const sp<AudioFlinger>& audioFlinger,
jiabin10d86fd2019-10-31 17:20:42 -07006111 AudioStreamOut* output, audio_io_handle_t id, bool systemReady)
6112 : DirectOutputThread(audioFlinger, output, id, OFFLOAD, systemReady),
Andy Hungf8044752016-07-27 14:58:11 -07006113 mPausedWriteLength(0), mPausedBytesRemaining(0), mKeepWakeLock(true),
6114 mOffloadUnderrunPosition(~0LL)
Eric Laurentbfb1b832013-01-07 09:53:42 -08006115{
Sanna Catherine de Treville Wager2a6a9452017-07-28 11:02:01 -07006116 //FIXME: mStandby should be set to true by ThreadBase constructo
Eric Laurentfd477972013-10-25 18:10:40 -07006117 mStandby = true;
Eric Laurent64667972016-03-30 18:19:46 -07006118 mKeepWakeLock = property_get_bool("ro.audio.offload_wakelock", true /* default_value */);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006119}
6120
Eric Laurentbfb1b832013-01-07 09:53:42 -08006121void AudioFlinger::OffloadThread::threadLoop_exit()
6122{
6123 if (mFlushPending || mHwPaused) {
6124 // If a flush is pending or track was paused, just discard buffered data
6125 flushHw_l();
6126 } else {
6127 mMixerStatus = MIXER_DRAIN_ALL;
6128 threadLoop_drain();
6129 }
Uday Gupta56604aa2014-05-13 11:19:17 -07006130 if (mUseAsyncWrite) {
6131 ALOG_ASSERT(mCallbackThread != 0);
6132 mCallbackThread->exit();
6133 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006134 PlaybackThread::threadLoop_exit();
6135}
6136
6137AudioFlinger::PlaybackThread::mixer_state AudioFlinger::OffloadThread::prepareTracks_l(
6138 Vector< sp<Track> > *tracksToRemove
6139)
6140{
Eric Laurentbfb1b832013-01-07 09:53:42 -08006141 size_t count = mActiveTracks.size();
6142
6143 mixer_state mixerStatus = MIXER_IDLE;
Eric Laurent972a1732013-09-04 09:42:59 -07006144 bool doHwPause = false;
6145 bool doHwResume = false;
6146
Glenn Kastenc42e9b42016-03-21 11:35:03 -07006147 ALOGV("OffloadThread::prepareTracks_l active tracks %zu", count);
Eric Laurentede6c3b2013-09-19 14:37:46 -07006148
Eric Laurentbfb1b832013-01-07 09:53:42 -08006149 // find out which tracks need to be processed
Andy Hungdae27702016-10-31 14:01:16 -07006150 for (const sp<Track> &t : mActiveTracks) {
Eric Laurent5850c4c2016-11-10 13:04:31 -08006151 Track* const track = t.get();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006152#ifdef VERY_VERY_VERBOSE_LOGGING
Eric Laurentbfb1b832013-01-07 09:53:42 -08006153 audio_track_cblk_t* cblk = track->cblk();
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006154#endif
Eric Laurentfd477972013-10-25 18:10:40 -07006155 // Only consider last track started for volume and mixer state control.
6156 // In theory an older track could underrun and restart after the new one starts
6157 // but as we only care about the transition phase between two tracks on a
6158 // direct output, it is not a problem to ignore the underrun case.
Andy Hungdae27702016-10-31 14:01:16 -07006159 sp<Track> l = mActiveTracks.getLatest();
Eric Laurent5850c4c2016-11-10 13:04:31 -08006160 bool last = l.get() == track;
Eric Laurentfd477972013-10-25 18:10:40 -07006161
Haynes Mathew George7844f672014-01-15 12:32:55 -08006162 if (track->isInvalid()) {
6163 ALOGW("An invalidated track shouldn't be in active list");
6164 tracksToRemove->add(track);
6165 continue;
6166 }
6167
6168 if (track->mState == TrackBase::IDLE) {
6169 ALOGW("An idle track shouldn't be in active list");
6170 continue;
6171 }
6172
Eric Laurentbfb1b832013-01-07 09:53:42 -08006173 if (track->isPausing()) {
6174 track->setPaused();
6175 if (last) {
Eric Laurent5cff4032015-05-26 13:49:58 -07006176 if (mHwSupportsPause && !mHwPaused) {
Eric Laurent972a1732013-09-04 09:42:59 -07006177 doHwPause = true;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006178 mHwPaused = true;
6179 }
6180 // If we were part way through writing the mixbuffer to
6181 // the HAL we must save this until we resume
6182 // BUG - this will be wrong if a different track is made active,
6183 // in that case we want to discard the pending data in the
6184 // mixbuffer and tell the client to present it again when the
6185 // track is resumed
6186 mPausedWriteLength = mCurrentWriteLength;
6187 mPausedBytesRemaining = mBytesRemaining;
6188 mBytesRemaining = 0; // stop writing
6189 }
6190 tracksToRemove->add(track);
Haynes Mathew George7844f672014-01-15 12:32:55 -08006191 } else if (track->isFlushPending()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006192 if (track->isStopping_1()) {
6193 track->mRetryCount = kMaxTrackStopRetriesOffload;
6194 } else {
6195 track->mRetryCount = kMaxTrackRetriesOffload;
6196 }
Haynes Mathew George7844f672014-01-15 12:32:55 -08006197 track->flushAck();
6198 if (last) {
6199 mFlushPending = true;
6200 }
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006201 } else if (track->isResumePending()){
6202 track->resumeAck();
6203 if (last) {
6204 if (mPausedBytesRemaining) {
6205 // Need to continue write that was interrupted
6206 mCurrentWriteLength = mPausedWriteLength;
6207 mBytesRemaining = mPausedBytesRemaining;
6208 mPausedBytesRemaining = 0;
6209 }
6210 if (mHwPaused) {
6211 doHwResume = true;
6212 mHwPaused = false;
6213 // threadLoop_mix() will handle the case that we need to
6214 // resume an interrupted write
6215 }
6216 // enable write to audio HAL
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006217 mSleepTimeUs = 0;
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006218
Eric Laurent3df841a2016-07-15 15:15:40 -07006219 mLeftVolFloat = mRightVolFloat = -1.0;
6220
Haynes Mathew George2d3ca682014-03-07 13:43:49 -08006221 // Do not handle new data in this iteration even if track->framesReady()
6222 mixerStatus = MIXER_TRACKS_ENABLED;
6223 }
6224 } else if (track->framesReady() && track->isReady() &&
Eric Laurent3b4529e2013-09-05 18:09:19 -07006225 !track->isPaused() && !track->isTerminated() && !track->isStopping_2()) {
Andy Hungc0691382018-09-12 18:01:57 -07006226 ALOGVV("OffloadThread: track(%d) s=%08x [OK]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006227 if (track->mFillingUpStatus == Track::FS_FILLED) {
6228 track->mFillingUpStatus = Track::FS_ACTIVE;
Eric Laurent3df841a2016-07-15 15:15:40 -07006229 if (last) {
6230 // make sure processVolume_l() will apply new volume even if 0
6231 mLeftVolFloat = mRightVolFloat = -1.0;
6232 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006233 }
6234
6235 if (last) {
Eric Laurentd7e59222013-11-15 12:02:28 -08006236 sp<Track> previousTrack = mPreviousTrack.promote();
6237 if (previousTrack != 0) {
6238 if (track != previousTrack.get()) {
Eric Laurent9da3d952013-11-12 19:25:43 -08006239 // Flush any data still being written from last track
6240 mBytesRemaining = 0;
6241 if (mPausedBytesRemaining) {
6242 // Last track was paused so we also need to flush saved
6243 // mixbuffer state and invalidate track so that it will
6244 // re-submit that unwritten data when it is next resumed
6245 mPausedBytesRemaining = 0;
6246 // Invalidate is a bit drastic - would be more efficient
6247 // to have a flag to tell client that some of the
6248 // previously written data was lost
Eric Laurentd7e59222013-11-15 12:02:28 -08006249 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006250 }
6251 // flush data already sent to the DSP if changing audio session as audio
6252 // comes from a different source. Also invalidate previous track to force a
6253 // seek when resuming.
Eric Laurentd7e59222013-11-15 12:02:28 -08006254 if (previousTrack->sessionId() != track->sessionId()) {
6255 previousTrack->invalidate();
Eric Laurent9da3d952013-11-12 19:25:43 -08006256 }
6257 }
6258 }
6259 mPreviousTrack = track;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006260 // reset retry count
Eric Laurente93cc032016-05-05 10:15:10 -07006261 if (track->isStopping_1()) {
6262 track->mRetryCount = kMaxTrackStopRetriesOffload;
6263 } else {
6264 track->mRetryCount = kMaxTrackRetriesOffload;
6265 }
Eric Laurent5850c4c2016-11-10 13:04:31 -08006266 mActiveTrack = t;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006267 mixerStatus = MIXER_TRACKS_READY;
6268 }
6269 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006270 ALOGVV("OffloadThread: track(%d) s=%08x [NOT READY]", track->id(), cblk->mServer);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006271 if (track->isStopping_1()) {
Eric Laurente93cc032016-05-05 10:15:10 -07006272 if (--(track->mRetryCount) <= 0) {
6273 // Hardware buffer can hold a large amount of audio so we must
6274 // wait for all current track's data to drain before we say
6275 // that the track is stopped.
6276 if (mBytesRemaining == 0) {
6277 // Only start draining when all data in mixbuffer
6278 // has been written
6279 ALOGV("OffloadThread: underrun and STOPPING_1 -> draining, STOPPING_2");
6280 track->mState = TrackBase::STOPPING_2; // so presentation completes after
6281 // drain do not drain if no data was ever sent to HAL (mStandby == true)
6282 if (last && !mStandby) {
6283 // do not modify drain sequence if we are already draining. This happens
6284 // when resuming from pause after drain.
6285 if ((mDrainSequence & 1) == 0) {
6286 mSleepTimeUs = 0;
6287 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
6288 mixerStatus = MIXER_DRAIN_TRACK;
6289 mDrainSequence += 2;
6290 }
6291 if (mHwPaused) {
6292 // It is possible to move from PAUSED to STOPPING_1 without
6293 // a resume so we must ensure hardware is running
6294 doHwResume = true;
6295 mHwPaused = false;
6296 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006297 }
6298 }
Eric Laurente93cc032016-05-05 10:15:10 -07006299 } else if (last) {
6300 ALOGV("stopping1 underrun retries left %d", track->mRetryCount);
6301 mixerStatus = MIXER_TRACKS_ENABLED;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006302 }
6303 } else if (track->isStopping_2()) {
Eric Laurent6a51d7e2013-10-17 18:59:26 -07006304 // Drain has completed or we are in standby, signal presentation complete
6305 if (!(mDrainSequence & 1) || !last || mStandby) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006306 track->mState = TrackBase::STOPPED;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006307 uint32_t latency = 0;
6308 status_t result = mOutput->stream->getLatency(&latency);
6309 ALOGE_IF(result != OK,
6310 "Error when retrieving output stream latency: %d", result);
6311 size_t audioHALFrames = (latency * mSampleRate) / 1000;
Andy Hung818e7a32016-02-16 18:08:07 -08006312 int64_t framesWritten =
Phil Burk062e67a2015-02-11 13:40:50 -08006313 mBytesWritten / mOutput->getFrameSize();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006314 track->presentationComplete(framesWritten, audioHALFrames);
6315 track->reset();
6316 tracksToRemove->add(track);
Andy Hungf3234512018-07-03 14:51:47 -07006317 // DIRECT and OFFLOADED stop resets frame counts.
6318 if (!mUseAsyncWrite) {
6319 // If we don't get explicit drain notification we must
6320 // register discontinuity regardless of whether this is
6321 // the previous (!last) or the upcoming (last) track
6322 // to avoid skipping the discontinuity.
6323 mTimestampVerifier.discontinuity();
6324 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006325 }
6326 } else {
6327 // No buffers for this track. Give it a few chances to
6328 // fill a buffer, then remove it from active list.
6329 if (--(track->mRetryCount) <= 0) {
Andy Hungf8044752016-07-27 14:58:11 -07006330 bool running = false;
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006331 uint64_t position = 0;
6332 struct timespec unused;
6333 // The running check restarts the retry counter at least once.
6334 status_t ret = mOutput->stream->getPresentationPosition(&position, &unused);
6335 if (ret == NO_ERROR && position != mOffloadUnderrunPosition) {
6336 running = true;
6337 mOffloadUnderrunPosition = position;
6338 }
6339 if (ret == NO_ERROR) {
Andy Hungf8044752016-07-27 14:58:11 -07006340 ALOGVV("underrun counter, running(%d): %lld vs %lld", running,
6341 (long long)position, (long long)mOffloadUnderrunPosition);
6342 }
6343 if (running) { // still running, give us more time.
6344 track->mRetryCount = kMaxTrackRetriesOffload;
6345 } else {
Andy Hungc0691382018-09-12 18:01:57 -07006346 ALOGV("OffloadThread: BUFFER TIMEOUT: remove track(%d) from active list",
6347 track->id());
Andy Hungf8044752016-07-27 14:58:11 -07006348 tracksToRemove->add(track);
Glenn Kastend3bb6452016-12-05 18:14:37 -08006349 // tell client process that the track was disabled because of underrun;
Andy Hungf8044752016-07-27 14:58:11 -07006350 // it will then automatically call start() when data is available
6351 track->disable();
6352 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006353 } else if (last){
6354 mixerStatus = MIXER_TRACKS_ENABLED;
6355 }
6356 }
6357 }
6358 // compute volume for this track
Wenfeng Sun79458332019-05-29 20:12:43 +08006359 if (track->isReady()) { // check ready to prevent premature start.
6360 processVolume_l(track, last);
6361 }
Eric Laurentbfb1b832013-01-07 09:53:42 -08006362 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006363
Eric Laurentea0fade2013-10-04 16:23:48 -07006364 // make sure the pause/flush/resume sequence is executed in the right order.
6365 // If a flush is pending and a track is active but the HW is not paused, force a HW pause
6366 // before flush and then resume HW. This can happen in case of pause/flush/resume
6367 // if resume is received before pause is executed.
Eric Laurentfd477972013-10-25 18:10:40 -07006368 if (!mStandby && (doHwPause || (mFlushPending && !mHwPaused && (count != 0)))) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006369 status_t result = mOutput->stream->pause();
6370 ALOGE_IF(result != OK, "Error when pausing output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006371 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006372 if (mFlushPending) {
6373 flushHw_l();
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006374 }
Eric Laurentfd477972013-10-25 18:10:40 -07006375 if (!mStandby && doHwResume) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07006376 status_t result = mOutput->stream->resume();
6377 ALOGE_IF(result != OK, "Error when resuming output stream: %d", result);
Eric Laurent972a1732013-09-04 09:42:59 -07006378 }
Eric Laurent6bf9ae22013-08-30 15:12:37 -07006379
Eric Laurentbfb1b832013-01-07 09:53:42 -08006380 // remove all the tracks that need to be...
6381 removeTracks_l(*tracksToRemove);
6382
6383 return mixerStatus;
6384}
6385
Eric Laurentbfb1b832013-01-07 09:53:42 -08006386// must be called with thread mutex locked
6387bool AudioFlinger::OffloadThread::waitingAsyncCallback_l()
6388{
Eric Laurent3b4529e2013-09-05 18:09:19 -07006389 ALOGVV("waitingAsyncCallback_l mWriteAckSequence %d mDrainSequence %d",
6390 mWriteAckSequence, mDrainSequence);
6391 if (mUseAsyncWrite && ((mWriteAckSequence & 1) || (mDrainSequence & 1))) {
Eric Laurentbfb1b832013-01-07 09:53:42 -08006392 return true;
6393 }
6394 return false;
6395}
6396
Eric Laurentbfb1b832013-01-07 09:53:42 -08006397bool AudioFlinger::OffloadThread::waitingAsyncCallback()
6398{
6399 Mutex::Autolock _l(mLock);
6400 return waitingAsyncCallback_l();
6401}
6402
6403void AudioFlinger::OffloadThread::flushHw_l()
6404{
Eric Laurente659ef42014-09-29 13:06:46 -07006405 DirectOutputThread::flushHw_l();
Eric Laurentbfb1b832013-01-07 09:53:42 -08006406 // Flush anything still waiting in the mixbuffer
6407 mCurrentWriteLength = 0;
6408 mBytesRemaining = 0;
6409 mPausedWriteLength = 0;
6410 mPausedBytesRemaining = 0;
Eric Laurent3eaf66b2016-04-01 14:44:17 -07006411 // reset bytes written count to reflect that DSP buffers are empty after flush.
6412 mBytesWritten = 0;
Andy Hungf8044752016-07-27 14:58:11 -07006413 mOffloadUnderrunPosition = ~0LL;
Haynes Mathew George0f02f262014-01-11 13:03:57 -08006414
Eric Laurentbfb1b832013-01-07 09:53:42 -08006415 if (mUseAsyncWrite) {
Eric Laurent3b4529e2013-09-05 18:09:19 -07006416 // discard any pending drain or write ack by incrementing sequence
6417 mWriteAckSequence = (mWriteAckSequence + 2) & ~1;
6418 mDrainSequence = (mDrainSequence + 2) & ~1;
Eric Laurentbfb1b832013-01-07 09:53:42 -08006419 ALOG_ASSERT(mCallbackThread != 0);
Eric Laurent3b4529e2013-09-05 18:09:19 -07006420 mCallbackThread->setWriteBlocked(mWriteAckSequence);
6421 mCallbackThread->setDraining(mDrainSequence);
Eric Laurentbfb1b832013-01-07 09:53:42 -08006422 }
6423}
6424
Haynes Mathew George05317d22016-05-03 16:34:26 -07006425void AudioFlinger::OffloadThread::invalidateTracks(audio_stream_type_t streamType)
6426{
6427 Mutex::Autolock _l(mLock);
Eric Laurent13084622016-05-17 10:51:49 -07006428 if (PlaybackThread::invalidateTracks_l(streamType)) {
6429 mFlushPending = true;
6430 }
Haynes Mathew George05317d22016-05-03 16:34:26 -07006431}
6432
Eric Laurentbfb1b832013-01-07 09:53:42 -08006433// ----------------------------------------------------------------------------
6434
Eric Laurent81784c32012-11-19 14:55:58 -08006435AudioFlinger::DuplicatingThread::DuplicatingThread(const sp<AudioFlinger>& audioFlinger,
Eric Laurent72e3f392015-05-20 14:43:50 -07006436 AudioFlinger::MixerThread* mainThread, audio_io_handle_t id, bool systemReady)
jiabin10d86fd2019-10-31 17:20:42 -07006437 : MixerThread(audioFlinger, mainThread->getOutput(), id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006438 systemReady, DUPLICATING),
Eric Laurent81784c32012-11-19 14:55:58 -08006439 mWaitTimeMs(UINT_MAX)
6440{
6441 addOutputTrack(mainThread);
6442}
6443
6444AudioFlinger::DuplicatingThread::~DuplicatingThread()
6445{
6446 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6447 mOutputTracks[i]->destroy();
6448 }
6449}
6450
6451void AudioFlinger::DuplicatingThread::threadLoop_mix()
6452{
6453 // mix buffers...
6454 if (outputsReady(outputTracks)) {
Glenn Kastend79072e2016-01-06 08:41:20 -08006455 mAudioMixer->process();
Eric Laurent81784c32012-11-19 14:55:58 -08006456 } else {
Eric Laurent02b57082014-11-07 17:28:28 -08006457 if (mMixerBufferValid) {
6458 memset(mMixerBuffer, 0, mMixerBufferSize);
6459 } else {
6460 memset(mSinkBuffer, 0, mSinkBufferSize);
6461 }
Eric Laurent81784c32012-11-19 14:55:58 -08006462 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006463 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006464 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006465 mCurrentWriteLength = mSinkBufferSize;
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006466 mStandbyTimeNs = systemTime() + mStandbyDelayNs;
Eric Laurent81784c32012-11-19 14:55:58 -08006467}
6468
6469void AudioFlinger::DuplicatingThread::threadLoop_sleepTime()
6470{
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006471 if (mSleepTimeUs == 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08006472 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006473 mSleepTimeUs = mActiveSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006474 } else {
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006475 mSleepTimeUs = mIdleSleepTimeUs;
Eric Laurent81784c32012-11-19 14:55:58 -08006476 }
6477 } else if (mBytesWritten != 0) {
6478 if (mMixerStatus == MIXER_TRACKS_ENABLED) {
6479 writeFrames = mNormalFrameCount;
Andy Hung25c2dac2014-02-27 14:56:00 -08006480 memset(mSinkBuffer, 0, mSinkBufferSize);
Eric Laurent81784c32012-11-19 14:55:58 -08006481 } else {
6482 // flush remaining overflow buffers in output tracks
6483 writeFrames = 0;
6484 }
Eric Laurentad9cb8b2015-05-26 16:38:19 -07006485 mSleepTimeUs = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08006486 }
6487}
6488
Eric Laurentbfb1b832013-01-07 09:53:42 -08006489ssize_t AudioFlinger::DuplicatingThread::threadLoop_write()
Eric Laurent81784c32012-11-19 14:55:58 -08006490{
6491 for (size_t i = 0; i < outputTracks.size(); i++) {
Andy Hung1c86ebe2018-05-29 20:29:08 -07006492 const ssize_t actualWritten = outputTracks[i]->write(mSinkBuffer, writeFrames);
6493
6494 // Consider the first OutputTrack for timestamp and frame counting.
6495
6496 // The threadLoop() generally assumes writing a full sink buffer size at a time.
6497 // Here, we correct for writeFrames of 0 (a stop) or underruns because
6498 // we always claim success.
6499 if (i == 0) {
6500 const ssize_t correction = mSinkBufferSize / mFrameSize - actualWritten;
6501 ALOGD_IF(correction != 0 && writeFrames != 0,
6502 "%s: writeFrames:%u actualWritten:%zd correction:%zd mFramesWritten:%lld",
6503 __func__, writeFrames, actualWritten, correction, (long long)mFramesWritten);
6504 mFramesWritten -= correction;
6505 }
6506
6507 // TODO: Report correction for the other output tracks and show in the dump.
Eric Laurent81784c32012-11-19 14:55:58 -08006508 }
Eric Laurent2c3740f2013-10-30 16:57:06 -07006509 mStandby = false;
Andy Hung25c2dac2014-02-27 14:56:00 -08006510 return (ssize_t)mSinkBufferSize;
Eric Laurent81784c32012-11-19 14:55:58 -08006511}
6512
6513void AudioFlinger::DuplicatingThread::threadLoop_standby()
6514{
6515 // DuplicatingThread implements standby by stopping all tracks
6516 for (size_t i = 0; i < outputTracks.size(); i++) {
6517 outputTracks[i]->stop();
6518 }
6519}
6520
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006521void AudioFlinger::DuplicatingThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Andy Hung1bc088a2018-02-09 15:57:31 -08006522{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07006523 MixerThread::dumpInternals_l(fd, args);
Andy Hung1bc088a2018-02-09 15:57:31 -08006524
6525 std::stringstream ss;
6526 const size_t numTracks = mOutputTracks.size();
6527 ss << " " << numTracks << " OutputTracks";
6528 if (numTracks > 0) {
6529 ss << ":";
6530 for (const auto &track : mOutputTracks) {
6531 const sp<ThreadBase> thread = track->thread().promote();
Andy Hungc0691382018-09-12 18:01:57 -07006532 ss << " (" << track->id() << " : ";
Andy Hung1bc088a2018-02-09 15:57:31 -08006533 if (thread.get() != nullptr) {
6534 ss << thread.get() << ", " << thread->id();
6535 } else {
6536 ss << "null";
6537 }
6538 ss << ")";
6539 }
6540 }
6541 ss << "\n";
6542 std::string result = ss.str();
6543 write(fd, result.c_str(), result.size());
6544}
6545
Eric Laurent81784c32012-11-19 14:55:58 -08006546void AudioFlinger::DuplicatingThread::saveOutputTracks()
6547{
6548 outputTracks = mOutputTracks;
6549}
6550
6551void AudioFlinger::DuplicatingThread::clearOutputTracks()
6552{
6553 outputTracks.clear();
6554}
6555
6556void AudioFlinger::DuplicatingThread::addOutputTrack(MixerThread *thread)
6557{
6558 Mutex::Autolock _l(mLock);
Andy Hungc25b84a2015-01-14 19:04:10 -08006559 // The downstream MixerThread consumes thread->frameCount() amount of frames per mix pass.
6560 // Adjust for thread->sampleRate() to determine minimum buffer frame count.
6561 // Then triple buffer because Threads do not run synchronously and may not be clock locked.
6562 const size_t frameCount =
6563 3 * sourceFramesNeeded(mSampleRate, thread->frameCount(), thread->sampleRate());
6564 // TODO: Consider asynchronous sample rate conversion to handle clock disparity
6565 // from different OutputTracks and their associated MixerThreads (e.g. one may
6566 // nearly empty and the other may be dropping data).
6567
6568 sp<OutputTrack> outputTrack = new OutputTrack(thread,
Eric Laurent81784c32012-11-19 14:55:58 -08006569 this,
6570 mSampleRate,
Andy Hungc25b84a2015-01-14 19:04:10 -08006571 mFormat,
Eric Laurent81784c32012-11-19 14:55:58 -08006572 mChannelMask,
Marco Nelissen462fd2f2013-01-14 14:12:05 -08006573 frameCount,
6574 IPCThreadState::self()->getCallingUid());
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006575 status_t status = outputTrack != 0 ? outputTrack->initCheck() : (status_t) NO_MEMORY;
6576 if (status != NO_ERROR) {
6577 ALOGE("addOutputTrack() initCheck failed %d", status);
6578 return;
Eric Laurent81784c32012-11-19 14:55:58 -08006579 }
Eric Laurentaf3ec7c2016-08-01 11:25:19 -07006580 thread->setStreamVolume(AUDIO_STREAM_PATCH, 1.0f);
6581 mOutputTracks.add(outputTrack);
6582 ALOGV("addOutputTrack() track %p, on thread %p", outputTrack.get(), thread);
6583 updateWaitTime_l();
Eric Laurent81784c32012-11-19 14:55:58 -08006584}
6585
6586void AudioFlinger::DuplicatingThread::removeOutputTrack(MixerThread *thread)
6587{
6588 Mutex::Autolock _l(mLock);
6589 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6590 if (mOutputTracks[i]->thread() == thread) {
6591 mOutputTracks[i]->destroy();
6592 mOutputTracks.removeAt(i);
6593 updateWaitTime_l();
Eric Laurentf6870ae2015-05-08 10:50:03 -07006594 if (thread->getOutput() == mOutput) {
6595 mOutput = NULL;
6596 }
Eric Laurent81784c32012-11-19 14:55:58 -08006597 return;
6598 }
6599 }
Eric Laurentf6870ae2015-05-08 10:50:03 -07006600 ALOGV("removeOutputTrack(): unknown thread: %p", thread);
Eric Laurent81784c32012-11-19 14:55:58 -08006601}
6602
6603// caller must hold mLock
6604void AudioFlinger::DuplicatingThread::updateWaitTime_l()
6605{
6606 mWaitTimeMs = UINT_MAX;
6607 for (size_t i = 0; i < mOutputTracks.size(); i++) {
6608 sp<ThreadBase> strong = mOutputTracks[i]->thread().promote();
6609 if (strong != 0) {
6610 uint32_t waitTimeMs = (strong->frameCount() * 2 * 1000) / strong->sampleRate();
6611 if (waitTimeMs < mWaitTimeMs) {
6612 mWaitTimeMs = waitTimeMs;
6613 }
6614 }
6615 }
6616}
6617
6618
6619bool AudioFlinger::DuplicatingThread::outputsReady(
6620 const SortedVector< sp<OutputTrack> > &outputTracks)
6621{
6622 for (size_t i = 0; i < outputTracks.size(); i++) {
6623 sp<ThreadBase> thread = outputTracks[i]->thread().promote();
6624 if (thread == 0) {
6625 ALOGW("DuplicatingThread::outputsReady() could not promote thread on output track %p",
6626 outputTracks[i].get());
6627 return false;
6628 }
6629 PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
6630 // see note at standby() declaration
6631 if (playbackThread->standby() && !playbackThread->isSuspended()) {
6632 ALOGV("DuplicatingThread output track %p on thread %p Not Ready", outputTracks[i].get(),
6633 thread.get());
6634 return false;
6635 }
6636 }
6637 return true;
6638}
6639
Kevin Rocard12381092018-04-11 09:19:59 -07006640void AudioFlinger::DuplicatingThread::sendMetadataToBackend_l(
6641 const StreamOutHalInterface::SourceMetadata& metadata)
Kevin Rocard069c2712018-03-29 19:09:14 -07006642{
Kevin Rocard12381092018-04-11 09:19:59 -07006643 for (auto& outputTrack : outputTracks) { // not mOutputTracks
6644 outputTrack->setMetadatas(metadata.tracks);
6645 }
Kevin Rocard069c2712018-03-29 19:09:14 -07006646}
6647
Eric Laurent81784c32012-11-19 14:55:58 -08006648uint32_t AudioFlinger::DuplicatingThread::activeSleepTimeUs() const
6649{
6650 return (mWaitTimeMs * 1000) / 2;
6651}
6652
6653void AudioFlinger::DuplicatingThread::cacheParameters_l()
6654{
6655 // updateWaitTime_l() sets mWaitTimeMs, which affects activeSleepTimeUs(), so call it first
6656 updateWaitTime_l();
6657
6658 MixerThread::cacheParameters_l();
6659}
6660
Eric Laurent6acd1d42017-01-04 14:23:29 -08006661
Eric Laurent81784c32012-11-19 14:55:58 -08006662// ----------------------------------------------------------------------------
6663// Record
6664// ----------------------------------------------------------------------------
6665
6666AudioFlinger::RecordThread::RecordThread(const sp<AudioFlinger>& audioFlinger,
6667 AudioStreamIn *input,
Eric Laurent81784c32012-11-19 14:55:58 -08006668 audio_io_handle_t id,
Eric Laurent72e3f392015-05-20 14:43:50 -07006669 bool systemReady
Glenn Kasten46909e72013-02-26 09:20:22 -08006670 ) :
jiabin10d86fd2019-10-31 17:20:42 -07006671 ThreadBase(audioFlinger, id, RECORD, systemReady),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006672 mInput(input),
Mikhail Naganovaf288872019-09-25 13:05:02 -07006673 mSource(mInput),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07006674 mActiveTracks(&this->mLocalLog),
6675 mRsmpInBuffer(NULL),
Glenn Kasten1b291842016-07-18 14:55:21 -07006676 // mRsmpInFrames, mRsmpInFramesP2, and mRsmpInFramesOA are set by readInputParameters_l()
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08006677 mRsmpInRear(0)
Glenn Kastenb880f5e2014-05-07 08:43:45 -07006678 , mReadOnlyHeap(new MemoryDealer(kRecordThreadReadOnlyHeapSize,
6679 "RecordThreadRO", MemoryHeapBase::READ_ONLY))
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006680 // mFastCapture below
6681 , mFastCaptureFutex(0)
6682 // mInputSource
6683 // mPipeSink
6684 // mPipeSource
6685 , mPipeFramesP2(0)
6686 // mPipeMemory
6687 // mFastCaptureNBLogWriter
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006688 , mFastTrackAvail(false)
Eric Laurentd8365c52017-07-16 15:27:05 -07006689 , mBtNrecSuspended(false)
Eric Laurent81784c32012-11-19 14:55:58 -08006690{
Glenn Kastend7dca052015-03-05 16:05:54 -08006691 snprintf(mThreadName, kThreadNameLength, "AudioIn_%X", id);
6692 mNBLogWriter = audioFlinger->newWriter_l(kLogSize, mThreadName);
Eric Laurent81784c32012-11-19 14:55:58 -08006693
Andy Hungc8fddf32018-08-08 18:32:37 -07006694 if (mInput != nullptr && mInput->audioHwDev != nullptr) {
6695 mIsMsdDevice = strcmp(
6696 mInput->audioHwDev->moduleName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0;
6697 }
6698
Glenn Kastendeca2ae2014-02-07 10:25:56 -08006699 readInputParameters_l();
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006700
Andy Hungc8fddf32018-08-08 18:32:37 -07006701 // TODO: We may also match on address as well as device type for
6702 // AUDIO_DEVICE_IN_BUS, AUDIO_DEVICE_IN_BLUETOOTH_A2DP, AUDIO_DEVICE_IN_REMOTE_SUBMIX
jiabin10d86fd2019-10-31 17:20:42 -07006703 // TODO: This property should be ensure that only contains one single device type.
6704 mTimestampCorrectedDevice = (audio_devices_t)property_get_int64(
6705 "audio.timestamp.corrected_input_device",
Andy Hungc8fddf32018-08-08 18:32:37 -07006706 (int64_t)(mIsMsdDevice ? AUDIO_DEVICE_IN_BUS // turn on by default for MSD
6707 : AUDIO_DEVICE_NONE));
6708
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006709 // create an NBAIO source for the HAL input stream, and negotiate
Mikhail Naganova0c91332016-09-19 10:01:12 -07006710 mInputSource = new AudioStreamInSource(input->stream);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006711 size_t numCounterOffers = 0;
6712 const NBAIO_Format offers[1] = {Format_from_SR_C(mSampleRate, mChannelCount, mFormat)};
Glenn Kasten57c4e6f2016-03-18 14:54:07 -07006713#if !LOG_NDEBUG
6714 ssize_t index =
6715#else
6716 (void)
6717#endif
6718 mInputSource->negotiate(offers, 1, NULL, numCounterOffers);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006719 ALOG_ASSERT(index == 0);
6720
6721 // initialize fast capture depending on configuration
6722 bool initFastCapture;
6723 switch (kUseFastCapture) {
6724 case FastCapture_Never:
6725 initFastCapture = false;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006726 ALOGV("%p kUseFastCapture = Never, initFastCapture = false", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006727 break;
6728 case FastCapture_Always:
6729 initFastCapture = true;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006730 ALOGV("%p kUseFastCapture = Always, initFastCapture = true", this);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006731 break;
6732 case FastCapture_Static:
Glenn Kasteneb9487e2015-07-22 09:15:17 -07006733 initFastCapture = (mFrameCount * 1000) / mSampleRate < kMinNormalCaptureBufferSizeMs;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006734 ALOGV("%p kUseFastCapture = Static, (%lld * 1000) / %u vs %u, initFastCapture = %d",
6735 this, (long long)mFrameCount, mSampleRate, kMinNormalCaptureBufferSizeMs,
6736 initFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006737 break;
6738 // case FastCapture_Dynamic:
6739 }
6740
6741 if (initFastCapture) {
Glenn Kastend198b852015-03-16 14:55:53 -07006742 // create a Pipe for FastCapture to write to, and for us and fast tracks to read from
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006743 NBAIO_Format format = mInputSource->format();
Glenn Kasten1b291842016-07-18 14:55:21 -07006744 // quadruple-buffering of 20 ms each; this ensures we can sleep for 20ms in RecordThread
6745 size_t pipeFramesP2 = roundup(4 * FMS_20 * mSampleRate / 1000);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006746 size_t pipeSize = pipeFramesP2 * Format_frameSize(format);
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006747 void *pipeBuffer = nullptr;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006748 const sp<MemoryDealer> roHeap(readOnlyHeap());
6749 sp<IMemory> pipeMemory;
6750 if ((roHeap == 0) ||
6751 (pipeMemory = roHeap->allocate(pipeSize)) == 0 ||
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07006752 (pipeBuffer = pipeMemory->pointer()) == nullptr) {
6753 ALOGE("not enough memory for pipe buffer size=%zu; "
6754 "roHeap=%p, pipeMemory=%p, pipeBuffer=%p; roHeapSize: %lld",
6755 pipeSize, roHeap.get(), pipeMemory.get(), pipeBuffer,
6756 (long long)kRecordThreadReadOnlyHeapSize);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006757 goto failed;
6758 }
6759 // pipe will be shared directly with fast clients, so clear to avoid leaking old information
6760 memset(pipeBuffer, 0, pipeSize);
6761 Pipe *pipe = new Pipe(pipeFramesP2, format, pipeBuffer);
6762 const NBAIO_Format offers[1] = {format};
6763 size_t numCounterOffers = 0;
6764 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
6765 ALOG_ASSERT(index == 0);
6766 mPipeSink = pipe;
6767 PipeReader *pipeReader = new PipeReader(*pipe);
6768 numCounterOffers = 0;
6769 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
6770 ALOG_ASSERT(index == 0);
6771 mPipeSource = pipeReader;
6772 mPipeFramesP2 = pipeFramesP2;
6773 mPipeMemory = pipeMemory;
6774
6775 // create fast capture
6776 mFastCapture = new FastCapture();
6777 FastCaptureStateQueue *sq = mFastCapture->sq();
6778#ifdef STATE_QUEUE_DUMP
6779 // FIXME
6780#endif
6781 FastCaptureState *state = sq->begin();
6782 state->mCblk = NULL;
6783 state->mInputSource = mInputSource.get();
6784 state->mInputSourceGen++;
6785 state->mPipeSink = pipe;
6786 state->mPipeSinkGen++;
6787 state->mFrameCount = mFrameCount;
6788 state->mCommand = FastCaptureState::COLD_IDLE;
6789 // already done in constructor initialization list
6790 //mFastCaptureFutex = 0;
6791 state->mColdFutexAddr = &mFastCaptureFutex;
6792 state->mColdGen++;
6793 state->mDumpState = &mFastCaptureDumpState;
6794#ifdef TEE_SINK
6795 // FIXME
6796#endif
6797 mFastCaptureNBLogWriter = audioFlinger->newWriter_l(kFastCaptureLogSize, "FastCapture");
6798 state->mNBLogWriter = mFastCaptureNBLogWriter.get();
6799 sq->end();
6800 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6801
6802 // start the fast capture
6803 mFastCapture->run("FastCapture", ANDROID_PRIORITY_URGENT_AUDIO);
6804 pid_t tid = mFastCapture->getTid();
Andy Hung4ef19fa2018-05-15 19:35:29 -07006805 sendPrioConfigEvent(getpid(), tid, kPriorityFastCapture, false /*forApp*/);
Mikhail Naganove1c4b5d2016-12-22 09:22:45 -08006806 stream()->setHalThreadPriority(kPriorityFastCapture);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006807#ifdef AUDIO_WATCHDOG
6808 // FIXME
6809#endif
6810
Glenn Kasten6e6704c2014-07-03 10:20:00 -07006811 mFastTrackAvail = true;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006812 }
Andy Hung8946a282018-04-19 20:04:56 -07006813#ifdef TEE_SINK
6814 mTee.set(mInputSource->format(), NBAIO_Tee::TEE_FLAG_INPUT_THREAD);
6815 mTee.setId(std::string("_") + std::to_string(mId) + "_C");
6816#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006817failed: ;
6818
6819 // FIXME mNormalSource
Eric Laurent81784c32012-11-19 14:55:58 -08006820}
6821
Eric Laurent81784c32012-11-19 14:55:58 -08006822AudioFlinger::RecordThread::~RecordThread()
6823{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006824 if (mFastCapture != 0) {
6825 FastCaptureStateQueue *sq = mFastCapture->sq();
6826 FastCaptureState *state = sq->begin();
6827 if (state->mCommand == FastCaptureState::COLD_IDLE) {
6828 int32_t old = android_atomic_inc(&mFastCaptureFutex);
6829 if (old == -1) {
6830 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
6831 }
6832 }
6833 state->mCommand = FastCaptureState::EXIT;
6834 sq->end();
6835 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_PUSHED);
6836 mFastCapture->join();
6837 mFastCapture.clear();
6838 }
6839 mAudioFlinger->unregisterWriter(mFastCaptureNBLogWriter);
Glenn Kasten481fb672013-09-30 14:39:28 -07006840 mAudioFlinger->unregisterWriter(mNBLogWriter);
Andy Hung57446612015-04-19 23:56:46 -07006841 free(mRsmpInBuffer);
Eric Laurent81784c32012-11-19 14:55:58 -08006842}
6843
6844void AudioFlinger::RecordThread::onFirstRef()
6845{
Glenn Kastend7dca052015-03-05 16:05:54 -08006846 run(mThreadName, PRIORITY_URGENT_AUDIO);
Eric Laurent81784c32012-11-19 14:55:58 -08006847}
6848
Eric Laurent555530a2017-02-07 18:17:24 -08006849void AudioFlinger::RecordThread::preExit()
6850{
6851 ALOGV(" preExit()");
6852 Mutex::Autolock _l(mLock);
6853 for (size_t i = 0; i < mTracks.size(); i++) {
6854 sp<RecordTrack> track = mTracks[i];
6855 track->invalidate();
6856 }
6857 mActiveTracks.clear();
6858 mStartStopCond.broadcast();
6859}
6860
Eric Laurent81784c32012-11-19 14:55:58 -08006861bool AudioFlinger::RecordThread::threadLoop()
6862{
Eric Laurent81784c32012-11-19 14:55:58 -08006863 nsecs_t lastWarning = 0;
6864
6865 inputStandBy();
Eric Laurent81784c32012-11-19 14:55:58 -08006866
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006867reacquire_wakelock:
6868 sp<RecordTrack> activeTrack;
6869 {
6870 Mutex::Autolock _l(mLock);
Andy Hungdae27702016-10-31 14:01:16 -07006871 acquireWakeLock_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006872 }
6873
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006874 // used to request a deferred sleep, to be executed later while mutex is unlocked
6875 uint32_t sleepUs = 0;
6876
Andy Hung446f4df2019-02-21 12:26:41 -08006877 int64_t lastLoopCountRead = -2; // never matches "previous" loop, when loopCount = 0.
6878
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006879 // loop while there is work to do
Andy Hung446f4df2019-02-21 12:26:41 -08006880 for (int64_t loopCount = 0;; ++loopCount) { // loopCount used for statistics tracking
Glenn Kastenc527a7c2013-08-13 15:43:49 -07006881 Vector< sp<EffectChain> > effectChains;
Glenn Kasten2cfbf882013-08-14 13:12:11 -07006882
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006883 // activeTracks accumulates a copy of a subset of mActiveTracks
6884 Vector< sp<RecordTrack> > activeTracks;
6885
Glenn Kasten735f45f2014-08-18 15:51:59 -07006886 // reference to the (first and only) active fast track
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006887 sp<RecordTrack> fastTrack;
Eric Laurent10351942014-05-08 18:49:52 -07006888
Glenn Kasten735f45f2014-08-18 15:51:59 -07006889 // reference to a fast track which is about to be removed
6890 sp<RecordTrack> fastTrackToRemove;
6891
Eric Laurent81784c32012-11-19 14:55:58 -08006892 { // scope for mLock
6893 Mutex::Autolock _l(mLock);
Eric Laurent000a4192014-01-29 15:17:32 -08006894
Eric Laurent021cf962014-05-13 10:18:14 -07006895 processConfigEvents_l();
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006896
Eric Laurent000a4192014-01-29 15:17:32 -08006897 // check exitPending here because checkForNewParameters_l() and
6898 // checkForNewParameters_l() can temporarily release mLock
6899 if (exitPending()) {
6900 break;
6901 }
6902
Eric Laurent5c25d562016-07-13 17:17:45 -07006903 // sleep with mutex unlocked
6904 if (sleepUs > 0) {
Glenn Kastenf9715e42016-07-13 14:02:03 -07006905 ATRACE_BEGIN("sleepC");
Eric Laurent5c25d562016-07-13 17:17:45 -07006906 mWaitWorkCV.waitRelative(mLock, microseconds((nsecs_t)sleepUs));
6907 ATRACE_END();
6908 sleepUs = 0;
6909 continue;
6910 }
6911
Glenn Kasten2b806402013-11-20 16:37:38 -08006912 // if no active track(s), then standby and release wakelock
6913 size_t size = mActiveTracks.size();
6914 if (size == 0) {
Glenn Kasten93e471f2013-08-19 08:40:07 -07006915 standbyIfNotAlreadyInStandby();
Glenn Kasten4ef0b462013-08-14 13:52:27 -07006916 // exitPending() can't become true here
Eric Laurent81784c32012-11-19 14:55:58 -08006917 releaseWakeLock_l();
6918 ALOGV("RecordThread: loop stopping");
6919 // go to sleep
6920 mWaitWorkCV.wait(mLock);
6921 ALOGV("RecordThread: loop starting");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08006922 goto reacquire_wakelock;
6923 }
6924
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006925 bool doBroadcast = false;
Eric Laurent5c25d562016-07-13 17:17:45 -07006926 bool allStopped = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006927 for (size_t i = 0; i < size; ) {
Glenn Kasten9e982352013-08-14 14:39:50 -07006928
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006929 activeTrack = mActiveTracks[i];
6930 if (activeTrack->isTerminated()) {
Glenn Kasten735f45f2014-08-18 15:51:59 -07006931 if (activeTrack->isFastTrack()) {
6932 ALOG_ASSERT(fastTrackToRemove == 0);
6933 fastTrackToRemove = activeTrack;
6934 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006935 removeTrack_l(activeTrack);
Glenn Kasten2b806402013-11-20 16:37:38 -08006936 mActiveTracks.remove(activeTrack);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006937 size--;
Glenn Kasten9e982352013-08-14 14:39:50 -07006938 continue;
6939 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006940
6941 TrackBase::track_state activeTrackState = activeTrack->mState;
6942 switch (activeTrackState) {
6943
6944 case TrackBase::PAUSING:
6945 mActiveTracks.remove(activeTrack);
Andy Hungce685402018-10-05 17:23:27 -07006946 activeTrack->mState = TrackBase::PAUSED;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006947 doBroadcast = true;
6948 size--;
6949 continue;
6950
6951 case TrackBase::STARTING_1:
6952 sleepUs = 10000;
6953 i++;
Eric Laurent5c25d562016-07-13 17:17:45 -07006954 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006955 continue;
6956
6957 case TrackBase::STARTING_2:
6958 doBroadcast = true;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006959 mStandby = false;
Glenn Kasten9e982352013-08-14 14:39:50 -07006960 activeTrack->mState = TrackBase::ACTIVE;
Eric Laurent5c25d562016-07-13 17:17:45 -07006961 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006962 break;
6963
6964 case TrackBase::ACTIVE:
Eric Laurent5c25d562016-07-13 17:17:45 -07006965 allStopped = false;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006966 break;
6967
Andy Hungce685402018-10-05 17:23:27 -07006968 case TrackBase::IDLE: // cannot be on ActiveTracks if idle
6969 case TrackBase::PAUSED: // cannot be on ActiveTracks if paused
6970 case TrackBase::STOPPED: // cannot be on ActiveTracks if destroyed/terminated
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006971 default:
Andy Hungce685402018-10-05 17:23:27 -07006972 LOG_ALWAYS_FATAL("%s: Unexpected active track state:%d, id:%d, tracks:%zu",
6973 __func__, activeTrackState, activeTrack->id(), size);
Glenn Kasten9e982352013-08-14 14:39:50 -07006974 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006975
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006976 activeTracks.add(activeTrack);
6977 i++;
Glenn Kasten9e982352013-08-14 14:39:50 -07006978
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07006979 if (activeTrack->isFastTrack()) {
6980 ALOG_ASSERT(!mFastTrackAvail);
6981 ALOG_ASSERT(fastTrack == 0);
6982 fastTrack = activeTrack;
6983 }
Glenn Kasten9e982352013-08-14 14:39:50 -07006984 }
Eric Laurent5c25d562016-07-13 17:17:45 -07006985
Andy Hungdae27702016-10-31 14:01:16 -07006986 mActiveTracks.updatePowerState(this);
6987
Kevin Rocard069c2712018-03-29 19:09:14 -07006988 updateMetadata_l();
6989
Eric Laurent5c25d562016-07-13 17:17:45 -07006990 if (allStopped) {
6991 standbyIfNotAlreadyInStandby();
6992 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006993 if (doBroadcast) {
6994 mStartStopCond.broadcast();
6995 }
6996
6997 // sleep if there are no active tracks to process
Eric Tan39ec8d62018-07-24 09:49:29 -07006998 if (activeTracks.isEmpty()) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08006999 if (sleepUs == 0) {
7000 sleepUs = kRecordThreadSleepUs;
7001 }
7002 continue;
7003 }
7004 sleepUs = 0;
Glenn Kasten9e982352013-08-14 14:39:50 -07007005
Eric Laurent81784c32012-11-19 14:55:58 -08007006 lockEffectChains_l(effectChains);
7007 }
7008
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007009 // thread mutex is now unlocked, mActiveTracks unknown, activeTracks.size() > 0
Glenn Kasten71652682013-08-14 15:17:55 -07007010
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007011 size_t size = effectChains.size();
7012 for (size_t i = 0; i < size; i++) {
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007013 // thread mutex is not locked, but effect chain is locked
7014 effectChains[i]->process_l();
7015 }
7016
Glenn Kasten735f45f2014-08-18 15:51:59 -07007017 // Push a new fast capture state if fast capture is not already running, or cblk change
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007018 if (mFastCapture != 0) {
7019 FastCaptureStateQueue *sq = mFastCapture->sq();
7020 FastCaptureState *state = sq->begin();
Glenn Kasten735f45f2014-08-18 15:51:59 -07007021 bool didModify = false;
7022 FastCaptureStateQueue::block_t block = FastCaptureStateQueue::BLOCK_UNTIL_PUSHED;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007023 if (state->mCommand != FastCaptureState::READ_WRITE /* FIXME &&
7024 (kUseFastMixer != FastMixer_Dynamic || state->mTrackMask > 1)*/) {
7025 if (state->mCommand == FastCaptureState::COLD_IDLE) {
7026 int32_t old = android_atomic_inc(&mFastCaptureFutex);
7027 if (old == -1) {
7028 (void) syscall(__NR_futex, &mFastCaptureFutex, FUTEX_WAKE_PRIVATE, 1);
7029 }
7030 }
7031 state->mCommand = FastCaptureState::READ_WRITE;
7032#if 0 // FIXME
7033 mFastCaptureDumpState.increaseSamplingN(mAudioFlinger->isLowRamDevice() ?
Glenn Kastenfbdb2ac2015-03-02 14:47:19 -08007034 FastThreadDumpState::kSamplingNforLowRamDevice :
7035 FastThreadDumpState::kSamplingN);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007036#endif
Glenn Kasten735f45f2014-08-18 15:51:59 -07007037 didModify = true;
7038 }
7039 audio_track_cblk_t *cblkOld = state->mCblk;
7040 audio_track_cblk_t *cblkNew = fastTrack != 0 ? fastTrack->cblk() : NULL;
7041 if (cblkNew != cblkOld) {
7042 state->mCblk = cblkNew;
7043 // block until acked if removing a fast track
7044 if (cblkOld != NULL) {
7045 block = FastCaptureStateQueue::BLOCK_UNTIL_ACKED;
7046 }
7047 didModify = true;
7048 }
jiabin01c8f562018-07-19 17:47:28 -07007049 AudioBufferProvider* abp = (fastTrack != 0 && fastTrack->isPatchTrack()) ?
7050 reinterpret_cast<AudioBufferProvider*>(fastTrack.get()) : nullptr;
7051 if (state->mFastPatchRecordBufferProvider != abp) {
7052 state->mFastPatchRecordBufferProvider = abp;
7053 state->mFastPatchRecordFormat = fastTrack == 0 ?
7054 AUDIO_FORMAT_INVALID : fastTrack->format();
7055 didModify = true;
7056 }
Glenn Kasten735f45f2014-08-18 15:51:59 -07007057 sq->end(didModify);
7058 if (didModify) {
7059 sq->push(block);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007060#if 0
7061 if (kUseFastCapture == FastCapture_Dynamic) {
7062 mNormalSource = mPipeSource;
7063 }
7064#endif
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007065 }
7066 }
7067
Glenn Kasten735f45f2014-08-18 15:51:59 -07007068 // now run the fast track destructor with thread mutex unlocked
7069 fastTrackToRemove.clear();
7070
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007071 // Read from HAL to keep up with fastest client if multiple active tracks, not slowest one.
7072 // Only the client(s) that are too slow will overrun. But if even the fastest client is too
7073 // slow, then this RecordThread will overrun by not calling HAL read often enough.
7074 // If destination is non-contiguous, first read past the nominal end of buffer, then
7075 // copy to the right place. Permitted because mRsmpInBuffer was over-allocated.
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007076
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007077 int32_t rear = mRsmpInRear & (mRsmpInFramesP2 - 1);
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007078 ssize_t framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007079 const int64_t lastIoBeginNs = systemTime(); // start IO timing
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007080
7081 // If an NBAIO source is present, use it to read the normal capture's data
7082 if (mPipeSource != 0) {
Andy Hung156317a2018-08-02 11:49:29 -07007083 size_t framesToRead = min(mRsmpInFramesOA - rear, mRsmpInFramesP2 / 2);
Andy Hungd5b638f2018-04-30 13:56:10 -07007084
7085 // The audio fifo read() returns OVERRUN on overflow, and advances the read pointer
7086 // to the full buffer point (clearing the overflow condition). Upon OVERRUN error,
7087 // we immediately retry the read() to get data and prevent another overflow.
7088 for (int retries = 0; retries <= 2; ++retries) {
7089 ALOGW_IF(retries > 0, "overrun on read from pipe, retry #%d", retries);
7090 framesRead = mPipeSource->read((uint8_t*)mRsmpInBuffer + rear * mFrameSize,
7091 framesToRead);
7092 if (framesRead != OVERRUN) break;
7093 }
7094
Andy Hung7a3dc6b2018-05-01 16:39:51 -07007095 const ssize_t availableToRead = mPipeSource->availableToRead();
7096 if (availableToRead >= 0) {
7097 // PipeSource is the master clock. It is up to the AudioRecord client to keep up.
7098 LOG_ALWAYS_FATAL_IF((size_t)availableToRead > mPipeFramesP2,
7099 "more frames to read than fifo size, %zd > %zu",
7100 availableToRead, mPipeFramesP2);
7101 const size_t pipeFramesFree = mPipeFramesP2 - availableToRead;
7102 const size_t sleepFrames = min(pipeFramesFree, mRsmpInFramesP2) / 2;
7103 ALOGVV("mPipeFramesP2:%zu mRsmpInFramesP2:%zu sleepFrames:%zu availableToRead:%zd",
7104 mPipeFramesP2, mRsmpInFramesP2, sleepFrames, availableToRead);
Glenn Kasten1b291842016-07-18 14:55:21 -07007105 sleepUs = (sleepFrames * 1000000LL) / mSampleRate;
7106 }
7107 if (framesRead < 0) {
7108 status_t status = (status_t) framesRead;
7109 switch (status) {
7110 case OVERRUN:
7111 ALOGW("overrun on read from pipe");
7112 framesRead = 0;
7113 break;
7114 case NEGOTIATE:
7115 ALOGE("re-negotiation is needed");
7116 framesRead = -1; // Will cause an attempt to recover.
7117 break;
7118 default:
7119 ALOGE("unknown error %d on read from pipe", status);
7120 break;
7121 }
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007122 }
7123 // otherwise use the HAL / AudioStreamIn directly
7124 } else {
Glenn Kastenec6a7032016-03-14 07:40:23 -07007125 ATRACE_BEGIN("read");
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007126 size_t bytesRead;
Mikhail Naganovaf288872019-09-25 13:05:02 -07007127 status_t result = mSource->read(
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007128 (uint8_t*)mRsmpInBuffer + rear * mFrameSize, mBufferSize, &bytesRead);
Glenn Kastenec6a7032016-03-14 07:40:23 -07007129 ATRACE_END();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007130 if (result < 0) {
7131 framesRead = result;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007132 } else {
7133 framesRead = bytesRead / mFrameSize;
7134 }
7135 }
7136
Andy Hung446f4df2019-02-21 12:26:41 -08007137 const int64_t lastIoEndNs = systemTime(); // end IO timing
7138
Andy Hung3f0c9022016-01-15 17:49:46 -08007139 // Update server timestamp with server stats
7140 // systemTime() is optional if the hardware supports timestamps.
7141 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += framesRead;
Andy Hung446f4df2019-02-21 12:26:41 -08007142 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = lastIoEndNs;
Andy Hung3f0c9022016-01-15 17:49:46 -08007143
7144 // Update server timestamp with kernel stats
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007145 if (mPipeSource.get() == nullptr /* don't obtain for FastCapture, could block */) {
Andy Hung3f0c9022016-01-15 17:49:46 -08007146 int64_t position, time;
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007147 if (mStandby) {
7148 mTimestampVerifier.discontinuity();
Mikhail Naganovaf288872019-09-25 13:05:02 -07007149 } else if (mSource->getCapturePosition(&position, &time) == NO_ERROR
Andy Hungc8fddf32018-08-08 18:32:37 -07007150 && time > mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL]) {
7151
7152 mTimestampVerifier.add(position, time, mSampleRate);
7153
7154 // Correct timestamps
7155 if (isTimestampCorrectionEnabled()) {
7156 ALOGV("TS_BEFORE: %d %lld %lld",
7157 id(), (long long)time, (long long)position);
7158 auto correctedTimestamp = mTimestampVerifier.getLastCorrectedTimestamp();
7159 position = correctedTimestamp.mFrames;
7160 time = correctedTimestamp.mTimeNs;
7161 ALOGV("TS_AFTER: %d %lld %lld",
7162 id(), (long long)time, (long long)position);
7163 }
7164
Andy Hung3f0c9022016-01-15 17:49:46 -08007165 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = position;
7166 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = time;
7167 // Note: In general record buffers should tend to be empty in
7168 // a properly running pipeline.
7169 //
7170 // Also, it is not advantageous to call get_presentation_position during the read
7171 // as the read obtains a lock, preventing the timestamp call from executing.
Andy Hung2e2c0bb2018-06-11 19:13:11 -07007172 } else {
7173 mTimestampVerifier.error();
Andy Hung3f0c9022016-01-15 17:49:46 -08007174 }
7175 }
Andy Hunge6c37112019-02-26 17:38:10 -08007176
7177 // From the timestamp, input read latency is negative output write latency.
7178 const audio_input_flags_t flags = mInput != NULL ? mInput->flags : AUDIO_INPUT_FLAG_NONE;
7179 const double latencyMs = RecordTrack::checkServerLatencySupported(mFormat, flags)
7180 ? - mTimestamp.getOutputServerLatencyMs(mSampleRate) : 0.;
7181 if (latencyMs != 0.) { // note 0. means timestamp is empty.
7182 mLatencyMs.add(latencyMs);
7183 }
7184
Andy Hung3f0c9022016-01-15 17:49:46 -08007185 // Use this to track timestamp information
7186 // ALOGD("%s", mTimestamp.toString().c_str());
7187
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007188 if (framesRead < 0 || (framesRead == 0 && mPipeSource == 0)) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007189 ALOGE("read failed: framesRead=%zd", framesRead);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007190 // Force input into standby so that it tries to recover at next read attempt
7191 inputStandBy();
7192 sleepUs = kRecordThreadSleepUs;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007193 }
7194 if (framesRead <= 0) {
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007195 goto unlock;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007196 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007197 ALOG_ASSERT(framesRead > 0);
Andy Hung6427e442018-08-09 12:51:02 -07007198 mFramesRead += framesRead;
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007199
Andy Hung8946a282018-04-19 20:04:56 -07007200#ifdef TEE_SINK
7201 (void)mTee.write((uint8_t*)mRsmpInBuffer + rear * mFrameSize, framesRead);
7202#endif
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007203 // If destination is non-contiguous, we now correct for reading past end of buffer.
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007204 {
7205 size_t part1 = mRsmpInFramesP2 - rear;
7206 if ((size_t) framesRead > part1) {
Andy Hung57446612015-04-19 23:56:46 -07007207 memcpy(mRsmpInBuffer, (uint8_t*)mRsmpInBuffer + mRsmpInFramesP2 * mFrameSize,
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007208 (framesRead - part1) * mFrameSize);
7209 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007210 }
7211 rear = mRsmpInRear += framesRead;
7212
7213 size = activeTracks.size();
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007214
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007215 // loop over each active track
7216 for (size_t i = 0; i < size; i++) {
7217 activeTrack = activeTracks[i];
7218
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007219 // skip fast tracks, as those are handled directly by FastCapture
7220 if (activeTrack->isFastTrack()) {
7221 continue;
7222 }
7223
Andy Hung73c02e42015-03-29 01:13:58 -07007224 // TODO: This code probably should be moved to RecordTrack.
Andy Hung97a893e2015-03-29 01:03:07 -07007225 // TODO: Update the activeTrack buffer converter in case of reconfigure.
7226
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007227 enum {
7228 OVERRUN_UNKNOWN,
7229 OVERRUN_TRUE,
7230 OVERRUN_FALSE
7231 } overrun = OVERRUN_UNKNOWN;
7232
7233 // loop over getNextBuffer to handle circular sink
7234 for (;;) {
7235
7236 activeTrack->mSink.frameCount = ~0;
7237 status_t status = activeTrack->getNextBuffer(&activeTrack->mSink);
7238 size_t framesOut = activeTrack->mSink.frameCount;
7239 LOG_ALWAYS_FATAL_IF((status == OK) != (framesOut > 0));
7240
Andy Hung73c02e42015-03-29 01:13:58 -07007241 // check available frames and handle overrun conditions
7242 // if the record track isn't draining fast enough.
7243 bool hasOverrun;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007244 size_t framesIn;
Andy Hung73c02e42015-03-29 01:13:58 -07007245 activeTrack->mResamplerBufferProvider->sync(&framesIn, &hasOverrun);
7246 if (hasOverrun) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007247 overrun = OVERRUN_TRUE;
7248 }
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007249 if (framesOut == 0 || framesIn == 0) {
7250 break;
7251 }
7252
Andy Hung6770c6f2015-04-07 13:43:36 -07007253 // Don't allow framesOut to be larger than what is possible with resampling
7254 // from framesIn.
7255 // This isn't strictly necessary but helps limit buffer resizing in
7256 // RecordBufferConverter. TODO: remove when no longer needed.
7257 framesOut = min(framesOut,
7258 destinationFramesPossible(
7259 framesIn, mSampleRate, activeTrack->mSampleRate));
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007260
7261 if (activeTrack->isDirect()) {
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007262 // No RecordBufferConverter used for direct streams. Pass
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007263 // straight from RecordThread buffer to RecordTrack buffer.
7264 AudioBufferProvider::Buffer buffer;
7265 buffer.frameCount = framesOut;
7266 status_t status = activeTrack->mResamplerBufferProvider->getNextBuffer(&buffer);
7267 if (status == OK && buffer.frameCount != 0) {
7268 ALOGV_IF(buffer.frameCount != framesOut,
7269 "%s() read less than expected (%zu vs %zu)",
7270 __func__, buffer.frameCount, framesOut);
7271 framesOut = buffer.frameCount;
Daniel Van Veen9e2376e2018-09-27 14:37:58 +10007272 memcpy(activeTrack->mSink.raw, buffer.raw, buffer.frameCount * mFrameSize);
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007273 activeTrack->mResamplerBufferProvider->releaseBuffer(&buffer);
7274 } else {
7275 framesOut = 0;
7276 ALOGE("%s() cannot fill request, status: %d, frameCount: %zu",
7277 __func__, status, buffer.frameCount);
7278 }
7279 } else {
7280 // process frames from the RecordThread buffer provider to the RecordTrack
7281 // buffer
7282 framesOut = activeTrack->mRecordBufferConverter->convert(
7283 activeTrack->mSink.raw,
7284 activeTrack->mResamplerBufferProvider,
7285 framesOut);
7286 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007287
7288 if (framesOut > 0 && (overrun == OVERRUN_UNKNOWN)) {
7289 overrun = OVERRUN_FALSE;
7290 }
7291
7292 if (activeTrack->mFramesToDrop == 0) {
7293 if (framesOut > 0) {
7294 activeTrack->mSink.frameCount = framesOut;
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007295 // Sanitize before releasing if the track has no access to the source data
7296 // An idle UID receives silence from non virtual devices until active
7297 if (activeTrack->isSilenced()) {
Jean-Michel Trivib0de5692019-08-20 15:42:04 -07007298 memset(activeTrack->mSink.raw, 0, framesOut * activeTrack->frameSize());
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007299 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007300 activeTrack->releaseBuffer(&activeTrack->mSink);
7301 }
7302 } else {
7303 // FIXME could do a partial drop of framesOut
7304 if (activeTrack->mFramesToDrop > 0) {
Mikhail Naganov6d91ba52019-03-26 14:35:28 -07007305 activeTrack->mFramesToDrop -= (ssize_t)framesOut;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007306 if (activeTrack->mFramesToDrop <= 0) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007307 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007308 }
7309 } else {
7310 activeTrack->mFramesToDrop += framesOut;
7311 if (activeTrack->mFramesToDrop >= 0 || activeTrack->mSyncStartEvent == 0 ||
7312 activeTrack->mSyncStartEvent->isCancelled()) {
7313 ALOGW("Synced record %s, session %d, trigger session %d",
7314 (activeTrack->mFramesToDrop >= 0) ? "timed out" : "cancelled",
7315 activeTrack->sessionId(),
7316 (activeTrack->mSyncStartEvent != 0) ?
Glenn Kastend848eb42016-03-08 13:42:11 -08007317 activeTrack->mSyncStartEvent->triggerSession() :
7318 AUDIO_SESSION_NONE);
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007319 activeTrack->clearSyncStartEvent();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007320 }
7321 }
7322 }
7323
7324 if (framesOut == 0) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007325 break;
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007326 }
7327 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007328
7329 switch (overrun) {
7330 case OVERRUN_TRUE:
7331 // client isn't retrieving buffers fast enough
7332 if (!activeTrack->setOverflow()) {
7333 nsecs_t now = systemTime();
7334 // FIXME should lastWarning per track?
7335 if ((now - lastWarning) > kWarningThrottleNs) {
7336 ALOGW("RecordThread: buffer overflow");
7337 lastWarning = now;
7338 }
7339 }
7340 break;
7341 case OVERRUN_FALSE:
7342 activeTrack->clearOverflow();
7343 break;
7344 case OVERRUN_UNKNOWN:
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007345 break;
7346 }
7347
Andy Hung3f0c9022016-01-15 17:49:46 -08007348 // update frame information and push timestamp out
7349 activeTrack->updateTrackFrameInfo(
Andy Hung6ae58432016-02-16 18:32:24 -08007350 activeTrack->mServerProxy->framesReleased(),
Andy Hung3f0c9022016-01-15 17:49:46 -08007351 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER],
7352 mSampleRate, mTimestamp);
Glenn Kasten1ba19cd2013-08-14 14:02:21 -07007353 }
7354
Glenn Kasten3d61bc12014-06-16 10:25:20 -07007355unlock:
Eric Laurent81784c32012-11-19 14:55:58 -08007356 // enable changes in effect chain
7357 unlockEffectChains(effectChains);
Glenn Kastenc527a7c2013-08-13 15:43:49 -07007358 // effectChains doesn't need to be cleared, since it is cleared by destructor at scope end
Eric Laurentcccbc762019-04-05 14:20:05 -07007359 if (audio_has_proportional_frames(mFormat)
7360 && loopCount == lastLoopCountRead + 1) {
7361 const int64_t readPeriodNs = lastIoEndNs - mLastIoEndNs;
7362 const double jitterMs =
7363 TimestampVerifier<int64_t, int64_t>::computeJitterMs(
7364 {framesRead, readPeriodNs},
7365 {0, 0} /* lastTimestamp */, mSampleRate);
7366 const double processMs = (lastIoBeginNs - mLastIoEndNs) * 1e-6;
7367
7368 Mutex::Autolock _l(mLock);
7369 mIoJitterMs.add(jitterMs);
7370 mProcessTimeMs.add(processMs);
7371 }
7372 // update timing info.
7373 mLastIoBeginNs = lastIoBeginNs;
7374 mLastIoEndNs = lastIoEndNs;
7375 lastLoopCountRead = loopCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007376 }
7377
Glenn Kasten93e471f2013-08-19 08:40:07 -07007378 standbyIfNotAlreadyInStandby();
Eric Laurent81784c32012-11-19 14:55:58 -08007379
7380 {
7381 Mutex::Autolock _l(mLock);
Eric Laurent9a54bc22013-09-09 09:08:44 -07007382 for (size_t i = 0; i < mTracks.size(); i++) {
7383 sp<RecordTrack> track = mTracks[i];
7384 track->invalidate();
7385 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007386 mActiveTracks.clear();
Eric Laurent81784c32012-11-19 14:55:58 -08007387 mStartStopCond.broadcast();
7388 }
7389
7390 releaseWakeLock();
7391
7392 ALOGV("RecordThread %p exiting", this);
7393 return false;
7394}
7395
Glenn Kasten93e471f2013-08-19 08:40:07 -07007396void AudioFlinger::RecordThread::standbyIfNotAlreadyInStandby()
Eric Laurent81784c32012-11-19 14:55:58 -08007397{
7398 if (!mStandby) {
7399 inputStandBy();
7400 mStandby = true;
7401 }
7402}
7403
7404void AudioFlinger::RecordThread::inputStandBy()
7405{
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007406 // Idle the fast capture if it's currently running
7407 if (mFastCapture != 0) {
7408 FastCaptureStateQueue *sq = mFastCapture->sq();
7409 FastCaptureState *state = sq->begin();
7410 if (!(state->mCommand & FastCaptureState::IDLE)) {
7411 state->mCommand = FastCaptureState::COLD_IDLE;
7412 state->mColdFutexAddr = &mFastCaptureFutex;
7413 state->mColdGen++;
7414 mFastCaptureFutex = 0;
7415 sq->end();
7416 // BLOCK_UNTIL_PUSHED would be insufficient, as we need it to stop doing I/O now
7417 sq->push(FastCaptureStateQueue::BLOCK_UNTIL_ACKED);
7418#if 0
7419 if (kUseFastCapture == FastCapture_Dynamic) {
7420 // FIXME
7421 }
7422#endif
7423#ifdef AUDIO_WATCHDOG
7424 // FIXME
7425#endif
7426 } else {
7427 sq->end(false /*didModify*/);
7428 }
7429 }
Mikhail Naganovaf288872019-09-25 13:05:02 -07007430 status_t result = mSource->standby();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07007431 ALOGE_IF(result != OK, "Error when putting input stream into standby: %d", result);
Andy Hungad6d52d2016-07-18 13:42:03 -07007432
7433 // If going into standby, flush the pipe source.
7434 if (mPipeSource.get() != nullptr) {
7435 const ssize_t flushed = mPipeSource->flush();
7436 if (flushed > 0) {
7437 ALOGV("Input standby flushed PipeSource %zd frames", flushed);
7438 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] += flushed;
7439 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] = systemTime();
7440 }
7441 }
Eric Laurent81784c32012-11-19 14:55:58 -08007442}
7443
Glenn Kasten05997e22014-03-13 15:08:33 -07007444// RecordThread::createRecordTrack_l() must be called with AudioFlinger::mLock held
Glenn Kastene198c362013-08-13 09:13:36 -07007445sp<AudioFlinger::RecordThread::RecordTrack> AudioFlinger::RecordThread::createRecordTrack_l(
Eric Laurent81784c32012-11-19 14:55:58 -08007446 const sp<AudioFlinger::Client>& client,
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007447 const audio_attributes_t& attr,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007448 uint32_t *pSampleRate,
Eric Laurent81784c32012-11-19 14:55:58 -08007449 audio_format_t format,
7450 audio_channel_mask_t channelMask,
Glenn Kasten74935e42013-12-19 08:56:45 -08007451 size_t *pFrameCount,
Glenn Kastend848eb42016-03-08 13:42:11 -08007452 audio_session_t sessionId,
Eric Laurentf14db3c2017-12-08 14:20:36 -08007453 size_t *pNotificationFrameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07007454 pid_t creatorPid,
Andy Hung1f12a8a2016-11-07 16:10:30 -08007455 uid_t uid,
Eric Laurent05067782016-06-01 18:27:28 -07007456 audio_input_flags_t *flags,
Eric Laurent81784c32012-11-19 14:55:58 -08007457 pid_t tid,
Eric Laurent20b9ef02016-12-05 11:03:16 -08007458 status_t *status,
Jean-Michel Trivib0de5692019-08-20 15:42:04 -07007459 audio_port_handle_t portId,
7460 const String16& opPackageName)
Eric Laurent81784c32012-11-19 14:55:58 -08007461{
Glenn Kasten74935e42013-12-19 08:56:45 -08007462 size_t frameCount = *pFrameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007463 size_t notificationFrameCount = *pNotificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007464 sp<RecordTrack> track;
7465 status_t lStatus;
Eric Laurent05067782016-06-01 18:27:28 -07007466 audio_input_flags_t inputFlags = mInput->flags;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007467 audio_input_flags_t requestedFlags = *flags;
7468 uint32_t sampleRate;
7469
7470 lStatus = initCheck();
7471 if (lStatus != NO_ERROR) {
7472 ALOGE("createRecordTrack_l() audio driver not initialized");
7473 goto Exit;
7474 }
7475
Mikhail Naganovce9f2652018-07-16 11:09:24 -07007476 if (!audio_is_linear_pcm(mFormat) && (*flags & AUDIO_INPUT_FLAG_DIRECT) == 0) {
7477 ALOGE("createRecordTrack_l() on an encoded stream requires AUDIO_INPUT_FLAG_DIRECT");
7478 lStatus = BAD_VALUE;
7479 goto Exit;
7480 }
7481
Eric Laurentf14db3c2017-12-08 14:20:36 -08007482 if (*pSampleRate == 0) {
7483 *pSampleRate = mSampleRate;
7484 }
7485 sampleRate = *pSampleRate;
Eric Laurent05067782016-06-01 18:27:28 -07007486
7487 // special case for FAST flag considered OK if fast capture is present
7488 if (hasFastCapture()) {
7489 inputFlags = (audio_input_flags_t)(inputFlags | AUDIO_INPUT_FLAG_FAST);
7490 }
7491
Eric Laurentf14db3c2017-12-08 14:20:36 -08007492 // Check if requested flags are compatible with input stream flags
Eric Laurent05067782016-06-01 18:27:28 -07007493 if ((*flags & inputFlags) != *flags) {
7494 ALOGW("createRecordTrack_l(): mismatch between requested flags (%08x) and"
7495 " input flags (%08x)",
7496 *flags, inputFlags);
7497 *flags = (audio_input_flags_t)(*flags & inputFlags);
7498 }
Eric Laurent81784c32012-11-19 14:55:58 -08007499
Glenn Kasten90e58b12013-07-31 16:16:02 -07007500 // client expresses a preference for FAST, but we get the final say
Eric Laurent05067782016-06-01 18:27:28 -07007501 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007502 if (
Glenn Kastenb7fbf7e2015-03-18 12:57:28 -07007503 // we formerly checked for a callback handler (non-0 tid),
7504 // but that is no longer required for TRANSFER_OBTAIN mode
7505 //
Phil Burk7ed66a12019-04-18 13:20:30 -07007506 // Frame count is not specified (0), or is less than or equal the pipe depth.
7507 // It is OK to provide a higher capacity than requested.
7508 // We will force it to mPipeFramesP2 below.
7509 (frameCount <= mPipeFramesP2) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007510 // PCM data
7511 audio_is_linear_pcm(format) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007512 // hardware format
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007513 (format == mFormat) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007514 // hardware channel mask
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007515 (channelMask == mChannelMask) &&
Glenn Kasten7fd04222016-02-02 12:38:16 -08007516 // hardware sample rate
Glenn Kasten90e58b12013-07-31 16:16:02 -07007517 (sampleRate == mSampleRate) &&
Glenn Kasten3a6c90a2014-03-13 15:07:51 -07007518 // record thread has an associated fast capture
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007519 hasFastCapture() &&
7520 // there are sufficient fast track slots available
7521 mFastTrackAvail
Glenn Kasten90e58b12013-07-31 16:16:02 -07007522 ) {
Eric Laurent4c415062016-06-17 16:14:16 -07007523 // check compatibility with audio effects.
7524 Mutex::Autolock _l(mLock);
7525 // Do not accept FAST flag if the session has software effects
7526 sp<EffectChain> chain = getEffectChain_l(sessionId);
7527 if (chain != 0) {
Andy Hungd3bb0ad2016-10-11 17:16:43 -07007528 audio_input_flags_t old = *flags;
7529 chain->checkInputFlagCompatibility(flags);
7530 if (old != *flags) {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007531 ALOGV("%p AUDIO_INPUT_FLAGS denied by effect old=%#x new=%#x",
7532 this, (int)old, (int)*flags);
Eric Laurent4c415062016-06-17 16:14:16 -07007533 }
7534 }
Eric Laurent122f7e72016-06-29 11:53:29 -07007535 ALOGV_IF((*flags & AUDIO_INPUT_FLAG_FAST) != 0,
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007536 "%p AUDIO_INPUT_FLAG_FAST accepted: frameCount=%zu mFrameCount=%zu",
7537 this, frameCount, mFrameCount);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007538 } else {
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007539 ALOGV("%p AUDIO_INPUT_FLAG_FAST denied: frameCount=%zu mFrameCount=%zu mPipeFramesP2=%zu "
7540 "format=%#x isLinear=%d mFormat=%#x channelMask=%#x sampleRate=%u mSampleRate=%u "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007541 "hasFastCapture=%d tid=%d mFastTrackAvail=%d",
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07007542 this, frameCount, mFrameCount, mPipeFramesP2,
7543 format, audio_is_linear_pcm(format), mFormat, channelMask, sampleRate, mSampleRate,
Glenn Kasten74105912014-07-03 12:28:53 -07007544 hasFastCapture(), tid, mFastTrackAvail);
Eric Laurent05067782016-06-01 18:27:28 -07007545 *flags = (audio_input_flags_t)(*flags & ~AUDIO_INPUT_FLAG_FAST);
Glenn Kasten74105912014-07-03 12:28:53 -07007546 }
7547 }
7548
Eric Laurentf14db3c2017-12-08 14:20:36 -08007549 // If FAST or RAW flags were corrected, ask caller to request new input from audio policy
7550 if ((*flags & AUDIO_INPUT_FLAG_FAST) !=
7551 (requestedFlags & AUDIO_INPUT_FLAG_FAST)) {
7552 *flags = (audio_input_flags_t) (*flags & ~(AUDIO_INPUT_FLAG_FAST | AUDIO_INPUT_FLAG_RAW));
7553 lStatus = BAD_TYPE;
7554 goto Exit;
7555 }
7556
Glenn Kasten74105912014-07-03 12:28:53 -07007557 // compute track buffer size in frames, and suggest the notification frame count
Eric Laurent05067782016-06-01 18:27:28 -07007558 if (*flags & AUDIO_INPUT_FLAG_FAST) {
Glenn Kasten74105912014-07-03 12:28:53 -07007559 // fast track: frame count is exactly the pipe depth
7560 frameCount = mPipeFramesP2;
7561 // ignore requested notificationFrames, and always notify exactly once every HAL buffer
Eric Laurentf14db3c2017-12-08 14:20:36 -08007562 notificationFrameCount = mFrameCount;
Glenn Kasten74105912014-07-03 12:28:53 -07007563 } else {
Glenn Kasten49d00ad2014-07-21 11:22:03 -07007564 // not fast track: max notification period is resampled equivalent of one HAL buffer time
7565 // or 20 ms if there is a fast capture
7566 // TODO This could be a roundupRatio inline, and const
7567 size_t maxNotificationFrames = ((int64_t) (hasFastCapture() ? mSampleRate/50 : mFrameCount)
7568 * sampleRate + mSampleRate - 1) / mSampleRate;
7569 // minimum number of notification periods is at least kMinNotifications,
7570 // and at least kMinMs rounded up to a whole notification period (minNotificationsByMs)
7571 static const size_t kMinNotifications = 3;
7572 static const uint32_t kMinMs = 30;
7573 // TODO This could be a roundupRatio inline
7574 const size_t minFramesByMs = (sampleRate * kMinMs + 1000 - 1) / 1000;
7575 // TODO This could be a roundupRatio inline
7576 const size_t minNotificationsByMs = (minFramesByMs + maxNotificationFrames - 1) /
7577 maxNotificationFrames;
7578 const size_t minFrameCount = maxNotificationFrames *
7579 max(kMinNotifications, minNotificationsByMs);
7580 frameCount = max(frameCount, minFrameCount);
Eric Laurentf14db3c2017-12-08 14:20:36 -08007581 if (notificationFrameCount == 0 || notificationFrameCount > maxNotificationFrames) {
7582 notificationFrameCount = maxNotificationFrames;
Glenn Kasten74105912014-07-03 12:28:53 -07007583 }
Glenn Kasten90e58b12013-07-31 16:16:02 -07007584 }
Glenn Kasten74935e42013-12-19 08:56:45 -08007585 *pFrameCount = frameCount;
Eric Laurentf14db3c2017-12-08 14:20:36 -08007586 *pNotificationFrameCount = notificationFrameCount;
Eric Laurent81784c32012-11-19 14:55:58 -08007587
7588 { // scope for mLock
7589 Mutex::Autolock _l(mLock);
7590
Kevin Rocard1f564ac2018-03-29 13:53:10 -07007591 track = new RecordTrack(this, client, attr, sampleRate,
Andy Hung8fe68032017-06-05 16:17:51 -07007592 format, channelMask, frameCount,
Eric Laurent09f1ed22019-04-24 17:45:17 -07007593 nullptr /* buffer */, (size_t)0 /* bufferSize */, sessionId, creatorPid, uid,
Jean-Michel Trivib0de5692019-08-20 15:42:04 -07007594 *flags, TrackBase::TYPE_DEFAULT, opPackageName, portId);
Eric Laurent81784c32012-11-19 14:55:58 -08007595
Glenn Kasten03003332013-08-06 15:40:54 -07007596 lStatus = track->initCheck();
7597 if (lStatus != NO_ERROR) {
Glenn Kasten35295072013-10-07 09:27:06 -07007598 ALOGE("createRecordTrack_l() initCheck failed %d; no control block?", lStatus);
Haynes Mathew George03e9e832013-12-13 15:40:13 -08007599 // track must be cleared from the caller as the caller has the AF lock
Eric Laurent81784c32012-11-19 14:55:58 -08007600 goto Exit;
7601 }
7602 mTracks.add(track);
7603
Eric Laurent05067782016-06-01 18:27:28 -07007604 if ((*flags & AUDIO_INPUT_FLAG_FAST) && (tid != -1)) {
Glenn Kasten90e58b12013-07-31 16:16:02 -07007605 pid_t callingPid = IPCThreadState::self()->getCallingPid();
7606 // we don't have CAP_SYS_NICE, nor do we want to have it as it's too powerful,
7607 // so ask activity manager to do this on our behalf
Glenn Kastenaf9a7b52017-03-29 11:29:39 -07007608 sendPrioConfigEvent_l(callingPid, tid, kPriorityAudioApp, true /*forApp*/);
Glenn Kasten90e58b12013-07-31 16:16:02 -07007609 }
Eric Laurent81784c32012-11-19 14:55:58 -08007610 }
Glenn Kasten05997e22014-03-13 15:08:33 -07007611
Eric Laurent81784c32012-11-19 14:55:58 -08007612 lStatus = NO_ERROR;
7613
7614Exit:
Glenn Kasten9156ef32013-08-06 15:39:08 -07007615 *status = lStatus;
Eric Laurent81784c32012-11-19 14:55:58 -08007616 return track;
7617}
7618
7619status_t AudioFlinger::RecordThread::start(RecordThread::RecordTrack* recordTrack,
7620 AudioSystem::sync_event_t event,
Glenn Kastend848eb42016-03-08 13:42:11 -08007621 audio_session_t triggerSession)
Eric Laurent81784c32012-11-19 14:55:58 -08007622{
7623 ALOGV("RecordThread::start event %d, triggerSession %d", event, triggerSession);
7624 sp<ThreadBase> strongMe = this;
7625 status_t status = NO_ERROR;
7626
7627 if (event == AudioSystem::SYNC_EVENT_NONE) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007628 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007629 } else if (event != AudioSystem::SYNC_EVENT_SAME) {
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007630 recordTrack->mSyncStartEvent = mAudioFlinger->createSyncEvent(event,
Eric Laurent81784c32012-11-19 14:55:58 -08007631 triggerSession,
7632 recordTrack->sessionId(),
7633 syncStartEventCallback,
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007634 recordTrack);
Eric Laurent81784c32012-11-19 14:55:58 -08007635 // Sync event can be cancelled by the trigger session if the track is not in a
7636 // compatible state in which case we start record immediately
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007637 if (recordTrack->mSyncStartEvent->isCancelled()) {
Glenn Kasten25f4aa82014-02-07 10:50:43 -08007638 recordTrack->clearSyncStartEvent();
Eric Laurent81784c32012-11-19 14:55:58 -08007639 } else {
7640 // do not wait for the event for more than AudioSystem::kSyncRecordStartTimeOutMs
Ivan Lozano1b35dd62017-12-06 16:55:10 -08007641 recordTrack->mFramesToDrop = -(ssize_t)
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007642 ((AudioSystem::kSyncRecordStartTimeOutMs * recordTrack->mSampleRate) / 1000);
Eric Laurent81784c32012-11-19 14:55:58 -08007643 }
7644 }
7645
7646 {
Glenn Kasten47c20702013-08-13 15:37:35 -07007647 // This section is a rendezvous between binder thread executing start() and RecordThread
Eric Laurent81784c32012-11-19 14:55:58 -08007648 AutoMutex lock(mLock);
Andy Hungce685402018-10-05 17:23:27 -07007649 if (recordTrack->isInvalid()) {
7650 recordTrack->clearSyncStartEvent();
7651 return INVALID_OPERATION;
7652 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007653 if (mActiveTracks.indexOf(recordTrack) >= 0) {
7654 if (recordTrack->mState == TrackBase::PAUSING) {
Andy Hungce685402018-10-05 17:23:27 -07007655 // We haven't stopped yet (moved to PAUSED and not in mActiveTracks)
7656 // so no need to startInput().
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007657 ALOGV("active record track PAUSING -> ACTIVE");
Glenn Kastenf10ffec2013-11-20 16:40:08 -08007658 recordTrack->mState = TrackBase::ACTIVE;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007659 } else {
7660 ALOGV("active record track state %d", recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007661 }
7662 return status;
7663 }
7664
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08007665 // TODO consider other ways of handling this, such as changing the state to :STARTING and
7666 // adding the track to mActiveTracks after returning from AudioSystem::startInput(),
7667 // or using a separate command thread
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007668 recordTrack->mState = TrackBase::STARTING_1;
Glenn Kasten2b806402013-11-20 16:37:38 -08007669 mActiveTracks.add(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007670 status_t status = NO_ERROR;
7671 if (recordTrack->isExternalTrack()) {
7672 mLock.unlock();
Eric Laurent4eb58f12018-12-07 16:41:02 -08007673 status = AudioSystem::startInput(recordTrack->portId());
Eric Laurent83b88082014-06-20 18:31:16 -07007674 mLock.lock();
Andy Hungce685402018-10-05 17:23:27 -07007675 if (recordTrack->isInvalid()) {
7676 recordTrack->clearSyncStartEvent();
7677 if (status == NO_ERROR && recordTrack->mState == TrackBase::STARTING_1) {
7678 recordTrack->mState = TrackBase::STARTING_2;
7679 // STARTING_2 forces destroy to call stopInput.
7680 }
7681 return INVALID_OPERATION;
7682 }
7683 if (recordTrack->mState != TrackBase::STARTING_1) {
7684 ALOGW("%s(%d): unsynchronized mState:%d change",
7685 __func__, recordTrack->id(), recordTrack->mState);
7686 // Someone else has changed state, let them take over,
7687 // leave mState in the new state.
7688 recordTrack->clearSyncStartEvent();
7689 return INVALID_OPERATION;
7690 }
7691 // we're ok, but perhaps startInput has failed
Eric Laurent83b88082014-06-20 18:31:16 -07007692 if (status != NO_ERROR) {
Andy Hungce685402018-10-05 17:23:27 -07007693 ALOGW("%s(%d): startInput failed, status %d",
7694 __func__, recordTrack->id(), status);
7695 // We are in ActiveTracks if STARTING_1 and valid, so remove from ActiveTracks,
7696 // leave in STARTING_1, so destroy() will not call stopInput.
Eric Laurent83b88082014-06-20 18:31:16 -07007697 mActiveTracks.remove(recordTrack);
Eric Laurent83b88082014-06-20 18:31:16 -07007698 recordTrack->clearSyncStartEvent();
Eric Laurent83b88082014-06-20 18:31:16 -07007699 return status;
7700 }
Eric Laurent09f1ed22019-04-24 17:45:17 -07007701 sendIoConfigEvent_l(
7702 AUDIO_CLIENT_STARTED, recordTrack->creatorPid(), recordTrack->portId());
Eric Laurent81784c32012-11-19 14:55:58 -08007703 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007704 // Catch up with current buffer indices if thread is already running.
7705 // This is what makes a new client discard all buffered data. If the track's mRsmpInFront
7706 // was initialized to some value closer to the thread's mRsmpInFront, then the track could
7707 // see previously buffered data before it called start(), but with greater risk of overrun.
7708
Andy Hung73c02e42015-03-29 01:13:58 -07007709 recordTrack->mResamplerBufferProvider->reset();
Mikhail Naganov7c6ae982018-06-14 12:33:38 -07007710 if (!recordTrack->isDirect()) {
7711 // clear any converter state as new data will be discontinuous
7712 recordTrack->mRecordBufferConverter->reset();
7713 }
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007714 recordTrack->mState = TrackBase::STARTING_2;
Eric Laurent81784c32012-11-19 14:55:58 -08007715 // signal thread to start
Eric Laurent81784c32012-11-19 14:55:58 -08007716 mWaitWorkCV.broadcast();
Eric Laurent81784c32012-11-19 14:55:58 -08007717 return status;
7718 }
Eric Laurent81784c32012-11-19 14:55:58 -08007719}
7720
Eric Laurent81784c32012-11-19 14:55:58 -08007721void AudioFlinger::RecordThread::syncStartEventCallback(const wp<SyncEvent>& event)
7722{
7723 sp<SyncEvent> strongEvent = event.promote();
7724
7725 if (strongEvent != 0) {
Eric Laurent8ea16e42014-02-20 16:26:11 -08007726 sp<RefBase> ptr = strongEvent->cookie().promote();
7727 if (ptr != 0) {
7728 RecordTrack *recordTrack = (RecordTrack *)ptr.get();
7729 recordTrack->handleSyncStartEvent(strongEvent);
7730 }
Eric Laurent81784c32012-11-19 14:55:58 -08007731 }
7732}
7733
Glenn Kastena8356f62013-07-25 14:37:52 -07007734bool AudioFlinger::RecordThread::stop(RecordThread::RecordTrack* recordTrack) {
Eric Laurent81784c32012-11-19 14:55:58 -08007735 ALOGV("RecordThread::stop");
Glenn Kastena8356f62013-07-25 14:37:52 -07007736 AutoMutex _l(mLock);
Andy Hungce685402018-10-05 17:23:27 -07007737 // if we're invalid, we can't be on the ActiveTracks.
Jean-Michel Trivi38f86712017-04-11 14:10:17 -07007738 if (mActiveTracks.indexOf(recordTrack) < 0 || recordTrack->mState == TrackBase::PAUSING) {
Eric Laurent81784c32012-11-19 14:55:58 -08007739 return false;
7740 }
Glenn Kasten47c20702013-08-13 15:37:35 -07007741 // note that threadLoop may still be processing the track at this point [without lock]
Eric Laurent81784c32012-11-19 14:55:58 -08007742 recordTrack->mState = TrackBase::PAUSING;
Andy Hungce685402018-10-05 17:23:27 -07007743
Andy Hungabfab202019-03-07 19:45:54 -08007744 // NOTE: Waiting here is important to keep stop synchronous.
7745 // This is needed for proper patchRecord peer release.
Andy Hungce685402018-10-05 17:23:27 -07007746 while (recordTrack->mState == TrackBase::PAUSING && !recordTrack->isInvalid()) {
7747 mWaitWorkCV.broadcast(); // signal thread to stop
7748 mStartStopCond.wait(mLock);
Eric Laurent81784c32012-11-19 14:55:58 -08007749 }
Andy Hungce685402018-10-05 17:23:27 -07007750
7751 if (recordTrack->mState == TrackBase::PAUSED) { // successful stop
Eric Laurent81784c32012-11-19 14:55:58 -08007752 ALOGV("Record stopped OK");
7753 return true;
7754 }
Andy Hungce685402018-10-05 17:23:27 -07007755
7756 // don't handle anything - we've been invalidated or restarted and in a different state
7757 ALOGW_IF("%s(%d): unsynchronized stop, state: %d",
7758 __func__, recordTrack->id(), recordTrack->mState);
Eric Laurent81784c32012-11-19 14:55:58 -08007759 return false;
7760}
7761
Glenn Kasten0f11b512014-01-31 16:18:54 -08007762bool AudioFlinger::RecordThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
Eric Laurent81784c32012-11-19 14:55:58 -08007763{
7764 return false;
7765}
7766
Glenn Kasten0f11b512014-01-31 16:18:54 -08007767status_t AudioFlinger::RecordThread::setSyncEvent(const sp<SyncEvent>& event __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007768{
7769#if 0 // This branch is currently dead code, but is preserved in case it will be needed in future
7770 if (!isValidSyncEvent(event)) {
7771 return BAD_VALUE;
7772 }
7773
Glenn Kastend848eb42016-03-08 13:42:11 -08007774 audio_session_t eventSession = event->triggerSession();
Eric Laurent81784c32012-11-19 14:55:58 -08007775 status_t ret = NAME_NOT_FOUND;
7776
7777 Mutex::Autolock _l(mLock);
7778
7779 for (size_t i = 0; i < mTracks.size(); i++) {
7780 sp<RecordTrack> track = mTracks[i];
7781 if (eventSession == track->sessionId()) {
7782 (void) track->setSyncEvent(event);
7783 ret = NO_ERROR;
7784 }
7785 }
7786 return ret;
7787#else
7788 return BAD_VALUE;
7789#endif
7790}
7791
jiabin653cc0a2018-01-17 17:54:10 -08007792status_t AudioFlinger::RecordThread::getActiveMicrophones(
7793 std::vector<media::MicrophoneInfo>* activeMicrophones)
7794{
7795 ALOGV("RecordThread::getActiveMicrophones");
7796 AutoMutex _l(mLock);
jiabin9ff780e2018-03-19 18:19:52 -07007797 status_t status = mInput->stream->getActiveMicrophones(activeMicrophones);
7798 return status;
jiabin653cc0a2018-01-17 17:54:10 -08007799}
7800
Paul McLean12340082019-03-19 09:35:05 -06007801status_t AudioFlinger::RecordThread::setPreferredMicrophoneDirection(
7802 audio_microphone_direction_t direction)
Paul McLean03a6e6a2018-12-04 10:54:13 -07007803{
Paul McLean12340082019-03-19 09:35:05 -06007804 ALOGV("setPreferredMicrophoneDirection(%d)", direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07007805 AutoMutex _l(mLock);
Paul McLean12340082019-03-19 09:35:05 -06007806 return mInput->stream->setPreferredMicrophoneDirection(direction);
Paul McLean03a6e6a2018-12-04 10:54:13 -07007807}
7808
Paul McLean12340082019-03-19 09:35:05 -06007809status_t AudioFlinger::RecordThread::setPreferredMicrophoneFieldDimension(float zoom)
Paul McLean03a6e6a2018-12-04 10:54:13 -07007810{
Paul McLean12340082019-03-19 09:35:05 -06007811 ALOGV("setPreferredMicrophoneFieldDimension(%f)", zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07007812 AutoMutex _l(mLock);
Paul McLean12340082019-03-19 09:35:05 -06007813 return mInput->stream->setPreferredMicrophoneFieldDimension(zoom);
Paul McLean03a6e6a2018-12-04 10:54:13 -07007814}
7815
Kevin Rocard069c2712018-03-29 19:09:14 -07007816void AudioFlinger::RecordThread::updateMetadata_l()
7817{
7818 if (mInput == nullptr || mInput->stream == nullptr ||
7819 !mActiveTracks.readAndClearHasChanged()) {
7820 return;
7821 }
7822 StreamInHalInterface::SinkMetadata metadata;
7823 for (const sp<RecordTrack> &track : mActiveTracks) {
7824 // No track is invalid as this is called after prepareTrack_l in the same critical section
7825 metadata.tracks.push_back({
7826 .source = track->attributes().source,
7827 .gain = 1, // capture tracks do not have volumes
7828 });
7829 }
7830 mInput->stream->updateSinkMetadata(metadata);
7831}
7832
Eric Laurent81784c32012-11-19 14:55:58 -08007833// destroyTrack_l() must be called with ThreadBase::mLock held
7834void AudioFlinger::RecordThread::destroyTrack_l(const sp<RecordTrack>& track)
7835{
Eric Laurentbfb1b832013-01-07 09:53:42 -08007836 track->terminate();
7837 track->mState = TrackBase::STOPPED;
Eric Laurent81784c32012-11-19 14:55:58 -08007838 // active tracks are removed by threadLoop()
Glenn Kasten2b806402013-11-20 16:37:38 -08007839 if (mActiveTracks.indexOf(track) < 0) {
Eric Laurent81784c32012-11-19 14:55:58 -08007840 removeTrack_l(track);
7841 }
7842}
7843
7844void AudioFlinger::RecordThread::removeTrack_l(const sp<RecordTrack>& track)
7845{
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007846 String8 result;
7847 track->appendDump(result, false /* active */);
7848 mLocalLog.log("removeTrack_l (%p) %s", track.get(), result.string());
7849
Eric Laurent81784c32012-11-19 14:55:58 -08007850 mTracks.remove(track);
7851 // need anything related to effects here?
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007852 if (track->isFastTrack()) {
7853 ALOG_ASSERT(!mFastTrackAvail);
7854 mFastTrackAvail = true;
7855 }
Eric Laurent81784c32012-11-19 14:55:58 -08007856}
7857
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007858void AudioFlinger::RecordThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007859{
Mikhail Naganov913d06c2016-11-01 12:49:22 -07007860 AudioStreamIn *input = mInput;
7861 audio_input_flags_t flags = input != NULL ? input->flags : AUDIO_INPUT_FLAG_NONE;
7862 dprintf(fd, " AudioStreamIn: %p flags %#x (%s)\n",
Andy Hung9b181952019-02-25 14:53:36 -08007863 input, flags, toString(flags).c_str());
Andy Hung6427e442018-08-09 12:51:02 -07007864 dprintf(fd, " Frames read: %lld\n", (long long)mFramesRead);
Eric Tan39ec8d62018-07-24 09:49:29 -07007865 if (mActiveTracks.isEmpty()) {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007866 dprintf(fd, " No active record clients\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007867 }
Andy Hungbfa64962017-06-12 14:43:19 -07007868
7869 if (input != nullptr) {
7870 dprintf(fd, " Hal stream dump:\n");
7871 (void)input->stream->dump(fd);
7872 }
7873
Glenn Kasten6e6704c2014-07-03 10:20:00 -07007874 dprintf(fd, " Fast capture thread: %s\n", hasFastCapture() ? "yes" : "no");
Glenn Kasten6dbb5e32014-05-13 10:38:42 -07007875 dprintf(fd, " Fast track available: %s\n", mFastTrackAvail ? "yes" : "no");
Glenn Kasten17c9c992015-03-02 15:53:01 -08007876
Glenn Kasten2f90c512015-12-02 11:40:09 -08007877 // Make a non-atomic copy of fast capture dump state so it won't change underneath us
7878 // while we are dumping it. It may be inconsistent, but it won't mutate!
7879 // This is a large object so we place it on the heap.
7880 // FIXME 25972958: Need an intelligent copy constructor that does not touch unused pages.
Eric Tan2942a4e2018-09-12 17:41:27 -07007881 const std::unique_ptr<FastCaptureDumpState> copy =
7882 std::make_unique<FastCaptureDumpState>(mFastCaptureDumpState);
Glenn Kasten2f90c512015-12-02 11:40:09 -08007883 copy->dump(fd);
Eric Laurent81784c32012-11-19 14:55:58 -08007884}
7885
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07007886void AudioFlinger::RecordThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent81784c32012-11-19 14:55:58 -08007887{
Eric Laurent81784c32012-11-19 14:55:58 -08007888 String8 result;
Marco Nelissenb2208842014-02-07 14:00:50 -08007889 size_t numtracks = mTracks.size();
7890 size_t numactive = mActiveTracks.size();
7891 size_t numactiveseen = 0;
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007892 dprintf(fd, " %zu Tracks", numtracks);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007893 const char *prefix = " ";
Marco Nelissenb2208842014-02-07 14:00:50 -08007894 if (numtracks) {
Glenn Kastenc42e9b42016-03-21 11:35:03 -07007895 dprintf(fd, " of which %zu are active\n", numactive);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007896 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007897 mTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007898 for (size_t i = 0; i < numtracks ; ++i) {
7899 sp<RecordTrack> track = mTracks[i];
7900 if (track != 0) {
7901 bool active = mActiveTracks.indexOf(track) >= 0;
7902 if (active) {
7903 numactiveseen++;
7904 }
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007905 result.append(prefix);
7906 track->appendDump(result, active);
Marco Nelissenb2208842014-02-07 14:00:50 -08007907 }
Eric Laurent81784c32012-11-19 14:55:58 -08007908 }
Marco Nelissenb2208842014-02-07 14:00:50 -08007909 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -07007910 dprintf(fd, "\n");
Eric Laurent81784c32012-11-19 14:55:58 -08007911 }
7912
Marco Nelissenb2208842014-02-07 14:00:50 -08007913 if (numactiveseen != numactive) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007914 result.append(" The following tracks are in the active list but"
Marco Nelissenb2208842014-02-07 14:00:50 -08007915 " not in the track list\n");
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007916 result.append(prefix);
Andy Hung000adb52018-06-01 15:43:26 -07007917 mActiveTracks[0]->appendDumpHeader(result);
Marco Nelissenb2208842014-02-07 14:00:50 -08007918 for (size_t i = 0; i < numactive; ++i) {
Glenn Kasten2b806402013-11-20 16:37:38 -08007919 sp<RecordTrack> track = mActiveTracks[i];
Marco Nelissenb2208842014-02-07 14:00:50 -08007920 if (mTracks.indexOf(track) < 0) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07007921 result.append(prefix);
7922 track->appendDump(result, true /* active */);
Marco Nelissenb2208842014-02-07 14:00:50 -08007923 }
Glenn Kasten2b806402013-11-20 16:37:38 -08007924 }
Eric Laurent81784c32012-11-19 14:55:58 -08007925
7926 }
7927 write(fd, result.string(), result.size());
7928}
7929
Svet Ganovf4ddfef2018-01-16 07:37:58 -08007930void AudioFlinger::RecordThread::setRecordSilenced(uid_t uid, bool silenced)
7931{
7932 Mutex::Autolock _l(mLock);
7933 for (size_t i = 0; i < mTracks.size() ; i++) {
7934 sp<RecordTrack> track = mTracks[i];
7935 if (track != 0 && track->uid() == uid) {
7936 track->setSilenced(silenced);
7937 }
7938 }
7939}
Andy Hung73c02e42015-03-29 01:13:58 -07007940
7941void AudioFlinger::RecordThread::ResamplerBufferProvider::reset()
7942{
7943 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7944 RecordThread *recordThread = (RecordThread *) threadBase.get();
7945 mRsmpInFront = recordThread->mRsmpInRear;
7946 mRsmpInUnrel = 0;
7947}
7948
7949void AudioFlinger::RecordThread::ResamplerBufferProvider::sync(
7950 size_t *framesAvailable, bool *hasOverrun)
7951{
7952 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
7953 RecordThread *recordThread = (RecordThread *) threadBase.get();
7954 const int32_t rear = recordThread->mRsmpInRear;
7955 const int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07007956 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung73c02e42015-03-29 01:13:58 -07007957
7958 size_t framesIn;
7959 bool overrun = false;
7960 if (filled < 0) {
7961 // should not happen, but treat like a massive overrun and re-sync
7962 framesIn = 0;
7963 mRsmpInFront = rear;
7964 overrun = true;
7965 } else if ((size_t) filled <= recordThread->mRsmpInFrames) {
7966 framesIn = (size_t) filled;
7967 } else {
7968 // client is not keeping up with server, but give it latest data
7969 framesIn = recordThread->mRsmpInFrames;
Hongwei Wang95e37682019-04-12 11:13:36 -07007970 mRsmpInFront = /* front = */ audio_utils::safe_sub_overflow(
7971 rear, static_cast<int32_t>(framesIn));
Andy Hung73c02e42015-03-29 01:13:58 -07007972 overrun = true;
7973 }
7974 if (framesAvailable != NULL) {
7975 *framesAvailable = framesIn;
7976 }
7977 if (hasOverrun != NULL) {
7978 *hasOverrun = overrun;
7979 }
7980}
7981
Eric Laurent81784c32012-11-19 14:55:58 -08007982// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007983status_t AudioFlinger::RecordThread::ResamplerBufferProvider::getNextBuffer(
Glenn Kastend79072e2016-01-06 08:41:20 -08007984 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08007985{
Andy Hung73c02e42015-03-29 01:13:58 -07007986 sp<ThreadBase> threadBase = mRecordTrack->mThread.promote();
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007987 if (threadBase == 0) {
7988 buffer->frameCount = 0;
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007989 buffer->raw = NULL;
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007990 return NOT_ENOUGH_DATA;
7991 }
7992 RecordThread *recordThread = (RecordThread *) threadBase.get();
7993 int32_t rear = recordThread->mRsmpInRear;
Andy Hung73c02e42015-03-29 01:13:58 -07007994 int32_t front = mRsmpInFront;
Hongwei Wang95e37682019-04-12 11:13:36 -07007995 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08007996 // FIXME should not be P2 (don't want to increase latency)
7997 // FIXME if client not keeping up, discard
Glenn Kasten607fa3e2014-02-21 14:24:58 -08007998 LOG_ALWAYS_FATAL_IF(!(0 <= filled && (size_t) filled <= recordThread->mRsmpInFrames));
Glenn Kasten85948432013-08-19 12:09:05 -07007999 // 'filled' may be non-contiguous, so return only the first contiguous chunk
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008000 front &= recordThread->mRsmpInFramesP2 - 1;
8001 size_t part1 = recordThread->mRsmpInFramesP2 - front;
Glenn Kasten85948432013-08-19 12:09:05 -07008002 if (part1 > (size_t) filled) {
8003 part1 = filled;
8004 }
8005 size_t ask = buffer->frameCount;
8006 ALOG_ASSERT(ask > 0);
8007 if (part1 > ask) {
8008 part1 = ask;
8009 }
8010 if (part1 == 0) {
Andy Hung73c02e42015-03-29 01:13:58 -07008011 // out of data is fine since the resampler will return a short-count.
Glenn Kasten85948432013-08-19 12:09:05 -07008012 buffer->raw = NULL;
8013 buffer->frameCount = 0;
Andy Hung73c02e42015-03-29 01:13:58 -07008014 mRsmpInUnrel = 0;
Glenn Kasten85948432013-08-19 12:09:05 -07008015 return NOT_ENOUGH_DATA;
Eric Laurent81784c32012-11-19 14:55:58 -08008016 }
8017
Andy Hung57446612015-04-19 23:56:46 -07008018 buffer->raw = (uint8_t*)recordThread->mRsmpInBuffer + front * recordThread->mFrameSize;
Glenn Kasten85948432013-08-19 12:09:05 -07008019 buffer->frameCount = part1;
Andy Hung73c02e42015-03-29 01:13:58 -07008020 mRsmpInUnrel = part1;
Eric Laurent81784c32012-11-19 14:55:58 -08008021 return NO_ERROR;
8022}
8023
8024// AudioBufferProvider interface
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008025void AudioFlinger::RecordThread::ResamplerBufferProvider::releaseBuffer(
8026 AudioBufferProvider::Buffer* buffer)
Eric Laurent81784c32012-11-19 14:55:58 -08008027{
Hongwei Wang95e37682019-04-12 11:13:36 -07008028 int32_t stepCount = static_cast<int32_t>(buffer->frameCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008029 if (stepCount == 0) {
8030 return;
8031 }
Andy Hung73c02e42015-03-29 01:13:58 -07008032 ALOG_ASSERT(stepCount <= mRsmpInUnrel);
8033 mRsmpInUnrel -= stepCount;
Hongwei Wang95e37682019-04-12 11:13:36 -07008034 mRsmpInFront = audio_utils::safe_add_overflow(mRsmpInFront, stepCount);
Glenn Kasten85948432013-08-19 12:09:05 -07008035 buffer->raw = NULL;
Eric Laurent81784c32012-11-19 14:55:58 -08008036 buffer->frameCount = 0;
8037}
8038
Eric Laurentd8365c52017-07-16 15:27:05 -07008039void AudioFlinger::RecordThread::checkBtNrec()
8040{
8041 Mutex::Autolock _l(mLock);
8042 checkBtNrec_l();
8043}
8044
8045void AudioFlinger::RecordThread::checkBtNrec_l()
8046{
8047 // disable AEC and NS if the device is a BT SCO headset supporting those
8048 // pre processings
jiabin10d86fd2019-10-31 17:20:42 -07008049 bool suspend = audio_is_bluetooth_sco_device(inDeviceType()) &&
Eric Laurentd8365c52017-07-16 15:27:05 -07008050 mAudioFlinger->btNrecIsOff();
8051 if (mBtNrecSuspended.exchange(suspend) != suspend) {
8052 for (size_t i = 0; i < mEffectChains.size(); i++) {
8053 setEffectSuspended_l(FX_IID_AEC, suspend, mEffectChains[i]->sessionId());
8054 setEffectSuspended_l(FX_IID_NS, suspend, mEffectChains[i]->sessionId());
8055 }
8056 }
8057}
8058
Andy Hung97a893e2015-03-29 01:03:07 -07008059
Eric Laurent10351942014-05-08 18:49:52 -07008060bool AudioFlinger::RecordThread::checkForNewParameter_l(const String8& keyValuePair,
8061 status_t& status)
Eric Laurent81784c32012-11-19 14:55:58 -08008062{
8063 bool reconfig = false;
8064
Eric Laurent10351942014-05-08 18:49:52 -07008065 status = NO_ERROR;
Eric Laurent81784c32012-11-19 14:55:58 -08008066
Eric Laurent10351942014-05-08 18:49:52 -07008067 audio_format_t reqFormat = mFormat;
8068 uint32_t samplingRate = mSampleRate;
Glenn Kastene1635ec2015-06-08 15:46:49 -07008069 // 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 -07008070 audio_channel_mask_t channelMask = audio_channel_in_mask_from_count(mChannelCount);
8071
8072 AudioParameter param = AudioParameter(keyValuePair);
8073 int value;
Haynes Mathew George9ce67b52015-09-30 11:40:47 -07008074
8075 // scope for AutoPark extends to end of method
8076 AutoPark<FastCapture> park(mFastCapture);
8077
Eric Laurent10351942014-05-08 18:49:52 -07008078 // TODO Investigate when this code runs. Check with audio policy when a sample rate and
8079 // channel count change can be requested. Do we mandate the first client defines the
8080 // HAL sampling rate and channel count or do we allow changes on the fly?
8081 if (param.getInt(String8(AudioParameter::keySamplingRate), value) == NO_ERROR) {
8082 samplingRate = value;
8083 reconfig = true;
8084 }
8085 if (param.getInt(String8(AudioParameter::keyFormat), value) == NO_ERROR) {
Andy Hung97a893e2015-03-29 01:03:07 -07008086 if (!audio_is_linear_pcm((audio_format_t) value)) {
Eric Laurent10351942014-05-08 18:49:52 -07008087 status = BAD_VALUE;
8088 } else {
8089 reqFormat = (audio_format_t) value;
Eric Laurent81784c32012-11-19 14:55:58 -08008090 reconfig = true;
8091 }
Eric Laurent10351942014-05-08 18:49:52 -07008092 }
8093 if (param.getInt(String8(AudioParameter::keyChannels), value) == NO_ERROR) {
8094 audio_channel_mask_t mask = (audio_channel_mask_t) value;
Andy Hungd330ee42015-04-20 13:23:41 -07008095 if (!audio_is_input_channel(mask) ||
8096 audio_channel_count_from_in_mask(mask) > FCC_8) {
Eric Laurent10351942014-05-08 18:49:52 -07008097 status = BAD_VALUE;
8098 } else {
8099 channelMask = mask;
8100 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008101 }
Eric Laurent10351942014-05-08 18:49:52 -07008102 }
8103 if (param.getInt(String8(AudioParameter::keyFrameCount), value) == NO_ERROR) {
8104 // do not accept frame count changes if tracks are open as the track buffer
8105 // size depends on frame count and correct behavior would not be guaranteed
8106 // if frame count is changed after track creation
8107 if (mActiveTracks.size() > 0) {
8108 status = INVALID_OPERATION;
8109 } else {
8110 reconfig = true;
Eric Laurent81784c32012-11-19 14:55:58 -08008111 }
Eric Laurent10351942014-05-08 18:49:52 -07008112 }
8113 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabin10d86fd2019-10-31 17:20:42 -07008114 LOG_FATAL("Should not set routing device in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008115 }
8116 if (param.getInt(String8(AudioParameter::keyInputSource), value) == NO_ERROR &&
8117 mAudioSource != (audio_source_t)value) {
jiabin10d86fd2019-10-31 17:20:42 -07008118 LOG_FATAL("Should not set audio source in RecordThread");
Eric Laurent10351942014-05-08 18:49:52 -07008119 }
Glenn Kastene198c362013-08-13 09:13:36 -07008120
Eric Laurent10351942014-05-08 18:49:52 -07008121 if (status == NO_ERROR) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008122 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008123 if (status == INVALID_OPERATION) {
8124 inputStandBy();
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008125 status = mInput->stream->setParameters(keyValuePair);
Eric Laurent10351942014-05-08 18:49:52 -07008126 }
8127 if (reconfig) {
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008128 if (status == BAD_VALUE) {
8129 uint32_t sRate;
8130 audio_channel_mask_t channelMask;
8131 audio_format_t format;
8132 if (mInput->stream->getAudioProperties(&sRate, &channelMask, &format) == OK &&
8133 audio_is_linear_pcm(format) && audio_is_linear_pcm(reqFormat) &&
8134 sRate <= (AUDIO_RESAMPLER_DOWN_RATIO_MAX * samplingRate) &&
8135 audio_channel_count_from_in_mask(channelMask) <= FCC_8) {
8136 status = NO_ERROR;
8137 }
Eric Laurent81784c32012-11-19 14:55:58 -08008138 }
Eric Laurent10351942014-05-08 18:49:52 -07008139 if (status == NO_ERROR) {
8140 readInputParameters_l();
Eric Laurent73e26b62015-04-27 16:55:58 -07008141 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
Eric Laurent81784c32012-11-19 14:55:58 -08008142 }
8143 }
Eric Laurent81784c32012-11-19 14:55:58 -08008144 }
Eric Laurent10351942014-05-08 18:49:52 -07008145
Eric Laurent81784c32012-11-19 14:55:58 -08008146 return reconfig;
8147}
8148
8149String8 AudioFlinger::RecordThread::getParameters(const String8& keys)
8150{
Eric Laurent81784c32012-11-19 14:55:58 -08008151 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008152 if (initCheck() == NO_ERROR) {
8153 String8 out_s8;
8154 if (mInput->stream->getParameters(keys, &out_s8) == OK) {
8155 return out_s8;
8156 }
Eric Laurent81784c32012-11-19 14:55:58 -08008157 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008158 return String8();
Eric Laurent81784c32012-11-19 14:55:58 -08008159}
8160
Eric Laurent09f1ed22019-04-24 17:45:17 -07008161void AudioFlinger::RecordThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
8162 audio_port_handle_t portId) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008163 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8164
8165 desc->mIoHandle = mId;
Eric Laurent81784c32012-11-19 14:55:58 -08008166
8167 switch (event) {
Eric Laurent73e26b62015-04-27 16:55:58 -07008168 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008169 case AUDIO_INPUT_REGISTERED:
Eric Laurent73e26b62015-04-27 16:55:58 -07008170 case AUDIO_INPUT_CONFIG_CHANGED:
Eric Laurent296fb132015-05-01 11:38:42 -07008171 desc->mPatch = mPatch;
Eric Laurent73e26b62015-04-27 16:55:58 -07008172 desc->mChannelMask = mChannelMask;
8173 desc->mSamplingRate = mSampleRate;
8174 desc->mFormat = mFormat;
8175 desc->mFrameCount = mFrameCount;
Glenn Kasten4a8308b2016-04-18 14:10:01 -07008176 desc->mFrameCountHAL = mFrameCount;
Eric Laurent73e26b62015-04-27 16:55:58 -07008177 desc->mLatency = 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008178 break;
Eric Laurent09f1ed22019-04-24 17:45:17 -07008179 case AUDIO_CLIENT_STARTED:
8180 desc->mPatch = mPatch;
8181 desc->mPortId = portId;
8182 break;
Eric Laurent73e26b62015-04-27 16:55:58 -07008183 case AUDIO_INPUT_CLOSED:
Eric Laurent81784c32012-11-19 14:55:58 -08008184 default:
8185 break;
8186 }
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07008187 mAudioFlinger->ioConfigChanged(event, desc, pid);
Eric Laurent81784c32012-11-19 14:55:58 -08008188}
8189
Glenn Kastendeca2ae2014-02-07 10:25:56 -08008190void AudioFlinger::RecordThread::readInputParameters_l()
Eric Laurent81784c32012-11-19 14:55:58 -08008191{
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008192 status_t result = mInput->stream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8193 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
Andy Hung463be252014-07-10 16:56:07 -07008194 mFormat = mHALFormat;
Mikhail Naganovce9f2652018-07-16 11:09:24 -07008195 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
8196 if (audio_is_linear_pcm(mFormat)) {
8197 LOG_ALWAYS_FATAL_IF(mChannelCount > FCC_8, "HAL channel count %d > %d",
8198 mChannelCount, FCC_8);
8199 } else {
8200 // Can have more that FCC_8 channels in encoded streams.
8201 ALOGI("HAL format %#x is not linear pcm", mFormat);
8202 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008203 result = mInput->stream->getFrameSize(&mFrameSize);
8204 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8205 result = mInput->stream->getBufferSize(&mBufferSize);
8206 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
Glenn Kasten548efc92012-11-29 08:48:51 -08008207 mFrameCount = mBufferSize / mFrameSize;
Mikhail Naganovb3cf7e62017-06-02 10:24:24 -07008208 ALOGV("%p RecordThread params: mChannelCount=%u, mFormat=%#x, mFrameSize=%lld, "
8209 "mBufferSize=%lld, mFrameCount=%lld",
8210 this, mChannelCount, mFormat, (long long)mFrameSize, (long long)mBufferSize,
8211 (long long)mFrameCount);
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008212 // This is the formula for calculating the temporary buffer size.
Glenn Kastene8426142014-02-28 16:45:03 -08008213 // With 7 HAL buffers, we can guarantee ability to down-sample the input by ratio of 6:1 to
Glenn Kasten85948432013-08-19 12:09:05 -07008214 // 1 full output buffer, regardless of the alignment of the available input.
Glenn Kastene8426142014-02-28 16:45:03 -08008215 // The value is somewhat arbitrary, and could probably be even larger.
Glenn Kasten6dd62fb2013-12-05 16:35:58 -08008216 // A larger value should allow more old data to be read after a track calls start(),
8217 // without increasing latency.
Andy Hung97a893e2015-03-29 01:03:07 -07008218 //
8219 // Note this is independent of the maximum downsampling ratio permitted for capture.
Glenn Kastene8426142014-02-28 16:45:03 -08008220 mRsmpInFrames = mFrameCount * 7;
Glenn Kasten85948432013-08-19 12:09:05 -07008221 mRsmpInFramesP2 = roundup(mRsmpInFrames);
Andy Hung57446612015-04-19 23:56:46 -07008222 free(mRsmpInBuffer);
Andy Hung0a01c2f2015-09-21 12:44:54 -07008223 mRsmpInBuffer = NULL;
Glenn Kasten49d00ad2014-07-21 11:22:03 -07008224
8225 // TODO optimize audio capture buffer sizes ...
8226 // Here we calculate the size of the sliding buffer used as a source
8227 // for resampling. mRsmpInFramesP2 is currently roundup(mFrameCount * 7).
8228 // For current HAL frame counts, this is usually 2048 = 40 ms. It would
8229 // be better to have it derived from the pipe depth in the long term.
8230 // The current value is higher than necessary. However it should not add to latency.
8231
Glenn Kasten85948432013-08-19 12:09:05 -07008232 // Over-allocate beyond mRsmpInFramesP2 to permit a HAL read past end of buffer
Glenn Kasten1b291842016-07-18 14:55:21 -07008233 mRsmpInFramesOA = mRsmpInFramesP2 + mFrameCount - 1;
8234 (void)posix_memalign(&mRsmpInBuffer, 32, mRsmpInFramesOA * mFrameSize);
Glenn Kastend3bb6452016-12-05 18:14:37 -08008235 // if posix_memalign fails, will segv here.
8236 memset(mRsmpInBuffer, 0, mRsmpInFramesOA * mFrameSize);
Eric Laurent81784c32012-11-19 14:55:58 -08008237
Glenn Kasten4cc0a6a2014-02-17 14:31:46 -08008238 // AudioRecord mSampleRate and mChannelCount are constant due to AudioRecord API constraints.
8239 // But if thread's mSampleRate or mChannelCount changes, how will that affect active tracks?
Eric Laurent81784c32012-11-19 14:55:58 -08008240}
8241
Glenn Kasten5f972c02014-01-13 09:59:31 -08008242uint32_t AudioFlinger::RecordThread::getInputFramesLost()
Eric Laurent81784c32012-11-19 14:55:58 -08008243{
8244 Mutex::Autolock _l(mLock);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008245 uint32_t result;
8246 if (initCheck() == NO_ERROR && mInput->stream->getInputFramesLost(&result) == OK) {
8247 return result;
Eric Laurent81784c32012-11-19 14:55:58 -08008248 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008249 return 0;
Eric Laurent81784c32012-11-19 14:55:58 -08008250}
8251
Glenn Kastend848eb42016-03-08 13:42:11 -08008252KeyedVector<audio_session_t, bool> AudioFlinger::RecordThread::sessionIds() const
Eric Laurent81784c32012-11-19 14:55:58 -08008253{
Glenn Kastend848eb42016-03-08 13:42:11 -08008254 KeyedVector<audio_session_t, bool> ids;
Eric Laurent81784c32012-11-19 14:55:58 -08008255 Mutex::Autolock _l(mLock);
8256 for (size_t j = 0; j < mTracks.size(); ++j) {
8257 sp<RecordThread::RecordTrack> track = mTracks[j];
Glenn Kastend848eb42016-03-08 13:42:11 -08008258 audio_session_t sessionId = track->sessionId();
Eric Laurent81784c32012-11-19 14:55:58 -08008259 if (ids.indexOfKey(sessionId) < 0) {
8260 ids.add(sessionId, true);
8261 }
8262 }
8263 return ids;
8264}
8265
8266AudioFlinger::AudioStreamIn* AudioFlinger::RecordThread::clearInput()
8267{
8268 Mutex::Autolock _l(mLock);
8269 AudioStreamIn *input = mInput;
8270 mInput = NULL;
8271 return input;
8272}
8273
8274// this method must always be called either with ThreadBase mLock held or inside the thread loop
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008275sp<StreamHalInterface> AudioFlinger::RecordThread::stream() const
Eric Laurent81784c32012-11-19 14:55:58 -08008276{
8277 if (mInput == NULL) {
8278 return NULL;
8279 }
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008280 return mInput->stream;
Eric Laurent81784c32012-11-19 14:55:58 -08008281}
8282
8283status_t AudioFlinger::RecordThread::addEffectChain_l(const sp<EffectChain>& chain)
8284{
Eric Laurent81784c32012-11-19 14:55:58 -08008285 ALOGV("addEffectChain_l() %p on thread %p", chain.get(), this);
Eric Laurentaaa44472014-09-12 17:41:50 -07008286 chain->setThread(this);
Eric Laurent81784c32012-11-19 14:55:58 -08008287 chain->setInBuffer(NULL);
8288 chain->setOutBuffer(NULL);
8289
8290 checkSuspendOnAddEffectChain_l(chain);
8291
Eric Laurent1b928682014-10-02 19:41:47 -07008292 // make sure enabled pre processing effects state is communicated to the HAL as we
8293 // just moved them to a new input stream.
8294 chain->syncHalEffectsState();
8295
Eric Laurent81784c32012-11-19 14:55:58 -08008296 mEffectChains.add(chain);
8297
8298 return NO_ERROR;
8299}
8300
8301size_t AudioFlinger::RecordThread::removeEffectChain_l(const sp<EffectChain>& chain)
8302{
8303 ALOGV("removeEffectChain_l() %p from thread %p", chain.get(), this);
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008304
8305 for (size_t i = 0; i < mEffectChains.size(); i++) {
8306 if (chain == mEffectChains[i]) {
8307 mEffectChains.removeAt(i);
8308 break;
8309 }
Eric Laurent81784c32012-11-19 14:55:58 -08008310 }
Eric Laurentb20cf7d2019-04-05 19:37:34 -07008311 return mEffectChains.size();
Eric Laurent81784c32012-11-19 14:55:58 -08008312}
8313
Eric Laurent1c333e22014-05-20 10:48:17 -07008314status_t AudioFlinger::RecordThread::createAudioPatch_l(const struct audio_patch *patch,
8315 audio_patch_handle_t *handle)
8316{
8317 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008318
8319 // store new device and send to effects
jiabin10d86fd2019-10-31 17:20:42 -07008320 mInDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
8321 mInDeviceTypeAddr.mAddress = patch->sources[0].ext.device.address;
François Gaffie0c280aa2018-07-25 10:02:15 +02008322 audio_port_handle_t deviceId = patch->sources[0].id;
Eric Laurent054d9d32015-04-24 08:48:48 -07008323 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabinb8269fd2019-11-11 12:16:27 -08008324 mEffectChains[i]->setInputDevice_l(inDeviceTypeAddr());
Eric Laurent054d9d32015-04-24 08:48:48 -07008325 }
8326
Eric Laurentd8365c52017-07-16 15:27:05 -07008327 checkBtNrec_l();
Eric Laurent054d9d32015-04-24 08:48:48 -07008328
8329 // store new source and send to effects
8330 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8331 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
Eric Laurent1c333e22014-05-20 10:48:17 -07008332 for (size_t i = 0; i < mEffectChains.size(); i++) {
Eric Laurent054d9d32015-04-24 08:48:48 -07008333 mEffectChains[i]->setAudioSource_l(mAudioSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07008334 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008335 }
Eric Laurent1c333e22014-05-20 10:48:17 -07008336
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008337 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008338 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8339 status = hwDevice->createAudioPatch(patch->num_sources,
8340 patch->sources,
8341 patch->num_sinks,
8342 patch->sinks,
8343 handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008344 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008345 char *address;
8346 if (strcmp(patch->sources[0].ext.device.address, "") != 0) {
8347 address = audio_device_address_to_parameter(
8348 patch->sources[0].ext.device.type,
8349 patch->sources[0].ext.device.address);
8350 } else {
8351 address = (char *)calloc(1, 1);
8352 }
8353 AudioParameter param = AudioParameter(String8(address));
8354 free(address);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008355 param.addInt(String8(AudioParameter::keyRouting),
Eric Laurent054d9d32015-04-24 08:48:48 -07008356 (int)patch->sources[0].ext.device.type);
Mikhail Naganov00260b52016-10-13 12:54:24 -07008357 param.addInt(String8(AudioParameter::keyInputSource),
Eric Laurent054d9d32015-04-24 08:48:48 -07008358 (int)patch->sinks[0].ext.mix.usecase.source);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008359 status = mInput->stream->setParameters(param.toString());
Eric Laurent054d9d32015-04-24 08:48:48 -07008360 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent1c333e22014-05-20 10:48:17 -07008361 }
Eric Laurent054d9d32015-04-24 08:48:48 -07008362
jiabin10d86fd2019-10-31 17:20:42 -07008363 if ((mPatch.num_sources == 0) || (mPatch.sources[0].id != deviceId)) {
Eric Laurente8726fe2015-06-26 09:39:24 -07008364 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
jiabin10d86fd2019-10-31 17:20:42 -07008365 mPatch = *patch;
Eric Laurente8726fe2015-06-26 09:39:24 -07008366 }
Eric Laurent296fb132015-05-01 11:38:42 -07008367
Eric Laurent1c333e22014-05-20 10:48:17 -07008368 return status;
8369}
8370
8371status_t AudioFlinger::RecordThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8372{
8373 status_t status = NO_ERROR;
Eric Laurent054d9d32015-04-24 08:48:48 -07008374
jiabin10d86fd2019-10-31 17:20:42 -07008375 mPatch = audio_patch{};
8376 mInDeviceTypeAddr.reset();
Eric Laurent054d9d32015-04-24 08:48:48 -07008377
Mikhail Naganov9ee05402016-10-13 15:58:17 -07008378 if (mInput->audioHwDev->supportsAudioPatches()) {
Mikhail Naganove4f1f632016-08-31 11:35:10 -07008379 sp<DeviceHalInterface> hwDevice = mInput->audioHwDev->hwDevice();
8380 status = hwDevice->releaseAudioPatch(handle);
Eric Laurent1c333e22014-05-20 10:48:17 -07008381 } else {
Eric Laurent054d9d32015-04-24 08:48:48 -07008382 AudioParameter param;
Mikhail Naganov00260b52016-10-13 12:54:24 -07008383 param.addInt(String8(AudioParameter::keyRouting), 0);
Mikhail Naganov1dc98672016-08-18 17:50:29 -07008384 status = mInput->stream->setParameters(param.toString());
Eric Laurent1c333e22014-05-20 10:48:17 -07008385 }
8386 return status;
8387}
8388
jiabin10d86fd2019-10-31 17:20:42 -07008389void AudioFlinger::RecordThread::updateOutDevices(const DeviceDescriptorBaseVector& outDevices)
8390{
8391 mOutDevices = outDevices;
8392 mOutDeviceTypeAddrs = deviceTypeAddrsFromDescriptors(mOutDevices);
8393 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabinb8269fd2019-11-11 12:16:27 -08008394 mEffectChains[i]->setDevices_l(outDeviceTypeAddrs());
jiabin10d86fd2019-10-31 17:20:42 -07008395 }
8396}
8397
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008398void AudioFlinger::RecordThread::addPatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008399{
8400 Mutex::Autolock _l(mLock);
8401 mTracks.add(record);
Mikhail Naganovaf288872019-09-25 13:05:02 -07008402 if (record->getSource()) {
8403 mSource = record->getSource();
8404 }
Eric Laurent83b88082014-06-20 18:31:16 -07008405}
8406
Mikhail Naganov444ecc32018-05-01 17:40:05 -07008407void AudioFlinger::RecordThread::deletePatchTrack(const sp<PatchRecord>& record)
Eric Laurent83b88082014-06-20 18:31:16 -07008408{
8409 Mutex::Autolock _l(mLock);
Mikhail Naganovaf288872019-09-25 13:05:02 -07008410 if (mSource == record->getSource()) {
8411 mSource = mInput;
8412 }
Eric Laurent83b88082014-06-20 18:31:16 -07008413 destroyTrack_l(record);
8414}
8415
Mikhail Naganovdc769682018-05-04 15:34:08 -07008416void AudioFlinger::RecordThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent83b88082014-06-20 18:31:16 -07008417{
Mikhail Naganovdc769682018-05-04 15:34:08 -07008418 ThreadBase::toAudioPortConfig(config);
Eric Laurent83b88082014-06-20 18:31:16 -07008419 config->role = AUDIO_PORT_ROLE_SINK;
8420 config->ext.mix.hw_module = mInput->audioHwDev->handle();
8421 config->ext.mix.usecase.source = mAudioSource;
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07008422 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
8423 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
8424 config->flags.input = mInput->flags;
8425 }
Eric Laurent83b88082014-06-20 18:31:16 -07008426}
Eric Laurent1c333e22014-05-20 10:48:17 -07008427
Eric Laurent6acd1d42017-01-04 14:23:29 -08008428// ----------------------------------------------------------------------------
8429// Mmap
8430// ----------------------------------------------------------------------------
8431
8432AudioFlinger::MmapThreadHandle::MmapThreadHandle(const sp<MmapThread>& thread)
8433 : mThread(thread)
8434{
Phil Burk9fabbf82017-08-03 12:02:00 -07008435 assert(thread != 0); // thread must start non-null and stay non-null
Eric Laurent6acd1d42017-01-04 14:23:29 -08008436}
8437
8438AudioFlinger::MmapThreadHandle::~MmapThreadHandle()
8439{
Phil Burk9fabbf82017-08-03 12:02:00 -07008440 mThread->disconnect();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008441}
8442
8443status_t AudioFlinger::MmapThreadHandle::createMmapBuffer(int32_t minSizeFrames,
8444 struct audio_mmap_buffer_info *info)
8445{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008446 return mThread->createMmapBuffer(minSizeFrames, info);
8447}
8448
8449status_t AudioFlinger::MmapThreadHandle::getMmapPosition(struct audio_mmap_position *position)
8450{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008451 return mThread->getMmapPosition(position);
8452}
8453
Eric Laurenta54f1282017-07-01 19:39:32 -07008454status_t AudioFlinger::MmapThreadHandle::start(const AudioClient& client,
Glenn Kastend3bb6452016-12-05 18:14:37 -08008455 audio_port_handle_t *handle)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008456
8457{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008458 return mThread->start(client, handle);
8459}
8460
8461status_t AudioFlinger::MmapThreadHandle::stop(audio_port_handle_t handle)
8462{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008463 return mThread->stop(handle);
8464}
8465
Eric Laurent18b57012017-02-13 16:23:52 -08008466status_t AudioFlinger::MmapThreadHandle::standby()
8467{
Eric Laurent18b57012017-02-13 16:23:52 -08008468 return mThread->standby();
8469}
8470
Eric Laurent6acd1d42017-01-04 14:23:29 -08008471
8472AudioFlinger::MmapThread::MmapThread(
8473 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabin10d86fd2019-10-31 17:20:42 -07008474 AudioHwDevice *hwDev, sp<StreamHalInterface> stream, bool systemReady)
8475 : ThreadBase(audioFlinger, id, MMAP, systemReady),
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008476 mSessionId(AUDIO_SESSION_NONE),
François Gaffie0c280aa2018-07-25 10:02:15 +02008477 mPortId(AUDIO_PORT_HANDLE_NONE),
Andy Hung2c6c3bb2017-06-16 14:01:45 -07008478 mHalStream(stream), mHalDevice(hwDev->hwDevice()), mAudioHwDev(hwDev),
Eric Laurent67f97292018-04-20 18:05:41 -07008479 mActiveTracks(&this->mLocalLog),
8480 mHalVolFloat(-1.0f), // Initialize to illegal value so it always gets set properly later.
8481 mNoCallbackWarningCount(0)
Eric Laurent6acd1d42017-01-04 14:23:29 -08008482{
Eric Laurent18b57012017-02-13 16:23:52 -08008483 mStandby = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008484 readHalParameters_l();
8485}
8486
8487AudioFlinger::MmapThread::~MmapThread()
8488{
Eric Laurent18b57012017-02-13 16:23:52 -08008489 releaseWakeLock_l();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008490}
8491
8492void AudioFlinger::MmapThread::onFirstRef()
8493{
8494 run(mThreadName, ANDROID_PRIORITY_URGENT_AUDIO);
8495}
8496
8497void AudioFlinger::MmapThread::disconnect()
8498{
Eric Laurent331679c2018-04-16 17:03:16 -07008499 ActiveTracks<MmapTrack> activeTracks;
8500 {
8501 Mutex::Autolock _l(mLock);
8502 for (const sp<MmapTrack> &t : mActiveTracks) {
8503 activeTracks.add(t);
8504 }
8505 }
8506 for (const sp<MmapTrack> &t : activeTracks) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008507 stop(t->portId());
8508 }
Phil Burk9fabbf82017-08-03 12:02:00 -07008509 // This will decrement references and may cause the destruction of this thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08008510 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008511 AudioSystem::releaseOutput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008512 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008513 AudioSystem::releaseInput(mPortId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008514 }
8515}
8516
8517
8518void AudioFlinger::MmapThread::configure(const audio_attributes_t *attr,
8519 audio_stream_type_t streamType __unused,
8520 audio_session_t sessionId,
8521 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008522 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008523 audio_port_handle_t portId)
8524{
8525 mAttr = *attr;
8526 mSessionId = sessionId;
8527 mCallback = callback;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008528 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008529 mPortId = portId;
8530}
8531
8532status_t AudioFlinger::MmapThread::createMmapBuffer(int32_t minSizeFrames,
8533 struct audio_mmap_buffer_info *info)
8534{
8535 if (mHalStream == 0) {
8536 return NO_INIT;
8537 }
Eric Laurent18b57012017-02-13 16:23:52 -08008538 mStandby = true;
8539 acquireWakeLock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008540 return mHalStream->createMmapBuffer(minSizeFrames, info);
8541}
8542
8543status_t AudioFlinger::MmapThread::getMmapPosition(struct audio_mmap_position *position)
8544{
8545 if (mHalStream == 0) {
8546 return NO_INIT;
8547 }
8548 return mHalStream->getMmapPosition(position);
8549}
8550
Eric Laurent331679c2018-04-16 17:03:16 -07008551status_t AudioFlinger::MmapThread::exitStandby()
8552{
8553 status_t ret = mHalStream->start();
8554 if (ret != NO_ERROR) {
8555 ALOGE("%s: error mHalStream->start() = %d for first track", __FUNCTION__, ret);
8556 return ret;
8557 }
8558 mStandby = false;
8559 return NO_ERROR;
8560}
8561
Eric Laurenta54f1282017-07-01 19:39:32 -07008562status_t AudioFlinger::MmapThread::start(const AudioClient& client,
Eric Laurent6acd1d42017-01-04 14:23:29 -08008563 audio_port_handle_t *handle)
8564{
Eric Laurenta54f1282017-07-01 19:39:32 -07008565 ALOGV("%s clientUid %d mStandby %d mPortId %d *handle %d", __FUNCTION__,
8566 client.clientUid, mStandby, mPortId, *handle);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008567 if (mHalStream == 0) {
8568 return NO_INIT;
8569 }
8570
8571 status_t ret;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008572
Eric Laurenta54f1282017-07-01 19:39:32 -07008573 if (*handle == mPortId) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008574 // for the first track, reuse portId and session allocated when the stream was opened
Eric Laurent331679c2018-04-16 17:03:16 -07008575 return exitStandby();
Eric Laurenta54f1282017-07-01 19:39:32 -07008576 }
8577
8578 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
8579
8580 audio_io_handle_t io = mId;
8581 if (isOutput()) {
8582 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8583 config.sample_rate = mSampleRate;
8584 config.channel_mask = mChannelMask;
8585 config.format = mFormat;
8586 audio_stream_type_t stream = streamType();
8587 audio_output_flags_t flags =
8588 (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008589 audio_port_handle_t deviceId = mDeviceId;
Kevin Rocard153f92d2018-12-18 18:33:28 -08008590 std::vector<audio_io_handle_t> secondaryOutputs;
Eric Laurenta54f1282017-07-01 19:39:32 -07008591 ret = AudioSystem::getOutputForAttr(&mAttr, &io,
8592 mSessionId,
8593 &stream,
Nadav Bar766fb022018-01-07 12:18:03 +02008594 client.clientPid,
Eric Laurenta54f1282017-07-01 19:39:32 -07008595 client.clientUid,
8596 &config,
8597 flags,
8598 &deviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08008599 &portId,
8600 &secondaryOutputs);
8601 ALOGD_IF(!secondaryOutputs.empty(),
8602 "MmapThread::start does not support secondary outputs, ignoring them");
Eric Laurent6acd1d42017-01-04 14:23:29 -08008603 } else {
Eric Laurenta54f1282017-07-01 19:39:32 -07008604 audio_config_base_t config;
8605 config.sample_rate = mSampleRate;
8606 config.channel_mask = mChannelMask;
8607 config.format = mFormat;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008608 audio_port_handle_t deviceId = mDeviceId;
Eric Laurenta54f1282017-07-01 19:39:32 -07008609 ret = AudioSystem::getInputForAttr(&mAttr, &io,
Mikhail Naganov2996f672019-04-18 12:29:59 -07008610 RECORD_RIID_INVALID,
Eric Laurenta54f1282017-07-01 19:39:32 -07008611 mSessionId,
8612 client.clientPid,
8613 client.clientUid,
Eric Laurentfee19762018-01-29 18:44:13 -08008614 client.packageName,
Eric Laurenta54f1282017-07-01 19:39:32 -07008615 &config,
8616 AUDIO_INPUT_FLAG_MMAP_NOIRQ,
8617 &deviceId,
8618 &portId);
8619 }
8620 // APM should not chose a different input or output stream for the same set of attributes
8621 // and audo configuration
8622 if (ret != NO_ERROR || io != mId) {
8623 ALOGE("%s: error getting output or input from APM (error %d, io %d expected io %d)",
8624 __FUNCTION__, ret, io, mId);
8625 return BAD_VALUE;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008626 }
8627
8628 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008629 ret = AudioSystem::startOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008630 } else {
Eric Laurent4eb58f12018-12-07 16:41:02 -08008631 ret = AudioSystem::startInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008632 }
8633
Eric Laurent331679c2018-04-16 17:03:16 -07008634 Mutex::Autolock _l(mLock);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008635 // abort if start is rejected by audio policy manager
8636 if (ret != NO_ERROR) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08008637 ALOGE("%s: error start rejected by AudioPolicyManager = %d", __FUNCTION__, ret);
Eric Tan39ec8d62018-07-24 09:49:29 -07008638 if (!mActiveTracks.isEmpty()) {
Eric Laurent331679c2018-04-16 17:03:16 -07008639 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008640 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008641 AudioSystem::releaseOutput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008642 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008643 AudioSystem::releaseInput(portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008644 }
Eric Laurent331679c2018-04-16 17:03:16 -07008645 mLock.lock();
Eric Laurent18b57012017-02-13 16:23:52 -08008646 } else {
8647 mHalStream->stop();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008648 }
8649 return PERMISSION_DENIED;
8650 }
8651
Kevin Rocard1f564ac2018-03-29 13:53:10 -07008652 // Given that MmapThread::mAttr is mutable, should a MmapTrack have attributes ?
8653 sp<MmapTrack> track = new MmapTrack(this, mAttr, mSampleRate, mFormat, mChannelMask, mSessionId,
Eric Laurent09f1ed22019-04-24 17:45:17 -07008654 isOutput(), client.clientUid, client.clientPid,
8655 IPCThreadState::self()->getCallingPid(), portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008656
Eric Laurent4eb58f12018-12-07 16:41:02 -08008657 if (isOutput()) {
8658 // force volume update when a new track is added
8659 mHalVolFloat = -1.0f;
8660 } else if (!track->isSilenced_l()) {
8661 for (const sp<MmapTrack> &t : mActiveTracks) {
8662 if (t->isSilenced_l() && t->uid() != client.clientUid)
8663 t->invalidate();
8664 }
8665 }
8666
8667
Eric Laurent6acd1d42017-01-04 14:23:29 -08008668 mActiveTracks.add(track);
Eric Laurenta54f1282017-07-01 19:39:32 -07008669 sp<EffectChain> chain = getEffectChain_l(mSessionId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008670 if (chain != 0) {
8671 chain->setStrategy(AudioSystem::getStrategyForStream(streamType()));
8672 chain->incTrackCnt();
8673 chain->incActiveTrackCnt();
8674 }
8675
8676 *handle = portId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008677 broadcast_l();
8678
Eric Laurenta54f1282017-07-01 19:39:32 -07008679 ALOGV("%s DONE handle %d stream %p", __FUNCTION__, *handle, mHalStream.get());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008680
8681 return NO_ERROR;
8682}
8683
8684status_t AudioFlinger::MmapThread::stop(audio_port_handle_t handle)
8685{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008686 ALOGV("%s handle %d", __FUNCTION__, handle);
8687
8688 if (mHalStream == 0) {
8689 return NO_INIT;
8690 }
8691
Eric Laurenta54f1282017-07-01 19:39:32 -07008692 if (handle == mPortId) {
8693 mHalStream->stop();
8694 return NO_ERROR;
8695 }
8696
Eric Laurent331679c2018-04-16 17:03:16 -07008697 Mutex::Autolock _l(mLock);
8698
Eric Laurent6acd1d42017-01-04 14:23:29 -08008699 sp<MmapTrack> track;
8700 for (const sp<MmapTrack> &t : mActiveTracks) {
8701 if (handle == t->portId()) {
8702 track = t;
8703 break;
8704 }
8705 }
8706 if (track == 0) {
8707 return BAD_VALUE;
8708 }
8709
8710 mActiveTracks.remove(track);
8711
Eric Laurent331679c2018-04-16 17:03:16 -07008712 mLock.unlock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008713 if (isOutput()) {
Eric Laurentd7fe0862018-07-14 16:48:01 -07008714 AudioSystem::stopOutput(track->portId());
8715 AudioSystem::releaseOutput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008716 } else {
Eric Laurentfee19762018-01-29 18:44:13 -08008717 AudioSystem::stopInput(track->portId());
8718 AudioSystem::releaseInput(track->portId());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008719 }
Eric Laurent331679c2018-04-16 17:03:16 -07008720 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008721
8722 sp<EffectChain> chain = getEffectChain_l(track->sessionId());
8723 if (chain != 0) {
8724 chain->decActiveTrackCnt();
8725 chain->decTrackCnt();
8726 }
8727
8728 broadcast_l();
8729
Eric Laurent6acd1d42017-01-04 14:23:29 -08008730 return NO_ERROR;
8731}
8732
Eric Laurent18b57012017-02-13 16:23:52 -08008733status_t AudioFlinger::MmapThread::standby()
8734{
8735 ALOGV("%s", __FUNCTION__);
8736
8737 if (mHalStream == 0) {
8738 return NO_INIT;
8739 }
Eric Tan39ec8d62018-07-24 09:49:29 -07008740 if (!mActiveTracks.isEmpty()) {
Eric Laurent18b57012017-02-13 16:23:52 -08008741 return INVALID_OPERATION;
8742 }
8743 mHalStream->standby();
8744 mStandby = true;
8745 releaseWakeLock();
8746 return NO_ERROR;
8747}
8748
Eric Laurent6acd1d42017-01-04 14:23:29 -08008749
8750void AudioFlinger::MmapThread::readHalParameters_l()
8751{
8752 status_t result = mHalStream->getAudioProperties(&mSampleRate, &mChannelMask, &mHALFormat);
8753 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving audio properties from HAL: %d", result);
8754 mFormat = mHALFormat;
8755 LOG_ALWAYS_FATAL_IF(!audio_is_linear_pcm(mFormat), "HAL format %#x is not linear pcm", mFormat);
8756 result = mHalStream->getFrameSize(&mFrameSize);
8757 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving frame size from HAL: %d", result);
8758 result = mHalStream->getBufferSize(&mBufferSize);
8759 LOG_ALWAYS_FATAL_IF(result != OK, "Error retrieving buffer size from HAL: %d", result);
8760 mFrameCount = mBufferSize / mFrameSize;
8761}
8762
8763bool AudioFlinger::MmapThread::threadLoop()
8764{
Eric Laurent6acd1d42017-01-04 14:23:29 -08008765 checkSilentMode_l();
8766
8767 const String8 myName(String8::format("thread %p type %d TID %d", this, mType, gettid()));
8768
8769 while (!exitPending())
8770 {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008771 Vector< sp<EffectChain> > effectChains;
8772
Andy Hung13850be2019-03-14 11:33:09 -07008773 { // under Thread lock
8774 Mutex::Autolock _l(mLock);
8775
Eric Laurent6acd1d42017-01-04 14:23:29 -08008776 if (mSignalPending) {
8777 // A signal was raised while we were unlocked
8778 mSignalPending = false;
8779 } else {
8780 if (mConfigEvents.isEmpty()) {
8781 // we're about to wait, flush the binder command buffer
8782 IPCThreadState::self()->flushCommands();
8783
8784 if (exitPending()) {
8785 break;
8786 }
8787
Eric Laurent6acd1d42017-01-04 14:23:29 -08008788 // wait until we have something to do...
8789 ALOGV("%s going to sleep", myName.string());
8790 mWaitWorkCV.wait(mLock);
8791 ALOGV("%s waking up", myName.string());
Eric Laurent6acd1d42017-01-04 14:23:29 -08008792
8793 checkSilentMode_l();
8794
8795 continue;
8796 }
8797 }
8798
8799 processConfigEvents_l();
8800
8801 processVolume_l();
8802
8803 checkInvalidTracks_l();
8804
8805 mActiveTracks.updatePowerState(this);
8806
Kevin Rocard069c2712018-03-29 19:09:14 -07008807 updateMetadata_l();
8808
Eric Laurent6acd1d42017-01-04 14:23:29 -08008809 lockEffectChains_l(effectChains);
Andy Hung13850be2019-03-14 11:33:09 -07008810 } // release Thread lock
8811
Eric Laurent6acd1d42017-01-04 14:23:29 -08008812 for (size_t i = 0; i < effectChains.size(); i ++) {
Andy Hung13850be2019-03-14 11:33:09 -07008813 effectChains[i]->process_l(); // Thread is not locked, but effect chain is locked
Eric Laurent6acd1d42017-01-04 14:23:29 -08008814 }
Andy Hung13850be2019-03-14 11:33:09 -07008815
8816 // enable changes in effect chain, including moving to another thread.
Eric Laurent6acd1d42017-01-04 14:23:29 -08008817 unlockEffectChains(effectChains);
8818 // Effect chains will be actually deleted here if they were removed from
8819 // mEffectChains list during mixing or effects processing
8820 }
8821
8822 threadLoop_exit();
8823
8824 if (!mStandby) {
8825 threadLoop_standby();
8826 mStandby = true;
8827 }
8828
Eric Laurent6acd1d42017-01-04 14:23:29 -08008829 ALOGV("Thread %p type %d exiting", this, mType);
8830 return false;
8831}
8832
8833// checkForNewParameter_l() must be called with ThreadBase::mLock held
8834bool AudioFlinger::MmapThread::checkForNewParameter_l(const String8& keyValuePair,
8835 status_t& status)
8836{
8837 AudioParameter param = AudioParameter(keyValuePair);
8838 int value;
Eric Laurente6e9a482017-07-25 19:26:02 -07008839 bool sendToHal = true;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008840 if (param.getInt(String8(AudioParameter::keyRouting), value) == NO_ERROR) {
jiabin10d86fd2019-10-31 17:20:42 -07008841 LOG_FATAL("Should not happen set routing device in MmapThread");
Eric Laurent6acd1d42017-01-04 14:23:29 -08008842 }
Eric Laurente6e9a482017-07-25 19:26:02 -07008843 if (sendToHal) {
8844 status = mHalStream->setParameters(keyValuePair);
8845 } else {
8846 status = NO_ERROR;
8847 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008848
8849 return false;
8850}
8851
8852String8 AudioFlinger::MmapThread::getParameters(const String8& keys)
8853{
8854 Mutex::Autolock _l(mLock);
8855 String8 out_s8;
8856 if (initCheck() == NO_ERROR && mHalStream->getParameters(keys, &out_s8) == OK) {
8857 return out_s8;
8858 }
8859 return String8();
8860}
8861
Eric Laurent09f1ed22019-04-24 17:45:17 -07008862void AudioFlinger::MmapThread::ioConfigChanged(audio_io_config_event event, pid_t pid,
8863 audio_port_handle_t portId __unused) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008864 sp<AudioIoDescriptor> desc = new AudioIoDescriptor();
8865
8866 desc->mIoHandle = mId;
8867
8868 switch (event) {
8869 case AUDIO_INPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008870 case AUDIO_INPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008871 case AUDIO_INPUT_CONFIG_CHANGED:
8872 case AUDIO_OUTPUT_OPENED:
Eric Laurentad2e7b92017-09-14 20:06:42 -07008873 case AUDIO_OUTPUT_REGISTERED:
Eric Laurent6acd1d42017-01-04 14:23:29 -08008874 case AUDIO_OUTPUT_CONFIG_CHANGED:
8875 desc->mPatch = mPatch;
8876 desc->mChannelMask = mChannelMask;
8877 desc->mSamplingRate = mSampleRate;
8878 desc->mFormat = mFormat;
8879 desc->mFrameCount = mFrameCount;
8880 desc->mFrameCountHAL = mFrameCount;
8881 desc->mLatency = 0;
8882 break;
8883
8884 case AUDIO_INPUT_CLOSED:
8885 case AUDIO_OUTPUT_CLOSED:
8886 default:
8887 break;
8888 }
8889 mAudioFlinger->ioConfigChanged(event, desc, pid);
8890}
8891
8892status_t AudioFlinger::MmapThread::createAudioPatch_l(const struct audio_patch *patch,
8893 audio_patch_handle_t *handle)
8894{
8895 status_t status = NO_ERROR;
8896
8897 // store new device and send to effects
8898 audio_devices_t type = AUDIO_DEVICE_NONE;
8899 audio_port_handle_t deviceId;
jiabin10d86fd2019-10-31 17:20:42 -07008900 AudioDeviceTypeAddrVector sinkDeviceTypeAddrs;
8901 AudioDeviceTypeAddr sourceDeviceTypeAddr;
8902 uint32_t numDevices = 0;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008903 if (isOutput()) {
8904 for (unsigned int i = 0; i < patch->num_sinks; i++) {
jiabin10d86fd2019-10-31 17:20:42 -07008905 LOG_ALWAYS_FATAL_IF(popcount(patch->sinks[i].ext.device.type) > 1
8906 && !mAudioHwDev->supportsAudioPatches(),
8907 "Enumerated device type(%#x) must not be used "
8908 "as it does not support audio patches",
8909 patch->sinks[i].ext.device.type);
Eric Laurent6acd1d42017-01-04 14:23:29 -08008910 type |= patch->sinks[i].ext.device.type;
jiabin10d86fd2019-10-31 17:20:42 -07008911 sinkDeviceTypeAddrs.push_back(AudioDeviceTypeAddr(patch->sinks[i].ext.device.type,
8912 patch->sinks[i].ext.device.address));
Eric Laurent6acd1d42017-01-04 14:23:29 -08008913 }
8914 deviceId = patch->sinks[0].id;
jiabin10d86fd2019-10-31 17:20:42 -07008915 numDevices = mPatch.num_sinks;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008916 } else {
8917 type = patch->sources[0].ext.device.type;
8918 deviceId = patch->sources[0].id;
jiabin10d86fd2019-10-31 17:20:42 -07008919 numDevices = mPatch.num_sources;
8920 sourceDeviceTypeAddr.mType = patch->sources[0].ext.device.type;
8921 sourceDeviceTypeAddr.mAddress = patch->sources[0].ext.device.address;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008922 }
8923
8924 for (size_t i = 0; i < mEffectChains.size(); i++) {
jiabinb8269fd2019-11-11 12:16:27 -08008925 if (isOutput()) {
8926 mEffectChains[i]->setDevices_l(sinkDeviceTypeAddrs);
8927 } else {
8928 mEffectChains[i]->setInputDevice_l(sourceDeviceTypeAddr);
8929 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08008930 }
8931
jiabin10d86fd2019-10-31 17:20:42 -07008932 if (!isOutput()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08008933 // store new source and send to effects
8934 if (mAudioSource != patch->sinks[0].ext.mix.usecase.source) {
8935 mAudioSource = patch->sinks[0].ext.mix.usecase.source;
8936 for (size_t i = 0; i < mEffectChains.size(); i++) {
8937 mEffectChains[i]->setAudioSource_l(mAudioSource);
8938 }
8939 }
8940 }
8941
8942 if (mAudioHwDev->supportsAudioPatches()) {
8943 status = mHalDevice->createAudioPatch(patch->num_sources,
8944 patch->sources,
8945 patch->num_sinks,
8946 patch->sinks,
8947 handle);
8948 } else {
8949 char *address;
8950 if (strcmp(patch->sinks[0].ext.device.address, "") != 0) {
8951 //FIXME: we only support address on first sink with HAL version < 3.0
8952 address = audio_device_address_to_parameter(
8953 patch->sinks[0].ext.device.type,
8954 patch->sinks[0].ext.device.address);
8955 } else {
8956 address = (char *)calloc(1, 1);
8957 }
8958 AudioParameter param = AudioParameter(String8(address));
8959 free(address);
8960 param.addInt(String8(AudioParameter::keyRouting), (int)type);
8961 if (!isOutput()) {
8962 param.addInt(String8(AudioParameter::keyInputSource),
8963 (int)patch->sinks[0].ext.mix.usecase.source);
8964 }
8965 status = mHalStream->setParameters(param.toString());
8966 *handle = AUDIO_PATCH_HANDLE_NONE;
8967 }
8968
jiabin10d86fd2019-10-31 17:20:42 -07008969 if (numDevices == 0 || mDeviceId != deviceId) {
8970 if (isOutput()) {
8971 sendIoConfigEvent_l(AUDIO_OUTPUT_CONFIG_CHANGED);
8972 mOutDeviceTypeAddrs = sinkDeviceTypeAddrs;
8973 } else {
8974 sendIoConfigEvent_l(AUDIO_INPUT_CONFIG_CHANGED);
8975 mInDeviceTypeAddr = sourceDeviceTypeAddr;
8976 }
Phil Burk7f6b40d2017-02-09 13:18:38 -08008977 sp<MmapStreamCallback> callback = mCallback.promote();
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008978 if (mDeviceId != deviceId && callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07008979 mLock.unlock();
Phil Burk7f6b40d2017-02-09 13:18:38 -08008980 callback->onRoutingChanged(deviceId);
Eric Laurent734046e2018-04-16 14:50:52 -07008981 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008982 }
jiabin10d86fd2019-10-31 17:20:42 -07008983 mPatch = *patch;
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07008984 mDeviceId = deviceId;
Eric Laurent6acd1d42017-01-04 14:23:29 -08008985 }
8986 return status;
8987}
8988
8989status_t AudioFlinger::MmapThread::releaseAudioPatch_l(const audio_patch_handle_t handle)
8990{
8991 status_t status = NO_ERROR;
8992
jiabin10d86fd2019-10-31 17:20:42 -07008993 mPatch = audio_patch{};
8994 mOutDeviceTypeAddrs.clear();
8995 mInDeviceTypeAddr.reset();
Eric Laurent6acd1d42017-01-04 14:23:29 -08008996
8997 bool supportsAudioPatches = mHalDevice->supportsAudioPatches(&supportsAudioPatches) == OK ?
8998 supportsAudioPatches : false;
8999
9000 if (supportsAudioPatches) {
9001 status = mHalDevice->releaseAudioPatch(handle);
9002 } else {
9003 AudioParameter param;
9004 param.addInt(String8(AudioParameter::keyRouting), 0);
9005 status = mHalStream->setParameters(param.toString());
9006 }
9007 return status;
9008}
9009
Mikhail Naganovdc769682018-05-04 15:34:08 -07009010void AudioFlinger::MmapThread::toAudioPortConfig(struct audio_port_config *config)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009011{
Mikhail Naganovdc769682018-05-04 15:34:08 -07009012 ThreadBase::toAudioPortConfig(config);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009013 if (isOutput()) {
9014 config->role = AUDIO_PORT_ROLE_SOURCE;
9015 config->ext.mix.hw_module = mAudioHwDev->handle();
9016 config->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
9017 } else {
9018 config->role = AUDIO_PORT_ROLE_SINK;
9019 config->ext.mix.hw_module = mAudioHwDev->handle();
9020 config->ext.mix.usecase.source = mAudioSource;
9021 }
9022}
9023
9024status_t AudioFlinger::MmapThread::addEffectChain_l(const sp<EffectChain>& chain)
9025{
9026 audio_session_t session = chain->sessionId();
9027
9028 ALOGV("addEffectChain_l() %p on thread %p for session %d", chain.get(), this, session);
9029 // Attach all tracks with same session ID to this chain.
9030 // indicate all active tracks in the chain
9031 for (const sp<MmapTrack> &track : mActiveTracks) {
9032 if (session == track->sessionId()) {
9033 chain->incTrackCnt();
9034 chain->incActiveTrackCnt();
9035 }
9036 }
9037
9038 chain->setThread(this);
9039 chain->setInBuffer(nullptr);
9040 chain->setOutBuffer(nullptr);
9041 chain->syncHalEffectsState();
9042
9043 mEffectChains.add(chain);
9044 checkSuspendOnAddEffectChain_l(chain);
9045 return NO_ERROR;
9046}
9047
9048size_t AudioFlinger::MmapThread::removeEffectChain_l(const sp<EffectChain>& chain)
9049{
9050 audio_session_t session = chain->sessionId();
9051
9052 ALOGV("removeEffectChain_l() %p from thread %p for session %d", chain.get(), this, session);
9053
9054 for (size_t i = 0; i < mEffectChains.size(); i++) {
9055 if (chain == mEffectChains[i]) {
9056 mEffectChains.removeAt(i);
9057 // detach all active tracks from the chain
9058 // detach all tracks with same session ID from this chain
9059 for (const sp<MmapTrack> &track : mActiveTracks) {
9060 if (session == track->sessionId()) {
9061 chain->decActiveTrackCnt();
9062 chain->decTrackCnt();
9063 }
9064 }
9065 break;
9066 }
9067 }
9068 return mEffectChains.size();
9069}
9070
Eric Laurent6acd1d42017-01-04 14:23:29 -08009071void AudioFlinger::MmapThread::threadLoop_standby()
9072{
9073 mHalStream->standby();
9074}
9075
9076void AudioFlinger::MmapThread::threadLoop_exit()
9077{
Phil Burk7dce7282017-09-27 13:51:41 -07009078 // Do not call callback->onTearDown() because it is redundant for thread exit
9079 // and because it can cause a recursive mutex lock on stop().
Eric Laurent6acd1d42017-01-04 14:23:29 -08009080}
9081
9082status_t AudioFlinger::MmapThread::setSyncEvent(const sp<SyncEvent>& event __unused)
9083{
9084 return BAD_VALUE;
9085}
9086
9087bool AudioFlinger::MmapThread::isValidSyncEvent(const sp<SyncEvent>& event __unused) const
9088{
9089 return false;
9090}
9091
9092status_t AudioFlinger::MmapThread::checkEffectCompatibility_l(
9093 const effect_descriptor_t *desc, audio_session_t sessionId)
9094{
9095 // No global effect sessions on mmap threads
9096 if (sessionId == AUDIO_SESSION_OUTPUT_MIX || sessionId == AUDIO_SESSION_OUTPUT_STAGE) {
9097 ALOGW("checkEffectCompatibility_l(): global effect %s on record thread %s",
9098 desc->name, mThreadName);
9099 return BAD_VALUE;
9100 }
9101
9102 if (!isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) != EFFECT_FLAG_TYPE_PRE_PROC)) {
9103 ALOGW("checkEffectCompatibility_l(): non pre processing effect %s on capture mmap thread",
9104 desc->name);
9105 return BAD_VALUE;
9106 }
9107 if (isOutput() && ((desc->flags & EFFECT_FLAG_TYPE_MASK) == EFFECT_FLAG_TYPE_PRE_PROC)) {
Glenn Kastend3bb6452016-12-05 18:14:37 -08009108 ALOGW("checkEffectCompatibility_l(): pre processing effect %s created on playback mmap "
9109 "thread", desc->name);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009110 return BAD_VALUE;
9111 }
9112
9113 // Only allow effects without processing load or latency
9114 if ((desc->flags & EFFECT_FLAG_NO_PROCESS_MASK) != EFFECT_FLAG_NO_PROCESS) {
9115 return BAD_VALUE;
9116 }
9117
9118 return NO_ERROR;
9119
9120}
9121
9122void AudioFlinger::MmapThread::checkInvalidTracks_l()
9123{
9124 for (const sp<MmapTrack> &track : mActiveTracks) {
9125 if (track->isInvalid()) {
Phil Burk7f6b40d2017-02-09 13:18:38 -08009126 sp<MmapStreamCallback> callback = mCallback.promote();
9127 if (callback != 0) {
Eric Laurent734046e2018-04-16 14:50:52 -07009128 mLock.unlock();
Eric Laurent331679c2018-04-16 17:03:16 -07009129 callback->onTearDown(track->portId());
Eric Laurent734046e2018-04-16 14:50:52 -07009130 mLock.lock();
Eric Laurent331679c2018-04-16 17:03:16 -07009131 } else if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9132 ALOGW("Could not notify MMAP stream tear down: no onTearDown callback!");
9133 mNoCallbackWarningCount++;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009134 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009135 }
9136 }
9137}
9138
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009139void AudioFlinger::MmapThread::dumpInternals_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009140{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009141 dprintf(fd, " Attributes: content type %d usage %d source %d\n",
9142 mAttr.content_type, mAttr.usage, mAttr.source);
9143 dprintf(fd, " Session: %d port Id: %d\n", mSessionId, mPortId);
Eric Tan39ec8d62018-07-24 09:49:29 -07009144 if (mActiveTracks.isEmpty()) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009145 dprintf(fd, " No active clients\n");
9146 }
9147}
9148
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009149void AudioFlinger::MmapThread::dumpTracks_l(int fd, const Vector<String16>& args __unused)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009150{
Eric Laurent6acd1d42017-01-04 14:23:29 -08009151 String8 result;
Eric Laurent6acd1d42017-01-04 14:23:29 -08009152 size_t numtracks = mActiveTracks.size();
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009153 dprintf(fd, " %zu Tracks\n", numtracks);
9154 const char *prefix = " ";
Eric Laurent6acd1d42017-01-04 14:23:29 -08009155 if (numtracks) {
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009156 result.append(prefix);
Kevin Rocard5f2136e2018-05-11 22:03:00 -07009157 mActiveTracks[0]->appendDumpHeader(result);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009158 for (size_t i = 0; i < numtracks ; ++i) {
9159 sp<MmapTrack> track = mActiveTracks[i];
Andy Hung2c6c3bb2017-06-16 14:01:45 -07009160 result.append(prefix);
9161 track->appendDump(result, true /* active */);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009162 }
9163 } else {
9164 dprintf(fd, "\n");
9165 }
9166 write(fd, result.string(), result.size());
9167}
9168
9169AudioFlinger::MmapPlaybackThread::MmapPlaybackThread(
9170 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabin10d86fd2019-10-31 17:20:42 -07009171 AudioHwDevice *hwDev, AudioStreamOut *output, bool systemReady)
9172 : MmapThread(audioFlinger, id, hwDev, output->stream, systemReady),
Eric Laurent6acd1d42017-01-04 14:23:29 -08009173 mStreamType(AUDIO_STREAM_MUSIC),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009174 mStreamVolume(1.0),
9175 mStreamMute(false),
Phil Burk56ecf3e2018-03-12 15:38:17 -07009176 mOutput(output)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009177{
9178 snprintf(mThreadName, kThreadNameLength, "AudioMmapOut_%X", id);
9179 mChannelCount = audio_channel_count_from_out_mask(mChannelMask);
9180 mMasterVolume = audioFlinger->masterVolume_l();
9181 mMasterMute = audioFlinger->masterMute_l();
9182 if (mAudioHwDev) {
9183 if (mAudioHwDev->canSetMasterVolume()) {
9184 mMasterVolume = 1.0;
9185 }
9186
9187 if (mAudioHwDev->canSetMasterMute()) {
9188 mMasterMute = false;
9189 }
9190 }
9191}
9192
9193void AudioFlinger::MmapPlaybackThread::configure(const audio_attributes_t *attr,
9194 audio_stream_type_t streamType,
9195 audio_session_t sessionId,
9196 const sp<MmapStreamCallback>& callback,
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009197 audio_port_handle_t deviceId,
Eric Laurent6acd1d42017-01-04 14:23:29 -08009198 audio_port_handle_t portId)
9199{
Eric Laurent7aa0ccb2017-08-28 11:12:52 -07009200 MmapThread::configure(attr, streamType, sessionId, callback, deviceId, portId);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009201 mStreamType = streamType;
9202}
9203
9204AudioStreamOut* AudioFlinger::MmapPlaybackThread::clearOutput()
9205{
9206 Mutex::Autolock _l(mLock);
9207 AudioStreamOut *output = mOutput;
9208 mOutput = NULL;
9209 return output;
9210}
9211
9212void AudioFlinger::MmapPlaybackThread::setMasterVolume(float value)
9213{
9214 Mutex::Autolock _l(mLock);
9215 // Don't apply master volume in SW if our HAL can do it for us.
9216 if (mAudioHwDev &&
9217 mAudioHwDev->canSetMasterVolume()) {
9218 mMasterVolume = 1.0;
9219 } else {
9220 mMasterVolume = value;
9221 }
9222}
9223
9224void AudioFlinger::MmapPlaybackThread::setMasterMute(bool muted)
9225{
9226 Mutex::Autolock _l(mLock);
9227 // Don't apply master mute in SW if our HAL can do it for us.
9228 if (mAudioHwDev && mAudioHwDev->canSetMasterMute()) {
9229 mMasterMute = false;
9230 } else {
9231 mMasterMute = muted;
9232 }
9233}
9234
9235void AudioFlinger::MmapPlaybackThread::setStreamVolume(audio_stream_type_t stream, float value)
9236{
9237 Mutex::Autolock _l(mLock);
9238 if (stream == mStreamType) {
9239 mStreamVolume = value;
9240 broadcast_l();
9241 }
9242}
9243
9244float AudioFlinger::MmapPlaybackThread::streamVolume(audio_stream_type_t stream) const
9245{
9246 Mutex::Autolock _l(mLock);
9247 if (stream == mStreamType) {
9248 return mStreamVolume;
9249 }
9250 return 0.0f;
9251}
9252
9253void AudioFlinger::MmapPlaybackThread::setStreamMute(audio_stream_type_t stream, bool muted)
9254{
9255 Mutex::Autolock _l(mLock);
9256 if (stream == mStreamType) {
9257 mStreamMute= muted;
9258 broadcast_l();
9259 }
9260}
9261
9262void AudioFlinger::MmapPlaybackThread::invalidateTracks(audio_stream_type_t streamType)
9263{
9264 Mutex::Autolock _l(mLock);
9265 if (streamType == mStreamType) {
9266 for (const sp<MmapTrack> &track : mActiveTracks) {
9267 track->invalidate();
9268 }
9269 broadcast_l();
9270 }
9271}
9272
9273void AudioFlinger::MmapPlaybackThread::processVolume_l()
9274{
9275 float volume;
9276
9277 if (mMasterMute || mStreamMute) {
9278 volume = 0;
9279 } else {
9280 volume = mMasterVolume * mStreamVolume;
9281 }
9282
9283 if (volume != mHalVolFloat) {
Eric Laurent6acd1d42017-01-04 14:23:29 -08009284
9285 // Convert volumes from float to 8.24
9286 uint32_t vol = (uint32_t)(volume * (1 << 24));
9287
9288 // Delegate volume control to effect in track effect chain if needed
9289 // only one effect chain can be present on DirectOutputThread, so if
9290 // there is one, the track is connected to it
9291 if (!mEffectChains.isEmpty()) {
9292 mEffectChains[0]->setVolume_l(&vol, &vol);
9293 volume = (float)vol / (1 << 24);
9294 }
Eric Laurentdff774a2017-04-21 15:29:38 -07009295 // Try to use HW volume control and fall back to SW control if not implemented
Phil Burk56ecf3e2018-03-12 15:38:17 -07009296 if (mOutput->stream->setVolume(volume, volume) == NO_ERROR) {
9297 mHalVolFloat = volume; // HW volume control worked, so update value.
9298 mNoCallbackWarningCount = 0;
9299 } else {
Eric Laurentdff774a2017-04-21 15:29:38 -07009300 sp<MmapStreamCallback> callback = mCallback.promote();
9301 if (callback != 0) {
9302 int channelCount;
9303 if (isOutput()) {
9304 channelCount = audio_channel_count_from_out_mask(mChannelMask);
9305 } else {
9306 channelCount = audio_channel_count_from_in_mask(mChannelMask);
9307 }
9308 Vector<float> values;
9309 for (int i = 0; i < channelCount; i++) {
9310 values.add(volume);
9311 }
Phil Burk56ecf3e2018-03-12 15:38:17 -07009312 mHalVolFloat = volume; // SW volume control worked, so update value.
9313 mNoCallbackWarningCount = 0;
Eric Laurent734046e2018-04-16 14:50:52 -07009314 mLock.unlock();
9315 callback->onVolumeChanged(mChannelMask, values);
9316 mLock.lock();
Eric Laurent6acd1d42017-01-04 14:23:29 -08009317 } else {
Phil Burk56ecf3e2018-03-12 15:38:17 -07009318 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9319 ALOGW("Could not set MMAP stream volume: no volume callback!");
9320 mNoCallbackWarningCount++;
9321 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009322 }
Eric Laurent6acd1d42017-01-04 14:23:29 -08009323 }
9324 }
9325}
9326
Kevin Rocard069c2712018-03-29 19:09:14 -07009327void AudioFlinger::MmapPlaybackThread::updateMetadata_l()
9328{
9329 if (mOutput == nullptr || mOutput->stream == nullptr ||
9330 !mActiveTracks.readAndClearHasChanged()) {
9331 return;
9332 }
9333 StreamOutHalInterface::SourceMetadata metadata;
9334 for (const sp<MmapTrack> &track : mActiveTracks) {
9335 // No track is invalid as this is called after prepareTrack_l in the same critical section
9336 metadata.tracks.push_back({
9337 .usage = track->attributes().usage,
9338 .content_type = track->attributes().content_type,
9339 .gain = mHalVolFloat, // TODO: propagate from aaudio pre-mix volume
9340 });
9341 }
9342 mOutput->stream->updateSourceMetadata(metadata);
9343}
9344
Eric Laurent6acd1d42017-01-04 14:23:29 -08009345void AudioFlinger::MmapPlaybackThread::checkSilentMode_l()
9346{
9347 if (!mMasterMute) {
9348 char value[PROPERTY_VALUE_MAX];
9349 if (property_get("ro.audio.silent", value, "0") > 0) {
9350 char *endptr;
9351 unsigned long ul = strtoul(value, &endptr, 0);
9352 if (*endptr == '\0' && ul != 0) {
9353 ALOGD("Silence is golden");
9354 // The setprop command will not allow a property to be changed after
9355 // the first time it is set, so we don't have to worry about un-muting.
9356 setMasterMute_l(true);
9357 }
9358 }
9359 }
9360}
9361
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009362void AudioFlinger::MmapPlaybackThread::toAudioPortConfig(struct audio_port_config *config)
9363{
9364 MmapThread::toAudioPortConfig(config);
9365 if (mOutput && mOutput->flags != AUDIO_OUTPUT_FLAG_NONE) {
9366 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9367 config->flags.output = mOutput->flags;
9368 }
9369}
9370
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009371void AudioFlinger::MmapPlaybackThread::dumpInternals_l(int fd, const Vector<String16>& args)
Eric Laurent6acd1d42017-01-04 14:23:29 -08009372{
Mikhail Naganov01dc5ca2019-03-29 10:12:12 -07009373 MmapThread::dumpInternals_l(fd, args);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009374
Glenn Kastend3bb6452016-12-05 18:14:37 -08009375 dprintf(fd, " Stream type: %d Stream volume: %f HAL volume: %f Stream mute %d\n",
9376 mStreamType, mStreamVolume, mHalVolFloat, mStreamMute);
Eric Laurent6acd1d42017-01-04 14:23:29 -08009377 dprintf(fd, " Master volume: %f Master mute %d\n", mMasterVolume, mMasterMute);
9378}
9379
9380AudioFlinger::MmapCaptureThread::MmapCaptureThread(
9381 const sp<AudioFlinger>& audioFlinger, audio_io_handle_t id,
jiabin10d86fd2019-10-31 17:20:42 -07009382 AudioHwDevice *hwDev, AudioStreamIn *input, bool systemReady)
9383 : MmapThread(audioFlinger, id, hwDev, input->stream, systemReady),
Eric Laurent6acd1d42017-01-04 14:23:29 -08009384 mInput(input)
9385{
9386 snprintf(mThreadName, kThreadNameLength, "AudioMmapIn_%X", id);
9387 mChannelCount = audio_channel_count_from_in_mask(mChannelMask);
9388}
9389
Eric Laurent331679c2018-04-16 17:03:16 -07009390status_t AudioFlinger::MmapCaptureThread::exitStandby()
9391{
Phil Burkf054fc32018-12-06 09:45:59 -08009392 {
9393 // mInput might have been cleared by clearInput()
9394 Mutex::Autolock _l(mLock);
9395 if (mInput != nullptr && mInput->stream != nullptr) {
9396 mInput->stream->setGain(1.0f);
9397 }
9398 }
Eric Laurent331679c2018-04-16 17:03:16 -07009399 return MmapThread::exitStandby();
9400}
9401
Eric Laurent6acd1d42017-01-04 14:23:29 -08009402AudioFlinger::AudioStreamIn* AudioFlinger::MmapCaptureThread::clearInput()
9403{
9404 Mutex::Autolock _l(mLock);
9405 AudioStreamIn *input = mInput;
9406 mInput = NULL;
9407 return input;
9408}
Kevin Rocard069c2712018-03-29 19:09:14 -07009409
Eric Laurent331679c2018-04-16 17:03:16 -07009410
9411void AudioFlinger::MmapCaptureThread::processVolume_l()
9412{
9413 bool changed = false;
9414 bool silenced = false;
9415
9416 sp<MmapStreamCallback> callback = mCallback.promote();
9417 if (callback == 0) {
9418 if (mNoCallbackWarningCount < kMaxNoCallbackWarnings) {
9419 ALOGW("Could not set MMAP stream silenced: no onStreamSilenced callback!");
9420 mNoCallbackWarningCount++;
9421 }
9422 }
9423
9424 // After a change occurred in track silenced state, mute capture in audio DSP if at least one
9425 // track is silenced and unmute otherwise
9426 for (size_t i = 0; i < mActiveTracks.size() && !silenced; i++) {
9427 if (!mActiveTracks[i]->getAndSetSilencedNotified_l()) {
9428 changed = true;
9429 silenced = mActiveTracks[i]->isSilenced_l();
9430 }
9431 }
9432
9433 if (changed) {
9434 mInput->stream->setGain(silenced ? 0.0f: 1.0f);
9435 }
9436}
9437
Kevin Rocard069c2712018-03-29 19:09:14 -07009438void AudioFlinger::MmapCaptureThread::updateMetadata_l()
9439{
9440 if (mInput == nullptr || mInput->stream == nullptr ||
9441 !mActiveTracks.readAndClearHasChanged()) {
9442 return;
9443 }
9444 StreamInHalInterface::SinkMetadata metadata;
9445 for (const sp<MmapTrack> &track : mActiveTracks) {
9446 // No track is invalid as this is called after prepareTrack_l in the same critical section
9447 metadata.tracks.push_back({
9448 .source = track->attributes().source,
9449 .gain = 1, // capture tracks do not have volumes
9450 });
9451 }
9452 mInput->stream->updateSinkMetadata(metadata);
9453}
9454
Eric Laurent331679c2018-04-16 17:03:16 -07009455void AudioFlinger::MmapCaptureThread::setRecordSilenced(uid_t uid, bool silenced)
9456{
9457 Mutex::Autolock _l(mLock);
9458 for (size_t i = 0; i < mActiveTracks.size() ; i++) {
9459 if (mActiveTracks[i]->uid() == uid) {
9460 mActiveTracks[i]->setSilenced_l(silenced);
9461 broadcast_l();
9462 }
9463 }
9464}
9465
Mikhail Naganov32abc2b2018-05-24 12:57:11 -07009466void AudioFlinger::MmapCaptureThread::toAudioPortConfig(struct audio_port_config *config)
9467{
9468 MmapThread::toAudioPortConfig(config);
9469 if (mInput && mInput->flags != AUDIO_INPUT_FLAG_NONE) {
9470 config->config_mask |= AUDIO_PORT_CONFIG_FLAGS;
9471 config->flags.input = mInput->flags;
9472 }
9473}
9474
Glenn Kasten63238ef2015-03-02 15:50:29 -08009475} // namespace android