blob: cd3c743048affae3c3e6a97f486119a37f7e8391 [file] [log] [blame]
Glenn Kasten97b5d0d2012-03-23 18:54:19 -07001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Glenn Kastena3d26282012-11-30 07:57:43 -080017// <IMPORTANT_WARNING>
18// Design rules for threadLoop() are given in the comments at section "Fast mixer thread" of
19// StateQueue.h. In particular, avoid library and system calls except at well-known points.
20// The design rules are only for threadLoop(), and don't apply to FastMixerDumpState methods.
21// </IMPORTANT_WARNING>
22
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070023#define LOG_TAG "FastMixer"
Glenn Kasten7f5d3352013-02-15 23:55:04 +000024//#define LOG_NDEBUG 0
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070025
Alex Rayb3a83642012-11-30 19:42:28 -080026#define ATRACE_TAG ATRACE_TAG_AUDIO
Alex Ray371eb972012-11-30 11:11:54 -080027
Glenn Kasten153b9fe2013-07-15 11:23:36 -070028#include "Configuration.h"
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070029#include <time.h>
30#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070031#include <utils/Trace.h>
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070032#include <system/audio.h>
Glenn Kasten214b4062015-03-02 14:15:47 -080033#ifdef FAST_THREAD_STATISTICS
Eric Tan5b13ff82018-07-27 11:20:17 -070034#include <audio_utils/Statistics.h>
Glenn Kasten0a14c4c2012-06-13 14:58:49 -070035#ifdef CPU_FREQUENCY_STATISTICS
Glenn Kasten42d45cf2012-05-02 10:34:47 -070036#include <cpustats/ThreadCpuUsage.h>
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070037#endif
Glenn Kasten0a14c4c2012-06-13 14:58:49 -070038#endif
jiabin245cdd92018-12-07 17:55:15 -080039#include <audio_utils/channels.h>
Andy Hung1258c1a2014-05-23 21:22:17 -070040#include <audio_utils/format.h>
jiabin245cdd92018-12-07 17:55:15 -080041#include <audio_utils/mono_blend.h>
Glenn Kastenc9a23672020-06-30 12:12:42 -070042#include <cutils/bitops.h>
Andy Hung068561c2017-01-03 17:09:32 -080043#include <media/AudioMixer.h>
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070044#include "FastMixer.h"
Glenn Kasteneef598c2017-04-03 14:41:13 -070045#include "TypedLogger.h"
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070046
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070047namespace android {
48
Glenn Kastene4a7ce22015-03-03 11:23:17 -080049/*static*/ const FastMixerState FastMixer::sInitial;
Glenn Kasten22340022014-04-07 12:04:41 -070050
Andy Hung8946a282018-04-19 20:04:56 -070051FastMixer::FastMixer(audio_io_handle_t parentIoHandle)
52 : FastThread("cycle_ms", "load_us"),
Glenn Kastene4a7ce22015-03-03 11:23:17 -080053 // mFastTrackNames
54 // mGenerations
55 mOutputSink(NULL),
56 mOutputSinkGen(0),
57 mMixer(NULL),
Andy Hung1258c1a2014-05-23 21:22:17 -070058 mSinkBuffer(NULL),
59 mSinkBufferSize(0),
Andy Hung9a592762014-07-21 21:56:01 -070060 mSinkChannelCount(FCC_2),
Andy Hung45d68d32014-05-23 21:13:31 -070061 mMixerBuffer(NULL),
Andy Hung1258c1a2014-05-23 21:22:17 -070062 mMixerBufferSize(0),
Andy Hung45d68d32014-05-23 21:13:31 -070063 mMixerBufferState(UNDEFINED),
Glenn Kastene4a7ce22015-03-03 11:23:17 -080064 mFormat(Format_Invalid),
65 mSampleRate(0),
66 mFastTracksGen(0),
67 mTotalNativeFramesWritten(0),
Glenn Kasten22340022014-04-07 12:04:41 -070068 // timestamp
Andy Hung2ddee192015-12-18 17:34:44 -080069 mNativeFramesWrittenButNotPresented(0), // the = 0 is to silence the compiler
Andy Hung8946a282018-04-19 20:04:56 -070070 mMasterMono(false),
71 mThreadIoHandle(parentIoHandle)
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070072{
Andy Hung8946a282018-04-19 20:04:56 -070073 (void)mThreadIoHandle; // prevent unused warning, see C++17 [[maybe_unused]]
74
Glenn Kastene4a7ce22015-03-03 11:23:17 -080075 // FIXME pass sInitial as parameter to base class constructor, and make it static local
76 mPrevious = &sInitial;
77 mCurrent = &sInitial;
Glenn Kasten22340022014-04-07 12:04:41 -070078
Glenn Kastene4a7ce22015-03-03 11:23:17 -080079 mDummyDumpState = &mDummyFastMixerDumpState;
Andy Hung9a592762014-07-21 21:56:01 -070080 // TODO: Add channel mask to NBAIO_Format.
81 // We assume that the channel mask must be a valid positional channel mask.
82 mSinkChannelMask = audio_channel_out_mask_from_count(mSinkChannelCount);
Glenn Kasten22340022014-04-07 12:04:41 -070083
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070084 unsigned i;
Glenn Kastendc2c50b2016-04-21 08:13:14 -070085 for (i = 0; i < FastMixerState::sMaxFastTracks; ++i) {
Glenn Kastene4a7ce22015-03-03 11:23:17 -080086 mGenerations[i] = 0;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070087 }
Glenn Kasten214b4062015-03-02 14:15:47 -080088#ifdef FAST_THREAD_STATISTICS
Glenn Kastene4a7ce22015-03-03 11:23:17 -080089 mOldLoad.tv_sec = 0;
90 mOldLoad.tv_nsec = 0;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070091#endif
Glenn Kasten22340022014-04-07 12:04:41 -070092}
93
94FastMixer::~FastMixer()
95{
96}
97
98FastMixerStateQueue* FastMixer::sq()
99{
100 return &mSQ;
101}
102
103const FastThreadState *FastMixer::poll()
104{
105 return mSQ.poll();
106}
107
Mikhail Naganov9b6599e2019-07-29 15:23:21 -0700108void FastMixer::setNBLogWriter(NBLog::Writer *logWriter __unused)
Glenn Kasten22340022014-04-07 12:04:41 -0700109{
Glenn Kasten22340022014-04-07 12:04:41 -0700110}
111
112void FastMixer::onIdle()
113{
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800114 mPreIdle = *(const FastMixerState *)mCurrent;
115 mCurrent = &mPreIdle;
Glenn Kasten22340022014-04-07 12:04:41 -0700116}
117
118void FastMixer::onExit()
119{
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800120 delete mMixer;
Andy Hung1258c1a2014-05-23 21:22:17 -0700121 free(mMixerBuffer);
122 free(mSinkBuffer);
Glenn Kasten22340022014-04-07 12:04:41 -0700123}
124
125bool FastMixer::isSubClassCommand(FastThreadState::Command command)
126{
127 switch ((FastMixerState::Command) command) {
128 case FastMixerState::MIX:
129 case FastMixerState::WRITE:
130 case FastMixerState::MIX_WRITE:
131 return true;
132 default:
133 return false;
134 }
135}
136
Andy Hung4d4ca6a2019-02-01 18:23:37 -0800137void FastMixer::updateMixerTrack(int index, Reason reason) {
138 const FastMixerState * const current = (const FastMixerState *) mCurrent;
139 const FastTrack * const fastTrack = &current->mFastTracks[index];
140
141 // check and update generation
142 if (reason == REASON_MODIFY && mGenerations[index] == fastTrack->mGeneration) {
143 return; // no change on an already configured track.
144 }
145 mGenerations[index] = fastTrack->mGeneration;
146
147 // mMixer == nullptr on configuration failure (check done after generation update).
148 if (mMixer == nullptr) {
149 return;
150 }
151
152 switch (reason) {
153 case REASON_REMOVE:
154 mMixer->destroy(index);
155 break;
156 case REASON_ADD: {
157 const status_t status = mMixer->create(
158 index, fastTrack->mChannelMask, fastTrack->mFormat, AUDIO_SESSION_OUTPUT_MIX);
159 LOG_ALWAYS_FATAL_IF(status != NO_ERROR,
160 "%s: cannot create fast track index"
161 " %d, mask %#x, format %#x in AudioMixer",
162 __func__, index, fastTrack->mChannelMask, fastTrack->mFormat);
163 }
164 [[fallthrough]]; // now fallthrough to update the newly created track.
165 case REASON_MODIFY:
166 mMixer->setBufferProvider(index, fastTrack->mBufferProvider);
167
168 float vlf, vrf;
169 if (fastTrack->mVolumeProvider != nullptr) {
170 const gain_minifloat_packed_t vlr = fastTrack->mVolumeProvider->getVolumeLR();
171 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
172 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
173 } else {
174 vlf = vrf = AudioMixer::UNITY_GAIN_FLOAT;
175 }
176
177 // set volume to avoid ramp whenever the track is updated (or created).
178 // Note: this does not distinguish from starting fresh or
179 // resuming from a paused state.
180 mMixer->setParameter(index, AudioMixer::VOLUME, AudioMixer::VOLUME0, &vlf);
181 mMixer->setParameter(index, AudioMixer::VOLUME, AudioMixer::VOLUME1, &vrf);
182
183 mMixer->setParameter(index, AudioMixer::RESAMPLE, AudioMixer::REMOVE, nullptr);
184 mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::MAIN_BUFFER,
185 (void *)mMixerBuffer);
186 mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::MIXER_FORMAT,
187 (void *)(uintptr_t)mMixerBufferFormat);
188 mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::FORMAT,
189 (void *)(uintptr_t)fastTrack->mFormat);
190 mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::CHANNEL_MASK,
191 (void *)(uintptr_t)fastTrack->mChannelMask);
192 mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::MIXER_CHANNEL_MASK,
193 (void *)(uintptr_t)mSinkChannelMask);
194 mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::HAPTIC_ENABLED,
195 (void *)(uintptr_t)fastTrack->mHapticPlaybackEnabled);
196 mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::HAPTIC_INTENSITY,
197 (void *)(uintptr_t)fastTrack->mHapticIntensity);
198
199 mMixer->enable(index);
200 break;
201 default:
202 LOG_ALWAYS_FATAL("%s: invalid update reason %d", __func__, reason);
203 }
204}
205
Glenn Kasten22340022014-04-07 12:04:41 -0700206void FastMixer::onStateChange()
207{
Glenn Kasten4dd03b52015-03-03 11:32:04 -0800208 const FastMixerState * const current = (const FastMixerState *) mCurrent;
209 const FastMixerState * const previous = (const FastMixerState *) mPrevious;
210 FastMixerDumpState * const dumpState = (FastMixerDumpState *) mDumpState;
Glenn Kasten22340022014-04-07 12:04:41 -0700211 const size_t frameCount = current->mFrameCount;
212
Andy Hung818e7a32016-02-16 18:08:07 -0800213 // update boottime offset, in case it has changed
214 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
215 mBoottimeOffset.load();
216
Glenn Kasten22340022014-04-07 12:04:41 -0700217 // handle state change here, but since we want to diff the state,
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800218 // we're prepared for previous == &sInitial the first time through
Glenn Kasten22340022014-04-07 12:04:41 -0700219 unsigned previousTrackMask;
220
221 // check for change in output HAL configuration
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800222 NBAIO_Format previousFormat = mFormat;
223 if (current->mOutputSinkGen != mOutputSinkGen) {
224 mOutputSink = current->mOutputSink;
225 mOutputSinkGen = current->mOutputSinkGen;
jiabin245cdd92018-12-07 17:55:15 -0800226 mSinkChannelMask = current->mSinkChannelMask;
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +0100227 mBalance.setChannelMask(mSinkChannelMask);
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800228 if (mOutputSink == NULL) {
229 mFormat = Format_Invalid;
230 mSampleRate = 0;
Andy Hung9a592762014-07-21 21:56:01 -0700231 mSinkChannelCount = 0;
232 mSinkChannelMask = AUDIO_CHANNEL_NONE;
jiabin245cdd92018-12-07 17:55:15 -0800233 mAudioChannelCount = 0;
Glenn Kasten22340022014-04-07 12:04:41 -0700234 } else {
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800235 mFormat = mOutputSink->format();
236 mSampleRate = Format_sampleRate(mFormat);
237 mSinkChannelCount = Format_channelCount(mFormat);
Andy Hung9a592762014-07-21 21:56:01 -0700238 LOG_ALWAYS_FATAL_IF(mSinkChannelCount > AudioMixer::MAX_NUM_CHANNELS);
239
jiabin245cdd92018-12-07 17:55:15 -0800240 if (mSinkChannelMask == AUDIO_CHANNEL_NONE) {
241 mSinkChannelMask = audio_channel_out_mask_from_count(mSinkChannelCount);
242 }
243 mAudioChannelCount = mSinkChannelCount - audio_channel_count_from_out_mask(
244 mSinkChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Glenn Kasten22340022014-04-07 12:04:41 -0700245 }
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800246 dumpState->mSampleRate = mSampleRate;
Glenn Kasten22340022014-04-07 12:04:41 -0700247 }
248
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800249 if ((!Format_isEqual(mFormat, previousFormat)) || (frameCount != previous->mFrameCount)) {
Glenn Kasten22340022014-04-07 12:04:41 -0700250 // FIXME to avoid priority inversion, don't delete here
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800251 delete mMixer;
252 mMixer = NULL;
Andy Hung1258c1a2014-05-23 21:22:17 -0700253 free(mMixerBuffer);
Andy Hung45d68d32014-05-23 21:13:31 -0700254 mMixerBuffer = NULL;
Andy Hung1258c1a2014-05-23 21:22:17 -0700255 free(mSinkBuffer);
256 mSinkBuffer = NULL;
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800257 if (frameCount > 0 && mSampleRate > 0) {
Glenn Kasten22340022014-04-07 12:04:41 -0700258 // FIXME new may block for unbounded time at internal mutex of the heap
259 // implementation; it would be better to have normal mixer allocate for us
260 // to avoid blocking here and to prevent possible priority inversion
Andy Hung1bc088a2018-02-09 15:57:31 -0800261 mMixer = new AudioMixer(frameCount, mSampleRate);
Glenn Kasten3ab8d662017-04-03 14:35:09 -0700262 // FIXME See the other FIXME at FastMixer::setNBLogWriter()
Eric Tan0513b5d2018-09-17 10:32:48 -0700263 NBLog::thread_params_t params;
264 params.frameCount = frameCount;
265 params.sampleRate = mSampleRate;
266 LOG_THREAD_PARAMS(params);
Andy Hung9a592762014-07-21 21:56:01 -0700267 const size_t mixerFrameSize = mSinkChannelCount
268 * audio_bytes_per_sample(mMixerBufferFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -0700269 mMixerBufferSize = mixerFrameSize * frameCount;
270 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
Andy Hung9a592762014-07-21 21:56:01 -0700271 const size_t sinkFrameSize = mSinkChannelCount
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800272 * audio_bytes_per_sample(mFormat.mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -0700273 if (sinkFrameSize > mixerFrameSize) { // need a sink buffer
274 mSinkBufferSize = sinkFrameSize * frameCount;
275 (void)posix_memalign(&mSinkBuffer, 32, mSinkBufferSize);
276 }
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800277 mPeriodNs = (frameCount * 1000000000LL) / mSampleRate; // 1.00
278 mUnderrunNs = (frameCount * 1750000000LL) / mSampleRate; // 1.75
279 mOverrunNs = (frameCount * 500000000LL) / mSampleRate; // 0.50
280 mForceNs = (frameCount * 950000000LL) / mSampleRate; // 0.95
281 mWarmupNsMin = (frameCount * 750000000LL) / mSampleRate; // 0.75
282 mWarmupNsMax = (frameCount * 1250000000LL) / mSampleRate; // 1.25
Glenn Kasten22340022014-04-07 12:04:41 -0700283 } else {
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800284 mPeriodNs = 0;
285 mUnderrunNs = 0;
286 mOverrunNs = 0;
287 mForceNs = 0;
288 mWarmupNsMin = 0;
289 mWarmupNsMax = LONG_MAX;
Glenn Kasten22340022014-04-07 12:04:41 -0700290 }
Andy Hung45d68d32014-05-23 21:13:31 -0700291 mMixerBufferState = UNDEFINED;
Glenn Kasten22340022014-04-07 12:04:41 -0700292 // we need to reconfigure all active tracks
293 previousTrackMask = 0;
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800294 mFastTracksGen = current->mFastTracksGen - 1;
Glenn Kasten22340022014-04-07 12:04:41 -0700295 dumpState->mFrameCount = frameCount;
Andy Hung8946a282018-04-19 20:04:56 -0700296#ifdef TEE_SINK
297 mTee.set(mFormat, NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
298 mTee.setId(std::string("_") + std::to_string(mThreadIoHandle) + "_F");
299#endif
Glenn Kasten22340022014-04-07 12:04:41 -0700300 } else {
301 previousTrackMask = previous->mTrackMask;
302 }
Glenn Kasten732845c2013-08-23 09:26:31 -0700303
Glenn Kasten22340022014-04-07 12:04:41 -0700304 // check for change in active track set
305 const unsigned currentTrackMask = current->mTrackMask;
306 dumpState->mTrackMask = currentTrackMask;
Andy Hung4d4ca6a2019-02-01 18:23:37 -0800307 dumpState->mNumTracks = popcount(currentTrackMask);
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800308 if (current->mFastTracksGen != mFastTracksGen) {
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700309
Glenn Kasten22340022014-04-07 12:04:41 -0700310 // process removed tracks first to avoid running out of track names
311 unsigned removedTracks = previousTrackMask & ~currentTrackMask;
312 while (removedTracks != 0) {
313 int i = __builtin_ctz(removedTracks);
314 removedTracks &= ~(1 << i);
Andy Hung4d4ca6a2019-02-01 18:23:37 -0800315 updateMixerTrack(i, REASON_REMOVE);
Glenn Kasten22340022014-04-07 12:04:41 -0700316 // don't reset track dump state, since other side is ignoring it
Glenn Kasten22340022014-04-07 12:04:41 -0700317 }
318
319 // now process added tracks
320 unsigned addedTracks = currentTrackMask & ~previousTrackMask;
321 while (addedTracks != 0) {
322 int i = __builtin_ctz(addedTracks);
323 addedTracks &= ~(1 << i);
Andy Hung4d4ca6a2019-02-01 18:23:37 -0800324 updateMixerTrack(i, REASON_ADD);
Glenn Kasten22340022014-04-07 12:04:41 -0700325 }
326
327 // finally process (potentially) modified tracks; these use the same slot
328 // but may have a different buffer provider or volume provider
329 unsigned modifiedTracks = currentTrackMask & previousTrackMask;
330 while (modifiedTracks != 0) {
331 int i = __builtin_ctz(modifiedTracks);
332 modifiedTracks &= ~(1 << i);
Andy Hung4d4ca6a2019-02-01 18:23:37 -0800333 updateMixerTrack(i, REASON_MODIFY);
Glenn Kasten22340022014-04-07 12:04:41 -0700334 }
335
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800336 mFastTracksGen = current->mFastTracksGen;
Glenn Kasten22340022014-04-07 12:04:41 -0700337 }
338}
339
340void FastMixer::onWork()
341{
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -0700342 // TODO: pass an ID parameter to indicate which time series we want to write to in NBLog.cpp
343 // Or: pass both of these into a single call with a boolean
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700344 const FastMixerState * const current = (const FastMixerState *) mCurrent;
345 FastMixerDumpState * const dumpState = (FastMixerDumpState *) mDumpState;
346
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -0700347 if (mIsWarm) {
Eric Tane98dd6f2018-08-22 18:23:50 -0700348 // Logging timestamps for FastMixer is currently disabled to make memory room for logging
349 // other statistics in FastMixer.
350 // To re-enable, delete the #ifdef FASTMIXER_LOG_HIST_TS lines (and the #endif lines).
351#ifdef FASTMIXER_LOG_HIST_TS
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -0700352 LOG_HIST_TS();
Eric Tane98dd6f2018-08-22 18:23:50 -0700353#endif
354 //ALOGD("Eric FastMixer::onWork() mIsWarm");
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -0700355 } else {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700356 dumpState->mTimestampVerifier.discontinuity();
Eric Tane98dd6f2018-08-22 18:23:50 -0700357 // See comment in if block.
358#ifdef FASTMIXER_LOG_HIST_TS
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -0700359 LOG_AUDIO_STATE();
Eric Tane98dd6f2018-08-22 18:23:50 -0700360#endif
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -0700361 }
Glenn Kasten4dd03b52015-03-03 11:32:04 -0800362 const FastMixerState::Command command = mCommand;
Glenn Kasten22340022014-04-07 12:04:41 -0700363 const size_t frameCount = current->mFrameCount;
364
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800365 if ((command & FastMixerState::MIX) && (mMixer != NULL) && mIsWarm) {
Andy Hungef7c7fb2014-05-12 16:51:41 -0700366 ALOG_ASSERT(mMixerBuffer != NULL);
Mohan Kumar947ffa32014-12-12 15:16:46 +0530367
368 // AudioMixer::mState.enabledTracks is undefined if mState.hook == process__validate,
369 // so we keep a side copy of enabledTracks
370 bool anyEnabledTracks = false;
371
Glenn Kasten22340022014-04-07 12:04:41 -0700372 // for each track, update volume and check for underrun
373 unsigned currentTrackMask = current->mTrackMask;
374 while (currentTrackMask != 0) {
375 int i = __builtin_ctz(currentTrackMask);
376 currentTrackMask &= ~(1 << i);
377 const FastTrack* fastTrack = &current->mFastTracks[i];
378
Andy Hung818e7a32016-02-16 18:08:07 -0800379 const int64_t trackFramesWrittenButNotPresented =
380 mNativeFramesWrittenButNotPresented;
381 const int64_t trackFramesWritten = fastTrack->mBufferProvider->framesReleased();
382 ExtendedTimestamp perTrackTimestamp(mTimestamp);
383
384 // Can't provide an ExtendedTimestamp before first frame presented.
385 // Also, timestamp may not go to very last frame on stop().
386 if (trackFramesWritten >= trackFramesWrittenButNotPresented &&
387 perTrackTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] > 0) {
388 perTrackTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
389 trackFramesWritten - trackFramesWrittenButNotPresented;
390 } else {
391 perTrackTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = 0;
392 perTrackTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = -1;
Glenn Kasten22340022014-04-07 12:04:41 -0700393 }
Andy Hung818e7a32016-02-16 18:08:07 -0800394 perTrackTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = trackFramesWritten;
395 fastTrack->mBufferProvider->onTimestamp(perTrackTimestamp);
Glenn Kasten22340022014-04-07 12:04:41 -0700396
Andy Hung1bc088a2018-02-09 15:57:31 -0800397 const int name = i;
Glenn Kasten22340022014-04-07 12:04:41 -0700398 if (fastTrack->mVolumeProvider != NULL) {
Glenn Kastenc56f3422014-03-21 17:53:17 -0700399 gain_minifloat_packed_t vlr = fastTrack->mVolumeProvider->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -0700400 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
401 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
402
Andy Hung4d4ca6a2019-02-01 18:23:37 -0800403 mMixer->setParameter(name, AudioMixer::RAMP_VOLUME, AudioMixer::VOLUME0, &vlf);
404 mMixer->setParameter(name, AudioMixer::RAMP_VOLUME, AudioMixer::VOLUME1, &vrf);
Glenn Kasten22340022014-04-07 12:04:41 -0700405 }
406 // FIXME The current implementation of framesReady() for fast tracks
407 // takes a tryLock, which can block
408 // up to 1 ms. If enough active tracks all blocked in sequence, this would result
409 // in the overall fast mix cycle being delayed. Should use a non-blocking FIFO.
410 size_t framesReady = fastTrack->mBufferProvider->framesReady();
411 if (ATRACE_ENABLED()) {
412 // I wish we had formatted trace names
413 char traceName[16];
414 strcpy(traceName, "fRdy");
415 traceName[4] = i + (i < 10 ? '0' : 'A' - 10);
416 traceName[5] = '\0';
417 ATRACE_INT(traceName, framesReady);
418 }
419 FastTrackDump *ftDump = &dumpState->mTracks[i];
420 FastTrackUnderruns underruns = ftDump->mUnderruns;
421 if (framesReady < frameCount) {
422 if (framesReady == 0) {
423 underruns.mBitFields.mEmpty++;
424 underruns.mBitFields.mMostRecent = UNDERRUN_EMPTY;
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800425 mMixer->disable(name);
Glenn Kasten09474df2012-05-10 14:48:07 -0700426 } else {
Glenn Kasten22340022014-04-07 12:04:41 -0700427 // allow mixing partial buffer
428 underruns.mBitFields.mPartial++;
429 underruns.mBitFields.mMostRecent = UNDERRUN_PARTIAL;
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800430 mMixer->enable(name);
Mohan Kumar947ffa32014-12-12 15:16:46 +0530431 anyEnabledTracks = true;
Glenn Kasten288ed212012-04-25 17:52:27 -0700432 }
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700433 } else {
Glenn Kasten22340022014-04-07 12:04:41 -0700434 underruns.mBitFields.mFull++;
435 underruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800436 mMixer->enable(name);
Mohan Kumar947ffa32014-12-12 15:16:46 +0530437 anyEnabledTracks = true;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700438 }
Glenn Kasten22340022014-04-07 12:04:41 -0700439 ftDump->mUnderruns = underruns;
440 ftDump->mFramesReady = framesReady;
Andy Hungb54c8542016-09-21 12:55:15 -0700441 ftDump->mFramesWritten = trackFramesWritten;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700442 }
443
Mohan Kumar947ffa32014-12-12 15:16:46 +0530444 if (anyEnabledTracks) {
445 // process() is CPU-bound
446 mMixer->process();
447 mMixerBufferState = MIXED;
448 } else if (mMixerBufferState != ZEROED) {
449 mMixerBufferState = UNDEFINED;
450 }
451
Andy Hung45d68d32014-05-23 21:13:31 -0700452 } else if (mMixerBufferState == MIXED) {
453 mMixerBufferState = UNDEFINED;
Glenn Kasten22340022014-04-07 12:04:41 -0700454 }
455 //bool didFullWrite = false; // dumpsys could display a count of partial writes
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800456 if ((command & FastMixerState::WRITE) && (mOutputSink != NULL) && (mMixerBuffer != NULL)) {
Andy Hung45d68d32014-05-23 21:13:31 -0700457 if (mMixerBufferState == UNDEFINED) {
Andy Hung1258c1a2014-05-23 21:22:17 -0700458 memset(mMixerBuffer, 0, mMixerBufferSize);
Andy Hung45d68d32014-05-23 21:13:31 -0700459 mMixerBufferState = ZEROED;
Glenn Kasten22340022014-04-07 12:04:41 -0700460 }
Andy Hung2ddee192015-12-18 17:34:44 -0800461
462 if (mMasterMono.load()) { // memory_order_seq_cst
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700463 mono_blend(mMixerBuffer, mMixerBufferFormat, Format_channelCount(mFormat), frameCount,
464 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -0800465 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +0100466
467 // Balance must take effect after mono conversion.
468 // mBalance detects zero balance within the class for speed (not needed here).
469 mBalance.setBalance(mMasterBalance.load());
470 mBalance.process((float *)mMixerBuffer, frameCount);
471
Glenn Kastenf59497b2015-01-26 16:35:47 -0800472 // prepare the buffer used to write to sink
Andy Hung1258c1a2014-05-23 21:22:17 -0700473 void *buffer = mSinkBuffer != NULL ? mSinkBuffer : mMixerBuffer;
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800474 if (mFormat.mFormat != mMixerBufferFormat) { // sink format not the same as mixer format
475 memcpy_by_audio_format(buffer, mFormat.mFormat, mMixerBuffer, mMixerBufferFormat,
476 frameCount * Format_channelCount(mFormat));
Andy Hung1258c1a2014-05-23 21:22:17 -0700477 }
jiabin245cdd92018-12-07 17:55:15 -0800478 if (mSinkChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) {
479 // When there are haptic channels, the sample data is partially interleaved.
480 // Make the sample data fully interleaved here.
481 adjust_channels_non_destructive(buffer, mAudioChannelCount, buffer, mSinkChannelCount,
482 audio_bytes_per_sample(mFormat.mFormat),
483 frameCount * audio_bytes_per_frame(mAudioChannelCount, mFormat.mFormat));
484 }
Glenn Kasten22340022014-04-07 12:04:41 -0700485 // if non-NULL, then duplicate write() to this non-blocking sink
Andy Hung8946a282018-04-19 20:04:56 -0700486#ifdef TEE_SINK
487 mTee.write(buffer, frameCount);
488#endif
Glenn Kasten22340022014-04-07 12:04:41 -0700489 // FIXME write() is non-blocking and lock-free for a properly implemented NBAIO sink,
490 // but this code should be modified to handle both non-blocking and blocking sinks
491 dumpState->mWriteSequence++;
492 ATRACE_BEGIN("write");
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800493 ssize_t framesWritten = mOutputSink->write(buffer, frameCount);
Glenn Kasten22340022014-04-07 12:04:41 -0700494 ATRACE_END();
495 dumpState->mWriteSequence++;
496 if (framesWritten >= 0) {
497 ALOG_ASSERT((size_t) framesWritten <= frameCount);
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800498 mTotalNativeFramesWritten += framesWritten;
499 dumpState->mFramesWritten = mTotalNativeFramesWritten;
Glenn Kasten22340022014-04-07 12:04:41 -0700500 //if ((size_t) framesWritten == frameCount) {
501 // didFullWrite = true;
502 //}
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700503 } else {
Glenn Kasten22340022014-04-07 12:04:41 -0700504 dumpState->mWriteErrors++;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700505 }
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800506 mAttemptedWrite = true;
Glenn Kasten22340022014-04-07 12:04:41 -0700507 // FIXME count # of writes blocked excessively, CPU usage, etc. for dump
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700508
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700509 if (mIsWarm) {
510 ExtendedTimestamp timestamp; // local
511 status_t status = mOutputSink->getTimestamp(timestamp);
512 if (status == NO_ERROR) {
513 dumpState->mTimestampVerifier.add(
514 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
515 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
516 mSampleRate);
517 const int64_t totalNativeFramesPresented =
Andy Hung818e7a32016-02-16 18:08:07 -0800518 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700519 if (totalNativeFramesPresented <= mTotalNativeFramesWritten) {
520 mNativeFramesWrittenButNotPresented =
521 mTotalNativeFramesWritten - totalNativeFramesPresented;
522 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
523 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
524 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
525 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
526 // We don't compensate for server - kernel time difference and
527 // only update latency if we have valid info.
Eric Tane98dd6f2018-08-22 18:23:50 -0700528 const double latencyMs =
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700529 (double)mNativeFramesWrittenButNotPresented * 1000 / mSampleRate;
Eric Tane98dd6f2018-08-22 18:23:50 -0700530 dumpState->mLatencyMs = latencyMs;
531 LOG_LATENCY(latencyMs);
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700532 } else {
533 // HAL reported that more frames were presented than were written
534 mNativeFramesWrittenButNotPresented = 0;
535 status = INVALID_OPERATION;
536 }
Glenn Kasten22340022014-04-07 12:04:41 -0700537 } else {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700538 dumpState->mTimestampVerifier.error();
Glenn Kasten22340022014-04-07 12:04:41 -0700539 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700540 if (status == NO_ERROR) {
541 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] =
542 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
543 } else {
544 // fetch server time if we can't get timestamp
545 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] =
546 systemTime(SYSTEM_TIME_MONOTONIC);
547 // clear out kernel cached position as this may get rapidly stale
548 // if we never get a new valid timestamp
549 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = 0;
550 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = -1;
551 }
Andy Hung818e7a32016-02-16 18:08:07 -0800552 }
Glenn Kasten22340022014-04-07 12:04:41 -0700553 }
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700554}
555
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700556} // namespace android