blob: c486630113e2d6fa36cbd95153ef3494b72ac41f [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>
33#ifdef FAST_MIXER_STATISTICS
34#include <cpustats/CentralTendencyStatistics.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
Andy Hung1258c1a2014-05-23 21:22:17 -070039#include <audio_utils/format.h>
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070040#include "AudioMixer.h"
41#include "FastMixer.h"
42
Glenn Kasten7fc97ba2013-07-16 17:18:58 -070043#define FCC_2 2 // fixed channel count assumption
44
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070045namespace android {
46
Glenn Kasten22340022014-04-07 12:04:41 -070047/*static*/ const FastMixerState FastMixer::initial;
48
49FastMixer::FastMixer() : FastThread(),
50 slopNs(0),
51 // fastTrackNames
52 // generations
53 outputSink(NULL),
54 outputSinkGen(0),
55 mixer(NULL),
Andy Hung1258c1a2014-05-23 21:22:17 -070056 mSinkBuffer(NULL),
57 mSinkBufferSize(0),
Andy Hung45d68d32014-05-23 21:13:31 -070058 mMixerBuffer(NULL),
Andy Hung1258c1a2014-05-23 21:22:17 -070059 mMixerBufferSize(0),
60 mMixerBufferFormat(AUDIO_FORMAT_PCM_16_BIT),
Andy Hung45d68d32014-05-23 21:13:31 -070061 mMixerBufferState(UNDEFINED),
Glenn Kasten22340022014-04-07 12:04:41 -070062 format(Format_Invalid),
63 sampleRate(0),
64 fastTracksGen(0),
65 totalNativeFramesWritten(0),
66 // timestamp
67 nativeFramesWrittenButNotPresented(0) // the = 0 is to silence the compiler
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070068{
Glenn Kasten22340022014-04-07 12:04:41 -070069 // FIXME pass initial as parameter to base class constructor, and make it static local
70 previous = &initial;
71 current = &initial;
72
73 mDummyDumpState = &dummyDumpState;
74
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070075 unsigned i;
76 for (i = 0; i < FastMixerState::kMaxFastTracks; ++i) {
77 fastTrackNames[i] = -1;
78 generations[i] = 0;
79 }
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070080#ifdef FAST_MIXER_STATISTICS
Glenn Kasten22340022014-04-07 12:04:41 -070081 oldLoad.tv_sec = 0;
82 oldLoad.tv_nsec = 0;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070083#endif
Glenn Kasten22340022014-04-07 12:04:41 -070084}
85
86FastMixer::~FastMixer()
87{
88}
89
90FastMixerStateQueue* FastMixer::sq()
91{
92 return &mSQ;
93}
94
95const FastThreadState *FastMixer::poll()
96{
97 return mSQ.poll();
98}
99
100void FastMixer::setLog(NBLog::Writer *logWriter)
101{
102 if (mixer != NULL) {
103 mixer->setLog(logWriter);
104 }
105}
106
107void FastMixer::onIdle()
108{
109 preIdle = *(const FastMixerState *)current;
110 current = &preIdle;
111}
112
113void FastMixer::onExit()
114{
115 delete mixer;
Andy Hung1258c1a2014-05-23 21:22:17 -0700116 free(mMixerBuffer);
117 free(mSinkBuffer);
Glenn Kasten22340022014-04-07 12:04:41 -0700118}
119
120bool FastMixer::isSubClassCommand(FastThreadState::Command command)
121{
122 switch ((FastMixerState::Command) command) {
123 case FastMixerState::MIX:
124 case FastMixerState::WRITE:
125 case FastMixerState::MIX_WRITE:
126 return true;
127 default:
128 return false;
129 }
130}
131
132void FastMixer::onStateChange()
133{
134 const FastMixerState * const current = (const FastMixerState *) this->current;
135 const FastMixerState * const previous = (const FastMixerState *) this->previous;
136 FastMixerDumpState * const dumpState = (FastMixerDumpState *) this->dumpState;
137 const size_t frameCount = current->mFrameCount;
138
139 // handle state change here, but since we want to diff the state,
140 // we're prepared for previous == &initial the first time through
141 unsigned previousTrackMask;
142
143 // check for change in output HAL configuration
144 NBAIO_Format previousFormat = format;
145 if (current->mOutputSinkGen != outputSinkGen) {
146 outputSink = current->mOutputSink;
147 outputSinkGen = current->mOutputSinkGen;
148 if (outputSink == NULL) {
149 format = Format_Invalid;
150 sampleRate = 0;
151 } else {
152 format = outputSink->format();
153 sampleRate = Format_sampleRate(format);
154 ALOG_ASSERT(Format_channelCount(format) == FCC_2);
155 }
156 dumpState->mSampleRate = sampleRate;
157 }
158
159 if ((!Format_isEqual(format, previousFormat)) || (frameCount != previous->mFrameCount)) {
160 // FIXME to avoid priority inversion, don't delete here
161 delete mixer;
162 mixer = NULL;
Andy Hung1258c1a2014-05-23 21:22:17 -0700163 free(mMixerBuffer);
Andy Hung45d68d32014-05-23 21:13:31 -0700164 mMixerBuffer = NULL;
Andy Hung1258c1a2014-05-23 21:22:17 -0700165 free(mSinkBuffer);
166 mSinkBuffer = NULL;
Glenn Kasten22340022014-04-07 12:04:41 -0700167 if (frameCount > 0 && sampleRate > 0) {
168 // FIXME new may block for unbounded time at internal mutex of the heap
169 // implementation; it would be better to have normal mixer allocate for us
170 // to avoid blocking here and to prevent possible priority inversion
171 mixer = new AudioMixer(frameCount, sampleRate, FastMixerState::kMaxFastTracks);
Andy Hung1258c1a2014-05-23 21:22:17 -0700172 const size_t mixerFrameSize = FCC_2 * audio_bytes_per_sample(mMixerBufferFormat);
173 mMixerBufferSize = mixerFrameSize * frameCount;
174 (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
175 const size_t sinkFrameSize = FCC_2 * audio_bytes_per_sample(format.mFormat);
176 if (sinkFrameSize > mixerFrameSize) { // need a sink buffer
177 mSinkBufferSize = sinkFrameSize * frameCount;
178 (void)posix_memalign(&mSinkBuffer, 32, mSinkBufferSize);
179 }
Glenn Kasten22340022014-04-07 12:04:41 -0700180 periodNs = (frameCount * 1000000000LL) / sampleRate; // 1.00
181 underrunNs = (frameCount * 1750000000LL) / sampleRate; // 1.75
182 overrunNs = (frameCount * 500000000LL) / sampleRate; // 0.50
183 forceNs = (frameCount * 950000000LL) / sampleRate; // 0.95
184 warmupNs = (frameCount * 500000000LL) / sampleRate; // 0.50
185 } else {
186 periodNs = 0;
187 underrunNs = 0;
188 overrunNs = 0;
189 forceNs = 0;
190 warmupNs = 0;
191 }
Andy Hung45d68d32014-05-23 21:13:31 -0700192 mMixerBufferState = UNDEFINED;
Glenn Kasten22340022014-04-07 12:04:41 -0700193#if !LOG_NDEBUG
194 for (unsigned i = 0; i < FastMixerState::kMaxFastTracks; ++i) {
195 fastTrackNames[i] = -1;
196 }
Glenn Kasten0a14c4c2012-06-13 14:58:49 -0700197#endif
Glenn Kasten22340022014-04-07 12:04:41 -0700198 // we need to reconfigure all active tracks
199 previousTrackMask = 0;
200 fastTracksGen = current->mFastTracksGen - 1;
201 dumpState->mFrameCount = frameCount;
202 } else {
203 previousTrackMask = previous->mTrackMask;
204 }
Glenn Kasten732845c2013-08-23 09:26:31 -0700205
Glenn Kasten22340022014-04-07 12:04:41 -0700206 // check for change in active track set
207 const unsigned currentTrackMask = current->mTrackMask;
208 dumpState->mTrackMask = currentTrackMask;
209 if (current->mFastTracksGen != fastTracksGen) {
Andy Hung45d68d32014-05-23 21:13:31 -0700210 ALOG_ASSERT(mMixerBuffer != NULL);
Glenn Kasten22340022014-04-07 12:04:41 -0700211 int name;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700212
Glenn Kasten22340022014-04-07 12:04:41 -0700213 // process removed tracks first to avoid running out of track names
214 unsigned removedTracks = previousTrackMask & ~currentTrackMask;
215 while (removedTracks != 0) {
216 int i = __builtin_ctz(removedTracks);
217 removedTracks &= ~(1 << i);
218 const FastTrack* fastTrack = &current->mFastTracks[i];
219 ALOG_ASSERT(fastTrack->mBufferProvider == NULL);
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800220 if (mixer != NULL) {
Glenn Kasten22340022014-04-07 12:04:41 -0700221 name = fastTrackNames[i];
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700222 ALOG_ASSERT(name >= 0);
Glenn Kasten22340022014-04-07 12:04:41 -0700223 mixer->deleteTrackName(name);
224 }
225#if !LOG_NDEBUG
226 fastTrackNames[i] = -1;
227#endif
228 // don't reset track dump state, since other side is ignoring it
229 generations[i] = fastTrack->mGeneration;
230 }
231
232 // now process added tracks
233 unsigned addedTracks = currentTrackMask & ~previousTrackMask;
234 while (addedTracks != 0) {
235 int i = __builtin_ctz(addedTracks);
236 addedTracks &= ~(1 << i);
237 const FastTrack* fastTrack = &current->mFastTracks[i];
238 AudioBufferProvider *bufferProvider = fastTrack->mBufferProvider;
239 ALOG_ASSERT(bufferProvider != NULL && fastTrackNames[i] == -1);
240 if (mixer != NULL) {
Andy Hunge8a1ced2014-05-09 15:02:21 -0700241 name = mixer->getTrackName(fastTrack->mChannelMask,
242 fastTrack->mFormat, AUDIO_SESSION_OUTPUT_MIX);
Glenn Kasten22340022014-04-07 12:04:41 -0700243 ALOG_ASSERT(name >= 0);
244 fastTrackNames[i] = name;
245 mixer->setBufferProvider(name, bufferProvider);
246 mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::MAIN_BUFFER,
Andy Hung45d68d32014-05-23 21:13:31 -0700247 (void *) mMixerBuffer);
Glenn Kasten22340022014-04-07 12:04:41 -0700248 // newly allocated track names default to full scale volume
Andy Hung1258c1a2014-05-23 21:22:17 -0700249 mixer->setParameter(
250 name,
251 AudioMixer::TRACK,
252 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hungef7c7fb2014-05-12 16:51:41 -0700253 mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::FORMAT,
254 (void *)(uintptr_t)fastTrack->mFormat);
Glenn Kasten22340022014-04-07 12:04:41 -0700255 mixer->enable(name);
256 }
257 generations[i] = fastTrack->mGeneration;
258 }
259
260 // finally process (potentially) modified tracks; these use the same slot
261 // but may have a different buffer provider or volume provider
262 unsigned modifiedTracks = currentTrackMask & previousTrackMask;
263 while (modifiedTracks != 0) {
264 int i = __builtin_ctz(modifiedTracks);
265 modifiedTracks &= ~(1 << i);
266 const FastTrack* fastTrack = &current->mFastTracks[i];
267 if (fastTrack->mGeneration != generations[i]) {
268 // this track was actually modified
269 AudioBufferProvider *bufferProvider = fastTrack->mBufferProvider;
270 ALOG_ASSERT(bufferProvider != NULL);
271 if (mixer != NULL) {
272 name = fastTrackNames[i];
273 ALOG_ASSERT(name >= 0);
274 mixer->setBufferProvider(name, bufferProvider);
275 if (fastTrack->mVolumeProvider == NULL) {
Andy Hung6be49402014-05-30 10:42:03 -0700276 float f = AudioMixer::UNITY_GAIN_FLOAT;
277 mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME0, &f);
278 mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME1, &f);
Glenn Kasten288ed212012-04-25 17:52:27 -0700279 }
Glenn Kasten22340022014-04-07 12:04:41 -0700280 mixer->setParameter(name, AudioMixer::RESAMPLE,
281 AudioMixer::REMOVE, NULL);
Andy Hung1258c1a2014-05-23 21:22:17 -0700282 mixer->setParameter(
283 name,
284 AudioMixer::TRACK,
285 AudioMixer::MIXER_FORMAT, (void *)mMixerBufferFormat);
Andy Hungef7c7fb2014-05-12 16:51:41 -0700286 mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::FORMAT,
287 (void *)(uintptr_t)fastTrack->mFormat);
Glenn Kasten22340022014-04-07 12:04:41 -0700288 mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::CHANNEL_MASK,
289 (void *)(uintptr_t) fastTrack->mChannelMask);
290 // already enabled
291 }
292 generations[i] = fastTrack->mGeneration;
293 }
294 }
295
296 fastTracksGen = current->mFastTracksGen;
297
298 dumpState->mNumTracks = popcount(currentTrackMask);
299 }
300}
301
302void FastMixer::onWork()
303{
304 const FastMixerState * const current = (const FastMixerState *) this->current;
305 FastMixerDumpState * const dumpState = (FastMixerDumpState *) this->dumpState;
306 const FastMixerState::Command command = this->command;
307 const size_t frameCount = current->mFrameCount;
308
309 if ((command & FastMixerState::MIX) && (mixer != NULL) && isWarm) {
Andy Hungef7c7fb2014-05-12 16:51:41 -0700310 ALOG_ASSERT(mMixerBuffer != NULL);
Glenn Kasten22340022014-04-07 12:04:41 -0700311 // for each track, update volume and check for underrun
312 unsigned currentTrackMask = current->mTrackMask;
313 while (currentTrackMask != 0) {
314 int i = __builtin_ctz(currentTrackMask);
315 currentTrackMask &= ~(1 << i);
316 const FastTrack* fastTrack = &current->mFastTracks[i];
317
318 // Refresh the per-track timestamp
319 if (timestampStatus == NO_ERROR) {
320 uint32_t trackFramesWrittenButNotPresented =
321 nativeFramesWrittenButNotPresented;
322 uint32_t trackFramesWritten = fastTrack->mBufferProvider->framesReleased();
323 // Can't provide an AudioTimestamp before first frame presented,
324 // or during the brief 32-bit wraparound window
325 if (trackFramesWritten >= trackFramesWrittenButNotPresented) {
326 AudioTimestamp perTrackTimestamp;
327 perTrackTimestamp.mPosition =
328 trackFramesWritten - trackFramesWrittenButNotPresented;
329 perTrackTimestamp.mTime = timestamp.mTime;
330 fastTrack->mBufferProvider->onTimestamp(perTrackTimestamp);
331 }
332 }
333
334 int name = fastTrackNames[i];
335 ALOG_ASSERT(name >= 0);
336 if (fastTrack->mVolumeProvider != NULL) {
Glenn Kastenc56f3422014-03-21 17:53:17 -0700337 gain_minifloat_packed_t vlr = fastTrack->mVolumeProvider->getVolumeLR();
Andy Hung6be49402014-05-30 10:42:03 -0700338 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
339 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
340
341 mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME0, &vlf);
342 mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME1, &vrf);
Glenn Kasten22340022014-04-07 12:04:41 -0700343 }
344 // FIXME The current implementation of framesReady() for fast tracks
345 // takes a tryLock, which can block
346 // up to 1 ms. If enough active tracks all blocked in sequence, this would result
347 // in the overall fast mix cycle being delayed. Should use a non-blocking FIFO.
348 size_t framesReady = fastTrack->mBufferProvider->framesReady();
349 if (ATRACE_ENABLED()) {
350 // I wish we had formatted trace names
351 char traceName[16];
352 strcpy(traceName, "fRdy");
353 traceName[4] = i + (i < 10 ? '0' : 'A' - 10);
354 traceName[5] = '\0';
355 ATRACE_INT(traceName, framesReady);
356 }
357 FastTrackDump *ftDump = &dumpState->mTracks[i];
358 FastTrackUnderruns underruns = ftDump->mUnderruns;
359 if (framesReady < frameCount) {
360 if (framesReady == 0) {
361 underruns.mBitFields.mEmpty++;
362 underruns.mBitFields.mMostRecent = UNDERRUN_EMPTY;
363 mixer->disable(name);
Glenn Kasten09474df2012-05-10 14:48:07 -0700364 } else {
Glenn Kasten22340022014-04-07 12:04:41 -0700365 // allow mixing partial buffer
366 underruns.mBitFields.mPartial++;
367 underruns.mBitFields.mMostRecent = UNDERRUN_PARTIAL;
Glenn Kasten288ed212012-04-25 17:52:27 -0700368 mixer->enable(name);
369 }
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700370 } else {
Glenn Kasten22340022014-04-07 12:04:41 -0700371 underruns.mBitFields.mFull++;
372 underruns.mBitFields.mMostRecent = UNDERRUN_FULL;
373 mixer->enable(name);
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700374 }
Glenn Kasten22340022014-04-07 12:04:41 -0700375 ftDump->mUnderruns = underruns;
376 ftDump->mFramesReady = framesReady;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700377 }
378
Glenn Kasten22340022014-04-07 12:04:41 -0700379 int64_t pts;
380 if (outputSink == NULL || (OK != outputSink->getNextWriteTimestamp(&pts))) {
381 pts = AudioBufferProvider::kInvalidPTS;
382 }
383
384 // process() is CPU-bound
385 mixer->process(pts);
Andy Hung45d68d32014-05-23 21:13:31 -0700386 mMixerBufferState = MIXED;
387 } else if (mMixerBufferState == MIXED) {
388 mMixerBufferState = UNDEFINED;
Glenn Kasten22340022014-04-07 12:04:41 -0700389 }
390 //bool didFullWrite = false; // dumpsys could display a count of partial writes
Andy Hung45d68d32014-05-23 21:13:31 -0700391 if ((command & FastMixerState::WRITE) && (outputSink != NULL) && (mMixerBuffer != NULL)) {
392 if (mMixerBufferState == UNDEFINED) {
Andy Hung1258c1a2014-05-23 21:22:17 -0700393 memset(mMixerBuffer, 0, mMixerBufferSize);
Andy Hung45d68d32014-05-23 21:13:31 -0700394 mMixerBufferState = ZEROED;
Glenn Kasten22340022014-04-07 12:04:41 -0700395 }
Andy Hung1258c1a2014-05-23 21:22:17 -0700396 void *buffer = mSinkBuffer != NULL ? mSinkBuffer : mMixerBuffer;
397 if (format.mFormat != mMixerBufferFormat) { // sink format not the same as mixer format
398 memcpy_by_audio_format(buffer, format.mFormat, mMixerBuffer, mMixerBufferFormat,
399 frameCount * Format_channelCount(format));
400 }
Glenn Kasten22340022014-04-07 12:04:41 -0700401 // if non-NULL, then duplicate write() to this non-blocking sink
402 NBAIO_Sink* teeSink;
403 if ((teeSink = current->mTeeSink) != NULL) {
Andy Hung45d68d32014-05-23 21:13:31 -0700404 (void) teeSink->write(mMixerBuffer, frameCount);
Glenn Kasten22340022014-04-07 12:04:41 -0700405 }
406 // FIXME write() is non-blocking and lock-free for a properly implemented NBAIO sink,
407 // but this code should be modified to handle both non-blocking and blocking sinks
408 dumpState->mWriteSequence++;
409 ATRACE_BEGIN("write");
Andy Hung1258c1a2014-05-23 21:22:17 -0700410 ssize_t framesWritten = outputSink->write(buffer, frameCount);
Glenn Kasten22340022014-04-07 12:04:41 -0700411 ATRACE_END();
412 dumpState->mWriteSequence++;
413 if (framesWritten >= 0) {
414 ALOG_ASSERT((size_t) framesWritten <= frameCount);
415 totalNativeFramesWritten += framesWritten;
416 dumpState->mFramesWritten = totalNativeFramesWritten;
417 //if ((size_t) framesWritten == frameCount) {
418 // didFullWrite = true;
419 //}
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700420 } else {
Glenn Kasten22340022014-04-07 12:04:41 -0700421 dumpState->mWriteErrors++;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700422 }
Glenn Kasten22340022014-04-07 12:04:41 -0700423 attemptedWrite = true;
424 // FIXME count # of writes blocked excessively, CPU usage, etc. for dump
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700425
Glenn Kasten22340022014-04-07 12:04:41 -0700426 timestampStatus = outputSink->getTimestamp(timestamp);
427 if (timestampStatus == NO_ERROR) {
428 uint32_t totalNativeFramesPresented = timestamp.mPosition;
429 if (totalNativeFramesPresented <= totalNativeFramesWritten) {
430 nativeFramesWrittenButNotPresented =
431 totalNativeFramesWritten - totalNativeFramesPresented;
432 } else {
433 // HAL reported that more frames were presented than were written
434 timestampStatus = INVALID_OPERATION;
435 }
436 }
437 }
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700438}
439
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700440FastMixerDumpState::FastMixerDumpState(
441#ifdef FAST_MIXER_STATISTICS
442 uint32_t samplingN
443#endif
Glenn Kasten22340022014-04-07 12:04:41 -0700444 ) : FastThreadDumpState(),
445 mWriteSequence(0), mFramesWritten(0),
446 mNumTracks(0), mWriteErrors(0),
447 mSampleRate(0), mFrameCount(0),
Glenn Kasten1295bb4d2012-05-31 07:43:43 -0700448 mTrackMask(0)
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700449{
Glenn Kasten153b9fe2013-07-15 11:23:36 -0700450#ifdef FAST_MIXER_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700451 increaseSamplingN(samplingN);
Glenn Kasten153b9fe2013-07-15 11:23:36 -0700452#endif
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700453}
454
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700455#ifdef FAST_MIXER_STATISTICS
456void FastMixerDumpState::increaseSamplingN(uint32_t samplingN)
457{
458 if (samplingN <= mSamplingN || samplingN > kSamplingN || roundup(samplingN) != samplingN) {
459 return;
460 }
461 uint32_t additional = samplingN - mSamplingN;
462 // sample arrays aren't accessed atomically with respect to the bounds,
463 // so clearing reduces chance for dumpsys to read random uninitialized samples
464 memset(&mMonotonicNs[mSamplingN], 0, sizeof(mMonotonicNs[0]) * additional);
465 memset(&mLoadNs[mSamplingN], 0, sizeof(mLoadNs[0]) * additional);
466#ifdef CPU_FREQUENCY_STATISTICS
467 memset(&mCpukHz[mSamplingN], 0, sizeof(mCpukHz[0]) * additional);
468#endif
469 mSamplingN = samplingN;
470}
471#endif
472
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700473FastMixerDumpState::~FastMixerDumpState()
474{
475}
476
Glenn Kasten1ab212cf2012-09-07 12:58:38 -0700477// helper function called by qsort()
478static int compare_uint32_t(const void *pa, const void *pb)
479{
480 uint32_t a = *(const uint32_t *)pa;
481 uint32_t b = *(const uint32_t *)pb;
482 if (a < b) {
483 return -1;
484 } else if (a > b) {
485 return 1;
486 } else {
487 return 0;
488 }
489}
490
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700491void FastMixerDumpState::dump(int fd) const
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700492{
Glenn Kasten868c0ab2012-06-13 14:59:17 -0700493 if (mCommand == FastMixerState::INITIAL) {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700494 dprintf(fd, " FastMixer not initialized\n");
Glenn Kasten868c0ab2012-06-13 14:59:17 -0700495 return;
496 }
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700497#define COMMAND_MAX 32
498 char string[COMMAND_MAX];
499 switch (mCommand) {
500 case FastMixerState::INITIAL:
501 strcpy(string, "INITIAL");
502 break;
503 case FastMixerState::HOT_IDLE:
504 strcpy(string, "HOT_IDLE");
505 break;
506 case FastMixerState::COLD_IDLE:
507 strcpy(string, "COLD_IDLE");
508 break;
509 case FastMixerState::EXIT:
510 strcpy(string, "EXIT");
511 break;
512 case FastMixerState::MIX:
513 strcpy(string, "MIX");
514 break;
515 case FastMixerState::WRITE:
516 strcpy(string, "WRITE");
517 break;
518 case FastMixerState::MIX_WRITE:
519 strcpy(string, "MIX_WRITE");
520 break;
521 default:
522 snprintf(string, COMMAND_MAX, "%d", mCommand);
523 break;
524 }
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700525 double measuredWarmupMs = (mMeasuredWarmupTs.tv_sec * 1000.0) +
Glenn Kasten288ed212012-04-25 17:52:27 -0700526 (mMeasuredWarmupTs.tv_nsec / 1000000.0);
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700527 double mixPeriodSec = (double) mFrameCount / (double) mSampleRate;
Elliott Hughes87cebad2014-05-22 10:14:43 -0700528 dprintf(fd, " FastMixer command=%s writeSequence=%u framesWritten=%u\n"
529 " numTracks=%u writeErrors=%u underruns=%u overruns=%u\n"
530 " sampleRate=%u frameCount=%zu measuredWarmup=%.3g ms, warmupCycles=%u\n"
531 " mixPeriod=%.2f ms\n",
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700532 string, mWriteSequence, mFramesWritten,
Glenn Kasten21e8c502012-04-12 09:39:42 -0700533 mNumTracks, mWriteErrors, mUnderruns, mOverruns,
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700534 mSampleRate, mFrameCount, measuredWarmupMs, mWarmupCycles,
535 mixPeriodSec * 1e3);
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700536#ifdef FAST_MIXER_STATISTICS
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700537 // find the interval of valid samples
538 uint32_t bounds = mBounds;
539 uint32_t newestOpen = bounds & 0xFFFF;
540 uint32_t oldestClosed = bounds >> 16;
541 uint32_t n = (newestOpen - oldestClosed) & 0xFFFF;
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700542 if (n > mSamplingN) {
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700543 ALOGE("too many samples %u", n);
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700544 n = mSamplingN;
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700545 }
546 // statistics for monotonic (wall clock) time, thread raw CPU load in time, CPU clock frequency,
547 // and adjusted CPU load in MHz normalized for CPU clock frequency
Glenn Kasten0a14c4c2012-06-13 14:58:49 -0700548 CentralTendencyStatistics wall, loadNs;
549#ifdef CPU_FREQUENCY_STATISTICS
550 CentralTendencyStatistics kHz, loadMHz;
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700551 uint32_t previousCpukHz = 0;
Glenn Kasten0a14c4c2012-06-13 14:58:49 -0700552#endif
Glenn Kasten1ab212cf2012-09-07 12:58:38 -0700553 // Assuming a normal distribution for cycle times, three standard deviations on either side of
554 // the mean account for 99.73% of the population. So if we take each tail to be 1/1000 of the
555 // sample set, we get 99.8% combined, or close to three standard deviations.
556 static const uint32_t kTailDenominator = 1000;
557 uint32_t *tail = n >= kTailDenominator ? new uint32_t[n] : NULL;
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700558 // loop over all the samples
Glenn Kasten1ab212cf2012-09-07 12:58:38 -0700559 for (uint32_t j = 0; j < n; ++j) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700560 size_t i = oldestClosed++ & (mSamplingN - 1);
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700561 uint32_t wallNs = mMonotonicNs[i];
Glenn Kasten1ab212cf2012-09-07 12:58:38 -0700562 if (tail != NULL) {
563 tail[j] = wallNs;
564 }
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700565 wall.sample(wallNs);
566 uint32_t sampleLoadNs = mLoadNs[i];
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700567 loadNs.sample(sampleLoadNs);
Glenn Kasten0a14c4c2012-06-13 14:58:49 -0700568#ifdef CPU_FREQUENCY_STATISTICS
569 uint32_t sampleCpukHz = mCpukHz[i];
Glenn Kastenc059bd42012-05-14 17:41:09 -0700570 // skip bad kHz samples
571 if ((sampleCpukHz & ~0xF) != 0) {
572 kHz.sample(sampleCpukHz >> 4);
573 if (sampleCpukHz == previousCpukHz) {
574 double megacycles = (double) sampleLoadNs * (double) (sampleCpukHz >> 4) * 1e-12;
575 double adjMHz = megacycles / mixPeriodSec; // _not_ wallNs * 1e9
576 loadMHz.sample(adjMHz);
577 }
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700578 }
579 previousCpukHz = sampleCpukHz;
Glenn Kasten0a14c4c2012-06-13 14:58:49 -0700580#endif
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700581 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800582 if (n) {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700583 dprintf(fd, " Simple moving statistics over last %.1f seconds:\n",
584 wall.n() * mixPeriodSec);
585 dprintf(fd, " wall clock time in ms per mix cycle:\n"
586 " mean=%.2f min=%.2f max=%.2f stddev=%.2f\n",
587 wall.mean()*1e-6, wall.minimum()*1e-6, wall.maximum()*1e-6,
588 wall.stddev()*1e-6);
589 dprintf(fd, " raw CPU load in us per mix cycle:\n"
590 " mean=%.0f min=%.0f max=%.0f stddev=%.0f\n",
591 loadNs.mean()*1e-3, loadNs.minimum()*1e-3, loadNs.maximum()*1e-3,
592 loadNs.stddev()*1e-3);
Marco Nelissenb2208842014-02-07 14:00:50 -0800593 } else {
Elliott Hughes87cebad2014-05-22 10:14:43 -0700594 dprintf(fd, " No FastMixer statistics available currently\n");
Marco Nelissenb2208842014-02-07 14:00:50 -0800595 }
Glenn Kasten0a14c4c2012-06-13 14:58:49 -0700596#ifdef CPU_FREQUENCY_STATISTICS
Elliott Hughes8b5f6422014-05-22 01:22:06 -0700597 dprintf(fd, " CPU clock frequency in MHz:\n"
598 " mean=%.0f min=%.0f max=%.0f stddev=%.0f\n",
599 kHz.mean()*1e-3, kHz.minimum()*1e-3, kHz.maximum()*1e-3, kHz.stddev()*1e-3);
600 dprintf(fd, " adjusted CPU load in MHz (i.e. normalized for CPU clock frequency):\n"
601 " mean=%.1f min=%.1f max=%.1f stddev=%.1f\n",
602 loadMHz.mean(), loadMHz.minimum(), loadMHz.maximum(), loadMHz.stddev());
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700603#endif
Glenn Kasten1ab212cf2012-09-07 12:58:38 -0700604 if (tail != NULL) {
605 qsort(tail, n, sizeof(uint32_t), compare_uint32_t);
606 // assume same number of tail samples on each side, left and right
607 uint32_t count = n / kTailDenominator;
608 CentralTendencyStatistics left, right;
609 for (uint32_t i = 0; i < count; ++i) {
610 left.sample(tail[i]);
611 right.sample(tail[n - (i + 1)]);
612 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700613 dprintf(fd, " Distribution of mix cycle times in ms for the tails (> ~3 stddev outliers):\n"
614 " left tail: mean=%.2f min=%.2f max=%.2f stddev=%.2f\n"
615 " right tail: mean=%.2f min=%.2f max=%.2f stddev=%.2f\n",
Elliott Hughes8b5f6422014-05-22 01:22:06 -0700616 left.mean()*1e-6, left.minimum()*1e-6, left.maximum()*1e-6, left.stddev()*1e-6,
617 right.mean()*1e-6, right.minimum()*1e-6, right.maximum()*1e-6,
618 right.stddev()*1e-6);
Glenn Kasten1ab212cf2012-09-07 12:58:38 -0700619 delete[] tail;
620 }
Glenn Kasten0a14c4c2012-06-13 14:58:49 -0700621#endif
Glenn Kasten1295bb4d2012-05-31 07:43:43 -0700622 // The active track mask and track states are updated non-atomically.
623 // So if we relied on isActive to decide whether to display,
624 // then we might display an obsolete track or omit an active track.
625 // Instead we always display all tracks, with an indication
626 // of whether we think the track is active.
627 uint32_t trackMask = mTrackMask;
Elliott Hughes87cebad2014-05-22 10:14:43 -0700628 dprintf(fd, " Fast tracks: kMaxFastTracks=%u activeMask=%#x\n",
Glenn Kasten1295bb4d2012-05-31 07:43:43 -0700629 FastMixerState::kMaxFastTracks, trackMask);
Elliott Hughes87cebad2014-05-22 10:14:43 -0700630 dprintf(fd, " Index Active Full Partial Empty Recent Ready\n");
Glenn Kasten1295bb4d2012-05-31 07:43:43 -0700631 for (uint32_t i = 0; i < FastMixerState::kMaxFastTracks; ++i, trackMask >>= 1) {
632 bool isActive = trackMask & 1;
633 const FastTrackDump *ftDump = &mTracks[i];
634 const FastTrackUnderruns& underruns = ftDump->mUnderruns;
635 const char *mostRecent;
636 switch (underruns.mBitFields.mMostRecent) {
637 case UNDERRUN_FULL:
638 mostRecent = "full";
639 break;
640 case UNDERRUN_PARTIAL:
641 mostRecent = "partial";
642 break;
643 case UNDERRUN_EMPTY:
644 mostRecent = "empty";
645 break;
646 default:
647 mostRecent = "?";
648 break;
649 }
Elliott Hughes87cebad2014-05-22 10:14:43 -0700650 dprintf(fd, " %5u %6s %4u %7u %5u %7s %5zu\n", i, isActive ? "yes" : "no",
Glenn Kasten1295bb4d2012-05-31 07:43:43 -0700651 (underruns.mBitFields.mFull) & UNDERRUN_MASK,
652 (underruns.mBitFields.mPartial) & UNDERRUN_MASK,
653 (underruns.mBitFields.mEmpty) & UNDERRUN_MASK,
654 mostRecent, ftDump->mFramesReady);
655 }
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700656}
657
658} // namespace android