blob: c5b9953ba39951de2b0e101df262cf3a87829a62 [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>
Glenn Kastenad8510a2015-02-17 16:24:07 -080030#include <utils/Debug.h>
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070031#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070032#include <utils/Trace.h>
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070033#include <system/audio.h>
Glenn Kasten214b4062015-03-02 14:15:47 -080034#ifdef FAST_THREAD_STATISTICS
Eric Tan5b13ff82018-07-27 11:20:17 -070035#include <audio_utils/Statistics.h>
Glenn Kasten0a14c4c2012-06-13 14:58:49 -070036#ifdef CPU_FREQUENCY_STATISTICS
Glenn Kasten42d45cf2012-05-02 10:34:47 -070037#include <cpustats/ThreadCpuUsage.h>
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070038#endif
Glenn Kasten0a14c4c2012-06-13 14:58:49 -070039#endif
jiabin245cdd92018-12-07 17:55:15 -080040#include <audio_utils/channels.h>
Andy Hung1258c1a2014-05-23 21:22:17 -070041#include <audio_utils/format.h>
jiabin245cdd92018-12-07 17:55:15 -080042#include <audio_utils/mono_blend.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
Glenn Kasten3ab8d662017-04-03 14:35:09 -0700108void FastMixer::setNBLogWriter(NBLog::Writer *logWriter)
Glenn Kasten22340022014-04-07 12:04:41 -0700109{
Glenn Kasten3ab8d662017-04-03 14:35:09 -0700110 // FIXME If mMixer is set or changed prior to this, we don't inform correctly.
111 // Should cache logWriter and re-apply it at the assignment to mMixer.
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800112 if (mMixer != NULL) {
Glenn Kasten3ab8d662017-04-03 14:35:09 -0700113 mMixer->setNBLogWriter(logWriter);
Glenn Kasten22340022014-04-07 12:04:41 -0700114 }
115}
116
117void FastMixer::onIdle()
118{
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800119 mPreIdle = *(const FastMixerState *)mCurrent;
120 mCurrent = &mPreIdle;
Glenn Kasten22340022014-04-07 12:04:41 -0700121}
122
123void FastMixer::onExit()
124{
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800125 delete mMixer;
Andy Hung1258c1a2014-05-23 21:22:17 -0700126 free(mMixerBuffer);
127 free(mSinkBuffer);
Glenn Kasten22340022014-04-07 12:04:41 -0700128}
129
130bool FastMixer::isSubClassCommand(FastThreadState::Command command)
131{
132 switch ((FastMixerState::Command) command) {
133 case FastMixerState::MIX:
134 case FastMixerState::WRITE:
135 case FastMixerState::MIX_WRITE:
136 return true;
137 default:
138 return false;
139 }
140}
141
Andy Hung4d4ca6a2019-02-01 18:23:37 -0800142void FastMixer::updateMixerTrack(int index, Reason reason) {
143 const FastMixerState * const current = (const FastMixerState *) mCurrent;
144 const FastTrack * const fastTrack = &current->mFastTracks[index];
145
146 // check and update generation
147 if (reason == REASON_MODIFY && mGenerations[index] == fastTrack->mGeneration) {
148 return; // no change on an already configured track.
149 }
150 mGenerations[index] = fastTrack->mGeneration;
151
152 // mMixer == nullptr on configuration failure (check done after generation update).
153 if (mMixer == nullptr) {
154 return;
155 }
156
157 switch (reason) {
158 case REASON_REMOVE:
159 mMixer->destroy(index);
160 break;
161 case REASON_ADD: {
162 const status_t status = mMixer->create(
163 index, fastTrack->mChannelMask, fastTrack->mFormat, AUDIO_SESSION_OUTPUT_MIX);
164 LOG_ALWAYS_FATAL_IF(status != NO_ERROR,
165 "%s: cannot create fast track index"
166 " %d, mask %#x, format %#x in AudioMixer",
167 __func__, index, fastTrack->mChannelMask, fastTrack->mFormat);
168 }
169 [[fallthrough]]; // now fallthrough to update the newly created track.
170 case REASON_MODIFY:
171 mMixer->setBufferProvider(index, fastTrack->mBufferProvider);
172
173 float vlf, vrf;
174 if (fastTrack->mVolumeProvider != nullptr) {
175 const gain_minifloat_packed_t vlr = fastTrack->mVolumeProvider->getVolumeLR();
176 vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
177 vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
178 } else {
179 vlf = vrf = AudioMixer::UNITY_GAIN_FLOAT;
180 }
181
182 // set volume to avoid ramp whenever the track is updated (or created).
183 // Note: this does not distinguish from starting fresh or
184 // resuming from a paused state.
185 mMixer->setParameter(index, AudioMixer::VOLUME, AudioMixer::VOLUME0, &vlf);
186 mMixer->setParameter(index, AudioMixer::VOLUME, AudioMixer::VOLUME1, &vrf);
187
188 mMixer->setParameter(index, AudioMixer::RESAMPLE, AudioMixer::REMOVE, nullptr);
189 mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::MAIN_BUFFER,
190 (void *)mMixerBuffer);
191 mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::MIXER_FORMAT,
192 (void *)(uintptr_t)mMixerBufferFormat);
193 mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::FORMAT,
194 (void *)(uintptr_t)fastTrack->mFormat);
195 mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::CHANNEL_MASK,
196 (void *)(uintptr_t)fastTrack->mChannelMask);
197 mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::MIXER_CHANNEL_MASK,
198 (void *)(uintptr_t)mSinkChannelMask);
199 mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::HAPTIC_ENABLED,
200 (void *)(uintptr_t)fastTrack->mHapticPlaybackEnabled);
201 mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::HAPTIC_INTENSITY,
202 (void *)(uintptr_t)fastTrack->mHapticIntensity);
203
204 mMixer->enable(index);
205 break;
206 default:
207 LOG_ALWAYS_FATAL("%s: invalid update reason %d", __func__, reason);
208 }
209}
210
Glenn Kasten22340022014-04-07 12:04:41 -0700211void FastMixer::onStateChange()
212{
Glenn Kasten4dd03b52015-03-03 11:32:04 -0800213 const FastMixerState * const current = (const FastMixerState *) mCurrent;
214 const FastMixerState * const previous = (const FastMixerState *) mPrevious;
215 FastMixerDumpState * const dumpState = (FastMixerDumpState *) mDumpState;
Glenn Kasten22340022014-04-07 12:04:41 -0700216 const size_t frameCount = current->mFrameCount;
217
Andy Hung818e7a32016-02-16 18:08:07 -0800218 // update boottime offset, in case it has changed
219 mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
220 mBoottimeOffset.load();
221
Glenn Kasten22340022014-04-07 12:04:41 -0700222 // handle state change here, but since we want to diff the state,
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800223 // we're prepared for previous == &sInitial the first time through
Glenn Kasten22340022014-04-07 12:04:41 -0700224 unsigned previousTrackMask;
225
226 // check for change in output HAL configuration
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800227 NBAIO_Format previousFormat = mFormat;
228 if (current->mOutputSinkGen != mOutputSinkGen) {
229 mOutputSink = current->mOutputSink;
230 mOutputSinkGen = current->mOutputSinkGen;
jiabin245cdd92018-12-07 17:55:15 -0800231 mSinkChannelMask = current->mSinkChannelMask;
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +0100232 mBalance.setChannelMask(mSinkChannelMask);
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800233 if (mOutputSink == NULL) {
234 mFormat = Format_Invalid;
235 mSampleRate = 0;
Andy Hung9a592762014-07-21 21:56:01 -0700236 mSinkChannelCount = 0;
237 mSinkChannelMask = AUDIO_CHANNEL_NONE;
jiabin245cdd92018-12-07 17:55:15 -0800238 mAudioChannelCount = 0;
Glenn Kasten22340022014-04-07 12:04:41 -0700239 } else {
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800240 mFormat = mOutputSink->format();
241 mSampleRate = Format_sampleRate(mFormat);
242 mSinkChannelCount = Format_channelCount(mFormat);
Andy Hung9a592762014-07-21 21:56:01 -0700243 LOG_ALWAYS_FATAL_IF(mSinkChannelCount > AudioMixer::MAX_NUM_CHANNELS);
244
jiabin245cdd92018-12-07 17:55:15 -0800245 if (mSinkChannelMask == AUDIO_CHANNEL_NONE) {
246 mSinkChannelMask = audio_channel_out_mask_from_count(mSinkChannelCount);
247 }
248 mAudioChannelCount = mSinkChannelCount - audio_channel_count_from_out_mask(
249 mSinkChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Glenn Kasten22340022014-04-07 12:04:41 -0700250 }
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800251 dumpState->mSampleRate = mSampleRate;
Glenn Kasten22340022014-04-07 12:04:41 -0700252 }
253
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800254 if ((!Format_isEqual(mFormat, previousFormat)) || (frameCount != previous->mFrameCount)) {
Glenn Kasten22340022014-04-07 12:04:41 -0700255 // FIXME to avoid priority inversion, don't delete here
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800256 delete mMixer;
257 mMixer = NULL;
Andy Hung1258c1a2014-05-23 21:22:17 -0700258 free(mMixerBuffer);
Andy Hung45d68d32014-05-23 21:13:31 -0700259 mMixerBuffer = NULL;
Andy Hung1258c1a2014-05-23 21:22:17 -0700260 free(mSinkBuffer);
261 mSinkBuffer = NULL;
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800262 if (frameCount > 0 && mSampleRate > 0) {
Glenn Kasten22340022014-04-07 12:04:41 -0700263 // FIXME new may block for unbounded time at internal mutex of the heap
264 // implementation; it would be better to have normal mixer allocate for us
265 // to avoid blocking here and to prevent possible priority inversion
Andy Hung1bc088a2018-02-09 15:57:31 -0800266 mMixer = new AudioMixer(frameCount, mSampleRate);
Glenn Kasten3ab8d662017-04-03 14:35:09 -0700267 // FIXME See the other FIXME at FastMixer::setNBLogWriter()
Eric Tan0513b5d2018-09-17 10:32:48 -0700268 NBLog::thread_params_t params;
269 params.frameCount = frameCount;
270 params.sampleRate = mSampleRate;
271 LOG_THREAD_PARAMS(params);
Andy Hung9a592762014-07-21 21:56:01 -0700272 const size_t mixerFrameSize = mSinkChannelCount
273 * audio_bytes_per_sample(mMixerBufferFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -0700274 mMixerBufferSize = mixerFrameSize * frameCount;
275 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
Andy Hung9a592762014-07-21 21:56:01 -0700276 const size_t sinkFrameSize = mSinkChannelCount
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800277 * audio_bytes_per_sample(mFormat.mFormat);
Andy Hung1258c1a2014-05-23 21:22:17 -0700278 if (sinkFrameSize > mixerFrameSize) { // need a sink buffer
279 mSinkBufferSize = sinkFrameSize * frameCount;
280 (void)posix_memalign(&mSinkBuffer, 32, mSinkBufferSize);
281 }
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800282 mPeriodNs = (frameCount * 1000000000LL) / mSampleRate; // 1.00
283 mUnderrunNs = (frameCount * 1750000000LL) / mSampleRate; // 1.75
284 mOverrunNs = (frameCount * 500000000LL) / mSampleRate; // 0.50
285 mForceNs = (frameCount * 950000000LL) / mSampleRate; // 0.95
286 mWarmupNsMin = (frameCount * 750000000LL) / mSampleRate; // 0.75
287 mWarmupNsMax = (frameCount * 1250000000LL) / mSampleRate; // 1.25
Glenn Kasten22340022014-04-07 12:04:41 -0700288 } else {
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800289 mPeriodNs = 0;
290 mUnderrunNs = 0;
291 mOverrunNs = 0;
292 mForceNs = 0;
293 mWarmupNsMin = 0;
294 mWarmupNsMax = LONG_MAX;
Glenn Kasten22340022014-04-07 12:04:41 -0700295 }
Andy Hung45d68d32014-05-23 21:13:31 -0700296 mMixerBufferState = UNDEFINED;
Glenn Kasten22340022014-04-07 12:04:41 -0700297 // we need to reconfigure all active tracks
298 previousTrackMask = 0;
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800299 mFastTracksGen = current->mFastTracksGen - 1;
Glenn Kasten22340022014-04-07 12:04:41 -0700300 dumpState->mFrameCount = frameCount;
Andy Hung8946a282018-04-19 20:04:56 -0700301#ifdef TEE_SINK
302 mTee.set(mFormat, NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
303 mTee.setId(std::string("_") + std::to_string(mThreadIoHandle) + "_F");
304#endif
Glenn Kasten22340022014-04-07 12:04:41 -0700305 } else {
306 previousTrackMask = previous->mTrackMask;
307 }
Glenn Kasten732845c2013-08-23 09:26:31 -0700308
Glenn Kasten22340022014-04-07 12:04:41 -0700309 // check for change in active track set
310 const unsigned currentTrackMask = current->mTrackMask;
311 dumpState->mTrackMask = currentTrackMask;
Andy Hung4d4ca6a2019-02-01 18:23:37 -0800312 dumpState->mNumTracks = popcount(currentTrackMask);
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800313 if (current->mFastTracksGen != mFastTracksGen) {
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700314
Glenn Kasten22340022014-04-07 12:04:41 -0700315 // process removed tracks first to avoid running out of track names
316 unsigned removedTracks = previousTrackMask & ~currentTrackMask;
317 while (removedTracks != 0) {
318 int i = __builtin_ctz(removedTracks);
319 removedTracks &= ~(1 << i);
Andy Hung4d4ca6a2019-02-01 18:23:37 -0800320 updateMixerTrack(i, REASON_REMOVE);
Glenn Kasten22340022014-04-07 12:04:41 -0700321 // don't reset track dump state, since other side is ignoring it
Glenn Kasten22340022014-04-07 12:04:41 -0700322 }
323
324 // now process added tracks
325 unsigned addedTracks = currentTrackMask & ~previousTrackMask;
326 while (addedTracks != 0) {
327 int i = __builtin_ctz(addedTracks);
328 addedTracks &= ~(1 << i);
Andy Hung4d4ca6a2019-02-01 18:23:37 -0800329 updateMixerTrack(i, REASON_ADD);
Glenn Kasten22340022014-04-07 12:04:41 -0700330 }
331
332 // finally process (potentially) modified tracks; these use the same slot
333 // but may have a different buffer provider or volume provider
334 unsigned modifiedTracks = currentTrackMask & previousTrackMask;
335 while (modifiedTracks != 0) {
336 int i = __builtin_ctz(modifiedTracks);
337 modifiedTracks &= ~(1 << i);
Andy Hung4d4ca6a2019-02-01 18:23:37 -0800338 updateMixerTrack(i, REASON_MODIFY);
Glenn Kasten22340022014-04-07 12:04:41 -0700339 }
340
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800341 mFastTracksGen = current->mFastTracksGen;
Glenn Kasten22340022014-04-07 12:04:41 -0700342 }
343}
344
345void FastMixer::onWork()
346{
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -0700347 // TODO: pass an ID parameter to indicate which time series we want to write to in NBLog.cpp
348 // Or: pass both of these into a single call with a boolean
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700349 const FastMixerState * const current = (const FastMixerState *) mCurrent;
350 FastMixerDumpState * const dumpState = (FastMixerDumpState *) mDumpState;
351
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -0700352 if (mIsWarm) {
Eric Tane98dd6f2018-08-22 18:23:50 -0700353 // Logging timestamps for FastMixer is currently disabled to make memory room for logging
354 // other statistics in FastMixer.
355 // To re-enable, delete the #ifdef FASTMIXER_LOG_HIST_TS lines (and the #endif lines).
356#ifdef FASTMIXER_LOG_HIST_TS
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -0700357 LOG_HIST_TS();
Eric Tane98dd6f2018-08-22 18:23:50 -0700358#endif
359 //ALOGD("Eric FastMixer::onWork() mIsWarm");
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -0700360 } else {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700361 dumpState->mTimestampVerifier.discontinuity();
Eric Tane98dd6f2018-08-22 18:23:50 -0700362 // See comment in if block.
363#ifdef FASTMIXER_LOG_HIST_TS
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -0700364 LOG_AUDIO_STATE();
Eric Tane98dd6f2018-08-22 18:23:50 -0700365#endif
Sanna Catherine de Treville Wager85768942017-07-26 20:17:30 -0700366 }
Glenn Kasten4dd03b52015-03-03 11:32:04 -0800367 const FastMixerState::Command command = mCommand;
Glenn Kasten22340022014-04-07 12:04:41 -0700368 const size_t frameCount = current->mFrameCount;
369
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800370 if ((command & FastMixerState::MIX) && (mMixer != NULL) && mIsWarm) {
Andy Hungef7c7fb2014-05-12 16:51:41 -0700371 ALOG_ASSERT(mMixerBuffer != NULL);
Mohan Kumar947ffa32014-12-12 15:16:46 +0530372
373 // AudioMixer::mState.enabledTracks is undefined if mState.hook == process__validate,
374 // so we keep a side copy of enabledTracks
375 bool anyEnabledTracks = false;
376
Glenn Kasten22340022014-04-07 12:04:41 -0700377 // for each track, update volume and check for underrun
378 unsigned currentTrackMask = current->mTrackMask;
379 while (currentTrackMask != 0) {
380 int i = __builtin_ctz(currentTrackMask);
381 currentTrackMask &= ~(1 << i);
382 const FastTrack* fastTrack = &current->mFastTracks[i];
383
Andy Hung818e7a32016-02-16 18:08:07 -0800384 const int64_t trackFramesWrittenButNotPresented =
385 mNativeFramesWrittenButNotPresented;
386 const int64_t trackFramesWritten = fastTrack->mBufferProvider->framesReleased();
387 ExtendedTimestamp perTrackTimestamp(mTimestamp);
388
389 // Can't provide an ExtendedTimestamp before first frame presented.
390 // Also, timestamp may not go to very last frame on stop().
391 if (trackFramesWritten >= trackFramesWrittenButNotPresented &&
392 perTrackTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] > 0) {
393 perTrackTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
394 trackFramesWritten - trackFramesWrittenButNotPresented;
395 } else {
396 perTrackTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = 0;
397 perTrackTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = -1;
Glenn Kasten22340022014-04-07 12:04:41 -0700398 }
Andy Hung818e7a32016-02-16 18:08:07 -0800399 perTrackTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = trackFramesWritten;
400 fastTrack->mBufferProvider->onTimestamp(perTrackTimestamp);
Glenn Kasten22340022014-04-07 12:04:41 -0700401
Andy Hung1bc088a2018-02-09 15:57:31 -0800402 const int name = i;
Glenn Kasten22340022014-04-07 12:04:41 -0700403 if (fastTrack->mVolumeProvider != NULL) {
Glenn Kastenc56f3422014-03-21 17:53:17 -0700404 gain_minifloat_packed_t vlr = fastTrack->mVolumeProvider->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -0700405 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
406 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
407
Andy Hung4d4ca6a2019-02-01 18:23:37 -0800408 mMixer->setParameter(name, AudioMixer::RAMP_VOLUME, AudioMixer::VOLUME0, &vlf);
409 mMixer->setParameter(name, AudioMixer::RAMP_VOLUME, AudioMixer::VOLUME1, &vrf);
Glenn Kasten22340022014-04-07 12:04:41 -0700410 }
411 // FIXME The current implementation of framesReady() for fast tracks
412 // takes a tryLock, which can block
413 // up to 1 ms. If enough active tracks all blocked in sequence, this would result
414 // in the overall fast mix cycle being delayed. Should use a non-blocking FIFO.
415 size_t framesReady = fastTrack->mBufferProvider->framesReady();
416 if (ATRACE_ENABLED()) {
417 // I wish we had formatted trace names
418 char traceName[16];
419 strcpy(traceName, "fRdy");
420 traceName[4] = i + (i < 10 ? '0' : 'A' - 10);
421 traceName[5] = '\0';
422 ATRACE_INT(traceName, framesReady);
423 }
424 FastTrackDump *ftDump = &dumpState->mTracks[i];
425 FastTrackUnderruns underruns = ftDump->mUnderruns;
426 if (framesReady < frameCount) {
427 if (framesReady == 0) {
428 underruns.mBitFields.mEmpty++;
429 underruns.mBitFields.mMostRecent = UNDERRUN_EMPTY;
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800430 mMixer->disable(name);
Glenn Kasten09474df2012-05-10 14:48:07 -0700431 } else {
Glenn Kasten22340022014-04-07 12:04:41 -0700432 // allow mixing partial buffer
433 underruns.mBitFields.mPartial++;
434 underruns.mBitFields.mMostRecent = UNDERRUN_PARTIAL;
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800435 mMixer->enable(name);
Mohan Kumar947ffa32014-12-12 15:16:46 +0530436 anyEnabledTracks = true;
Glenn Kasten288ed212012-04-25 17:52:27 -0700437 }
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700438 } else {
Glenn Kasten22340022014-04-07 12:04:41 -0700439 underruns.mBitFields.mFull++;
440 underruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800441 mMixer->enable(name);
Mohan Kumar947ffa32014-12-12 15:16:46 +0530442 anyEnabledTracks = true;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700443 }
Glenn Kasten22340022014-04-07 12:04:41 -0700444 ftDump->mUnderruns = underruns;
445 ftDump->mFramesReady = framesReady;
Andy Hungb54c8542016-09-21 12:55:15 -0700446 ftDump->mFramesWritten = trackFramesWritten;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700447 }
448
Mohan Kumar947ffa32014-12-12 15:16:46 +0530449 if (anyEnabledTracks) {
450 // process() is CPU-bound
451 mMixer->process();
452 mMixerBufferState = MIXED;
453 } else if (mMixerBufferState != ZEROED) {
454 mMixerBufferState = UNDEFINED;
455 }
456
Andy Hung45d68d32014-05-23 21:13:31 -0700457 } else if (mMixerBufferState == MIXED) {
458 mMixerBufferState = UNDEFINED;
Glenn Kasten22340022014-04-07 12:04:41 -0700459 }
460 //bool didFullWrite = false; // dumpsys could display a count of partial writes
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800461 if ((command & FastMixerState::WRITE) && (mOutputSink != NULL) && (mMixerBuffer != NULL)) {
Andy Hung45d68d32014-05-23 21:13:31 -0700462 if (mMixerBufferState == UNDEFINED) {
Andy Hung1258c1a2014-05-23 21:22:17 -0700463 memset(mMixerBuffer, 0, mMixerBufferSize);
Andy Hung45d68d32014-05-23 21:13:31 -0700464 mMixerBufferState = ZEROED;
Glenn Kasten22340022014-04-07 12:04:41 -0700465 }
Andy Hung2ddee192015-12-18 17:34:44 -0800466
467 if (mMasterMono.load()) { // memory_order_seq_cst
Glenn Kastenc42e9b42016-03-21 11:35:03 -0700468 mono_blend(mMixerBuffer, mMixerBufferFormat, Format_channelCount(mFormat), frameCount,
469 true /*limit*/);
Andy Hung2ddee192015-12-18 17:34:44 -0800470 }
Richard Folke Tullberg3fae0372017-01-13 09:04:25 +0100471
472 // Balance must take effect after mono conversion.
473 // mBalance detects zero balance within the class for speed (not needed here).
474 mBalance.setBalance(mMasterBalance.load());
475 mBalance.process((float *)mMixerBuffer, frameCount);
476
Glenn Kastenf59497b2015-01-26 16:35:47 -0800477 // prepare the buffer used to write to sink
Andy Hung1258c1a2014-05-23 21:22:17 -0700478 void *buffer = mSinkBuffer != NULL ? mSinkBuffer : mMixerBuffer;
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800479 if (mFormat.mFormat != mMixerBufferFormat) { // sink format not the same as mixer format
480 memcpy_by_audio_format(buffer, mFormat.mFormat, mMixerBuffer, mMixerBufferFormat,
481 frameCount * Format_channelCount(mFormat));
Andy Hung1258c1a2014-05-23 21:22:17 -0700482 }
jiabin245cdd92018-12-07 17:55:15 -0800483 if (mSinkChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) {
484 // When there are haptic channels, the sample data is partially interleaved.
485 // Make the sample data fully interleaved here.
486 adjust_channels_non_destructive(buffer, mAudioChannelCount, buffer, mSinkChannelCount,
487 audio_bytes_per_sample(mFormat.mFormat),
488 frameCount * audio_bytes_per_frame(mAudioChannelCount, mFormat.mFormat));
489 }
Glenn Kasten22340022014-04-07 12:04:41 -0700490 // if non-NULL, then duplicate write() to this non-blocking sink
Andy Hung8946a282018-04-19 20:04:56 -0700491#ifdef TEE_SINK
492 mTee.write(buffer, frameCount);
493#endif
Glenn Kasten22340022014-04-07 12:04:41 -0700494 // FIXME write() is non-blocking and lock-free for a properly implemented NBAIO sink,
495 // but this code should be modified to handle both non-blocking and blocking sinks
496 dumpState->mWriteSequence++;
497 ATRACE_BEGIN("write");
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800498 ssize_t framesWritten = mOutputSink->write(buffer, frameCount);
Glenn Kasten22340022014-04-07 12:04:41 -0700499 ATRACE_END();
500 dumpState->mWriteSequence++;
501 if (framesWritten >= 0) {
502 ALOG_ASSERT((size_t) framesWritten <= frameCount);
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800503 mTotalNativeFramesWritten += framesWritten;
504 dumpState->mFramesWritten = mTotalNativeFramesWritten;
Glenn Kasten22340022014-04-07 12:04:41 -0700505 //if ((size_t) framesWritten == frameCount) {
506 // didFullWrite = true;
507 //}
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700508 } else {
Glenn Kasten22340022014-04-07 12:04:41 -0700509 dumpState->mWriteErrors++;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700510 }
Glenn Kastene4a7ce22015-03-03 11:23:17 -0800511 mAttemptedWrite = true;
Glenn Kasten22340022014-04-07 12:04:41 -0700512 // FIXME count # of writes blocked excessively, CPU usage, etc. for dump
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700513
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700514 if (mIsWarm) {
515 ExtendedTimestamp timestamp; // local
516 status_t status = mOutputSink->getTimestamp(timestamp);
517 if (status == NO_ERROR) {
518 dumpState->mTimestampVerifier.add(
519 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
520 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
521 mSampleRate);
522 const int64_t totalNativeFramesPresented =
Andy Hung818e7a32016-02-16 18:08:07 -0800523 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700524 if (totalNativeFramesPresented <= mTotalNativeFramesWritten) {
525 mNativeFramesWrittenButNotPresented =
526 mTotalNativeFramesWritten - totalNativeFramesPresented;
527 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
528 timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
529 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
530 timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
531 // We don't compensate for server - kernel time difference and
532 // only update latency if we have valid info.
Eric Tane98dd6f2018-08-22 18:23:50 -0700533 const double latencyMs =
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700534 (double)mNativeFramesWrittenButNotPresented * 1000 / mSampleRate;
Eric Tane98dd6f2018-08-22 18:23:50 -0700535 dumpState->mLatencyMs = latencyMs;
536 LOG_LATENCY(latencyMs);
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700537 } else {
538 // HAL reported that more frames were presented than were written
539 mNativeFramesWrittenButNotPresented = 0;
540 status = INVALID_OPERATION;
541 }
Glenn Kasten22340022014-04-07 12:04:41 -0700542 } else {
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700543 dumpState->mTimestampVerifier.error();
Glenn Kasten22340022014-04-07 12:04:41 -0700544 }
Andy Hung2e2c0bb2018-06-11 19:13:11 -0700545 if (status == NO_ERROR) {
546 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] =
547 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
548 } else {
549 // fetch server time if we can't get timestamp
550 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] =
551 systemTime(SYSTEM_TIME_MONOTONIC);
552 // clear out kernel cached position as this may get rapidly stale
553 // if we never get a new valid timestamp
554 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = 0;
555 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = -1;
556 }
Andy Hung818e7a32016-02-16 18:08:07 -0800557 }
Glenn Kasten22340022014-04-07 12:04:41 -0700558 }
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700559}
560
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700561} // namespace android