blob: 90122e00d08fc7486dfdb7b8c3da94e56da2d882 [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 <sys/atomics.h>
30#include <time.h>
31#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>
34#ifdef FAST_MIXER_STATISTICS
35#include <cpustats/CentralTendencyStatistics.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
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070040#include "AudioMixer.h"
41#include "FastMixer.h"
42
43#define FAST_HOT_IDLE_NS 1000000L // 1 ms: time to sleep while hot idling
44#define FAST_DEFAULT_NS 999999999L // ~1 sec: default time to sleep
Glenn Kasteneb157162012-06-13 14:59:07 -070045#define MIN_WARMUP_CYCLES 2 // minimum number of loop cycles to wait for warmup
Glenn Kasten288ed212012-04-25 17:52:27 -070046#define MAX_WARMUP_CYCLES 10 // maximum number of loop cycles to wait for warmup
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070047
Glenn Kasten7fc97ba2013-07-16 17:18:58 -070048#define FCC_2 2 // fixed channel count assumption
49
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070050namespace android {
51
52// Fast mixer thread
53bool FastMixer::threadLoop()
54{
55 static const FastMixerState initial;
56 const FastMixerState *previous = &initial, *current = &initial;
57 FastMixerState preIdle; // copy of state before we went into idle
58 struct timespec oldTs = {0, 0};
59 bool oldTsValid = false;
60 long slopNs = 0; // accumulated time we've woken up too early (> 0) or too late (< 0)
61 long sleepNs = -1; // -1: busy wait, 0: sched_yield, > 0: nanosleep
62 int fastTrackNames[FastMixerState::kMaxFastTracks]; // handles used by mixer to identify tracks
63 int generations[FastMixerState::kMaxFastTracks]; // last observed mFastTracks[i].mGeneration
64 unsigned i;
65 for (i = 0; i < FastMixerState::kMaxFastTracks; ++i) {
66 fastTrackNames[i] = -1;
67 generations[i] = 0;
68 }
69 NBAIO_Sink *outputSink = NULL;
70 int outputSinkGen = 0;
71 AudioMixer* mixer = NULL;
72 short *mixBuffer = NULL;
73 enum {UNDEFINED, MIXED, ZEROED} mixBufferState = UNDEFINED;
74 NBAIO_Format format = Format_Invalid;
75 unsigned sampleRate = 0;
76 int fastTracksGen = 0;
77 long periodNs = 0; // expected period; the time required to render one mix buffer
Glenn Kasten288ed212012-04-25 17:52:27 -070078 long underrunNs = 0; // underrun likely when write cycle is greater than this value
79 long overrunNs = 0; // overrun likely when write cycle is less than this value
Glenn Kasten972af222012-06-13 17:14:03 -070080 long forceNs = 0; // if overrun detected, force the write cycle to take this much time
Glenn Kasten288ed212012-04-25 17:52:27 -070081 long warmupNs = 0; // warmup complete when write cycle is greater than to this value
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070082 FastMixerDumpState dummyDumpState, *dumpState = &dummyDumpState;
83 bool ignoreNextOverrun = true; // used to ignore initial overrun and first after an underrun
84#ifdef FAST_MIXER_STATISTICS
Glenn Kasten42d45cf2012-05-02 10:34:47 -070085 struct timespec oldLoad = {0, 0}; // previous value of clock_gettime(CLOCK_THREAD_CPUTIME_ID)
86 bool oldLoadValid = false; // whether oldLoad is valid
87 uint32_t bounds = 0;
Glenn Kasten4182c4e2013-07-15 14:45:07 -070088 bool full = false; // whether we have collected at least mSamplingN samples
Glenn Kasten0a14c4c2012-06-13 14:58:49 -070089#ifdef CPU_FREQUENCY_STATISTICS
Glenn Kasten42d45cf2012-05-02 10:34:47 -070090 ThreadCpuUsage tcu; // for reading the current CPU clock frequency in kHz
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070091#endif
Glenn Kasten0a14c4c2012-06-13 14:58:49 -070092#endif
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070093 unsigned coldGen = 0; // last observed mColdGen
Glenn Kasten288ed212012-04-25 17:52:27 -070094 bool isWarm = false; // true means ready to mix, false means wait for warmup before mixing
95 struct timespec measuredWarmupTs = {0, 0}; // how long did it take for warmup to complete
96 uint32_t warmupCycles = 0; // counter of number of loop cycles required to warmup
Glenn Kastenfbae5da2012-05-21 09:17:20 -070097 NBAIO_Sink* teeSink = NULL; // if non-NULL, then duplicate write() to this non-blocking sink
Glenn Kasten9e58b552013-01-18 15:09:48 -080098 NBLog::Writer dummyLogWriter, *logWriter = &dummyLogWriter;
Glenn Kasten732845c2013-08-23 09:26:31 -070099 uint32_t totalNativeFramesWritten = 0; // copied to dumpState->mFramesWritten
100
101 // next 2 fields are valid only when timestampStatus == NO_ERROR
102 AudioTimestamp timestamp;
103 uint32_t nativeFramesWrittenButNotPresented = 0; // the = 0 is to silence the compiler
104 status_t timestampStatus = INVALID_OPERATION;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700105
106 for (;;) {
107
108 // either nanosleep, sched_yield, or busy wait
109 if (sleepNs >= 0) {
110 if (sleepNs > 0) {
111 ALOG_ASSERT(sleepNs < 1000000000);
112 const struct timespec req = {0, sleepNs};
113 nanosleep(&req, NULL);
114 } else {
115 sched_yield();
116 }
117 }
118 // default to long sleep for next cycle
119 sleepNs = FAST_DEFAULT_NS;
120
121 // poll for state change
122 const FastMixerState *next = mSQ.poll();
123 if (next == NULL) {
124 // continue to use the default initial state until a real state is available
125 ALOG_ASSERT(current == &initial && previous == &initial);
126 next = current;
127 }
128
129 FastMixerState::Command command = next->mCommand;
130 if (next != current) {
131
132 // As soon as possible of learning of a new dump area, start using it
133 dumpState = next->mDumpState != NULL ? next->mDumpState : &dummyDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -0700134 teeSink = next->mTeeSink;
Glenn Kasten9e58b552013-01-18 15:09:48 -0800135 logWriter = next->mNBLogWriter != NULL ? next->mNBLogWriter : &dummyLogWriter;
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800136 if (mixer != NULL) {
137 mixer->setLog(logWriter);
138 }
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700139
140 // We want to always have a valid reference to the previous (non-idle) state.
141 // However, the state queue only guarantees access to current and previous states.
142 // So when there is a transition from a non-idle state into an idle state, we make a
143 // copy of the last known non-idle state so it is still available on return from idle.
144 // The possible transitions are:
145 // non-idle -> non-idle update previous from current in-place
146 // non-idle -> idle update previous from copy of current
147 // idle -> idle don't update previous
148 // idle -> non-idle don't update previous
149 if (!(current->mCommand & FastMixerState::IDLE)) {
150 if (command & FastMixerState::IDLE) {
151 preIdle = *current;
152 current = &preIdle;
153 oldTsValid = false;
Glenn Kasten153b9fe2013-07-15 11:23:36 -0700154#ifdef FAST_MIXER_STATISTICS
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700155 oldLoadValid = false;
Glenn Kasten153b9fe2013-07-15 11:23:36 -0700156#endif
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700157 ignoreNextOverrun = true;
158 }
159 previous = current;
160 }
161 current = next;
162 }
163#if !LOG_NDEBUG
164 next = NULL; // not referenced again
165#endif
166
167 dumpState->mCommand = command;
168
169 switch (command) {
170 case FastMixerState::INITIAL:
171 case FastMixerState::HOT_IDLE:
172 sleepNs = FAST_HOT_IDLE_NS;
173 continue;
174 case FastMixerState::COLD_IDLE:
175 // only perform a cold idle command once
Glenn Kasten21e8c502012-04-12 09:39:42 -0700176 // FIXME consider checking previous state and only perform if previous != COLD_IDLE
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700177 if (current->mColdGen != coldGen) {
178 int32_t *coldFutexAddr = current->mColdFutexAddr;
179 ALOG_ASSERT(coldFutexAddr != NULL);
180 int32_t old = android_atomic_dec(coldFutexAddr);
181 if (old <= 0) {
182 __futex_syscall4(coldFutexAddr, FUTEX_WAIT_PRIVATE, old - 1, NULL);
183 }
Glenn Kastena07f17c2013-04-23 12:39:37 -0700184 int policy = sched_getscheduler(0);
185 if (!(policy == SCHED_FIFO || policy == SCHED_RR)) {
186 ALOGE("did not receive expected priority boost");
187 }
Glenn Kasten288ed212012-04-25 17:52:27 -0700188 // This may be overly conservative; there could be times that the normal mixer
189 // requests such a brief cold idle that it doesn't require resetting this flag.
190 isWarm = false;
191 measuredWarmupTs.tv_sec = 0;
192 measuredWarmupTs.tv_nsec = 0;
193 warmupCycles = 0;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700194 sleepNs = -1;
195 coldGen = current->mColdGen;
Glenn Kasten153b9fe2013-07-15 11:23:36 -0700196#ifdef FAST_MIXER_STATISTICS
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700197 bounds = 0;
198 full = false;
Glenn Kasten153b9fe2013-07-15 11:23:36 -0700199#endif
Glenn Kasten04a4ca42012-06-01 10:49:51 -0700200 oldTsValid = !clock_gettime(CLOCK_MONOTONIC, &oldTs);
Glenn Kasten732845c2013-08-23 09:26:31 -0700201 timestampStatus = INVALID_OPERATION;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700202 } else {
203 sleepNs = FAST_HOT_IDLE_NS;
204 }
205 continue;
206 case FastMixerState::EXIT:
207 delete mixer;
208 delete[] mixBuffer;
209 return false;
210 case FastMixerState::MIX:
211 case FastMixerState::WRITE:
212 case FastMixerState::MIX_WRITE:
213 break;
214 default:
215 LOG_FATAL("bad command %d", command);
216 }
217
218 // there is a non-idle state available to us; did the state change?
219 size_t frameCount = current->mFrameCount;
220 if (current != previous) {
221
222 // handle state change here, but since we want to diff the state,
223 // we're prepared for previous == &initial the first time through
224 unsigned previousTrackMask;
225
226 // check for change in output HAL configuration
227 NBAIO_Format previousFormat = format;
228 if (current->mOutputSinkGen != outputSinkGen) {
229 outputSink = current->mOutputSink;
230 outputSinkGen = current->mOutputSinkGen;
231 if (outputSink == NULL) {
232 format = Format_Invalid;
233 sampleRate = 0;
234 } else {
235 format = outputSink->format();
236 sampleRate = Format_sampleRate(format);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -0700237 ALOG_ASSERT(Format_channelCount(format) == FCC_2);
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700238 }
239 }
240
Glenn Kasten6e0d67d2014-01-31 09:41:08 -0800241 if ((!Format_isEqual(format, previousFormat)) || (frameCount != previous->mFrameCount)) {
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700242 // FIXME to avoid priority inversion, don't delete here
243 delete mixer;
244 mixer = NULL;
245 delete[] mixBuffer;
246 mixBuffer = NULL;
247 if (frameCount > 0 && sampleRate > 0) {
248 // FIXME new may block for unbounded time at internal mutex of the heap
249 // implementation; it would be better to have normal mixer allocate for us
250 // to avoid blocking here and to prevent possible priority inversion
251 mixer = new AudioMixer(frameCount, sampleRate, FastMixerState::kMaxFastTracks);
Glenn Kasten7fc97ba2013-07-16 17:18:58 -0700252 mixBuffer = new short[frameCount * FCC_2];
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700253 periodNs = (frameCount * 1000000000LL) / sampleRate; // 1.00
254 underrunNs = (frameCount * 1750000000LL) / sampleRate; // 1.75
Glenn Kasten0d27c652012-08-07 10:38:59 -0700255 overrunNs = (frameCount * 500000000LL) / sampleRate; // 0.50
256 forceNs = (frameCount * 950000000LL) / sampleRate; // 0.95
Glenn Kasten288ed212012-04-25 17:52:27 -0700257 warmupNs = (frameCount * 500000000LL) / sampleRate; // 0.50
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700258 } else {
259 periodNs = 0;
260 underrunNs = 0;
261 overrunNs = 0;
Glenn Kasten972af222012-06-13 17:14:03 -0700262 forceNs = 0;
263 warmupNs = 0;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700264 }
265 mixBufferState = UNDEFINED;
266#if !LOG_NDEBUG
267 for (i = 0; i < FastMixerState::kMaxFastTracks; ++i) {
268 fastTrackNames[i] = -1;
269 }
270#endif
271 // we need to reconfigure all active tracks
272 previousTrackMask = 0;
273 fastTracksGen = current->mFastTracksGen - 1;
Glenn Kasten21e8c502012-04-12 09:39:42 -0700274 dumpState->mFrameCount = frameCount;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700275 } else {
276 previousTrackMask = previous->mTrackMask;
277 }
278
279 // check for change in active track set
280 unsigned currentTrackMask = current->mTrackMask;
Glenn Kasten1295bb4d2012-05-31 07:43:43 -0700281 dumpState->mTrackMask = currentTrackMask;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700282 if (current->mFastTracksGen != fastTracksGen) {
283 ALOG_ASSERT(mixBuffer != NULL);
284 int name;
285
286 // process removed tracks first to avoid running out of track names
287 unsigned removedTracks = previousTrackMask & ~currentTrackMask;
288 while (removedTracks != 0) {
289 i = __builtin_ctz(removedTracks);
290 removedTracks &= ~(1 << i);
291 const FastTrack* fastTrack = &current->mFastTracks[i];
Glenn Kasten288ed212012-04-25 17:52:27 -0700292 ALOG_ASSERT(fastTrack->mBufferProvider == NULL);
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700293 if (mixer != NULL) {
294 name = fastTrackNames[i];
295 ALOG_ASSERT(name >= 0);
296 mixer->deleteTrackName(name);
297 }
298#if !LOG_NDEBUG
299 fastTrackNames[i] = -1;
300#endif
Glenn Kasten288ed212012-04-25 17:52:27 -0700301 // don't reset track dump state, since other side is ignoring it
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700302 generations[i] = fastTrack->mGeneration;
303 }
304
305 // now process added tracks
306 unsigned addedTracks = currentTrackMask & ~previousTrackMask;
307 while (addedTracks != 0) {
308 i = __builtin_ctz(addedTracks);
309 addedTracks &= ~(1 << i);
310 const FastTrack* fastTrack = &current->mFastTracks[i];
311 AudioBufferProvider *bufferProvider = fastTrack->mBufferProvider;
312 ALOG_ASSERT(bufferProvider != NULL && fastTrackNames[i] == -1);
313 if (mixer != NULL) {
Jean-Michel Trivife3156e2012-09-10 18:58:27 -0700314 // calling getTrackName with default channel mask and a random invalid
315 // sessionId (no effects here)
316 name = mixer->getTrackName(AUDIO_CHANNEL_OUT_STEREO, -555);
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700317 ALOG_ASSERT(name >= 0);
318 fastTrackNames[i] = name;
319 mixer->setBufferProvider(name, bufferProvider);
320 mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::MAIN_BUFFER,
321 (void *) mixBuffer);
322 // newly allocated track names default to full scale volume
Glenn Kasten21e8c502012-04-12 09:39:42 -0700323 mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::CHANNEL_MASK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000324 (void *)(uintptr_t)fastTrack->mChannelMask);
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700325 mixer->enable(name);
326 }
327 generations[i] = fastTrack->mGeneration;
328 }
329
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800330 // finally process (potentially) modified tracks; these use the same slot
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700331 // but may have a different buffer provider or volume provider
332 unsigned modifiedTracks = currentTrackMask & previousTrackMask;
333 while (modifiedTracks != 0) {
334 i = __builtin_ctz(modifiedTracks);
335 modifiedTracks &= ~(1 << i);
336 const FastTrack* fastTrack = &current->mFastTracks[i];
337 if (fastTrack->mGeneration != generations[i]) {
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800338 // this track was actually modified
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700339 AudioBufferProvider *bufferProvider = fastTrack->mBufferProvider;
340 ALOG_ASSERT(bufferProvider != NULL);
341 if (mixer != NULL) {
342 name = fastTrackNames[i];
343 ALOG_ASSERT(name >= 0);
344 mixer->setBufferProvider(name, bufferProvider);
345 if (fastTrack->mVolumeProvider == NULL) {
346 mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME0,
347 (void *)0x1000);
348 mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME1,
349 (void *)0x1000);
350 }
Martin Storsjo3ce28aa2014-02-05 19:49:05 +0200351 mixer->setParameter(name, AudioMixer::RESAMPLE,
352 AudioMixer::REMOVE, NULL);
Glenn Kasten21e8c502012-04-12 09:39:42 -0700353 mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::CHANNEL_MASK,
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000354 (void *)(uintptr_t) fastTrack->mChannelMask);
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700355 // already enabled
356 }
357 generations[i] = fastTrack->mGeneration;
358 }
359 }
360
361 fastTracksGen = current->mFastTracksGen;
362
363 dumpState->mNumTracks = popcount(currentTrackMask);
364 }
365
366#if 1 // FIXME shouldn't need this
367 // only process state change once
368 previous = current;
369#endif
370 }
371
372 // do work using current state here
Glenn Kasten288ed212012-04-25 17:52:27 -0700373 if ((command & FastMixerState::MIX) && (mixer != NULL) && isWarm) {
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700374 ALOG_ASSERT(mixBuffer != NULL);
Glenn Kasten288ed212012-04-25 17:52:27 -0700375 // for each track, update volume and check for underrun
376 unsigned currentTrackMask = current->mTrackMask;
377 while (currentTrackMask != 0) {
378 i = __builtin_ctz(currentTrackMask);
379 currentTrackMask &= ~(1 << i);
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700380 const FastTrack* fastTrack = &current->mFastTracks[i];
Glenn Kasten732845c2013-08-23 09:26:31 -0700381
382 // Refresh the per-track timestamp
383 if (timestampStatus == NO_ERROR) {
Martin Storsjo3ce28aa2014-02-05 19:49:05 +0200384 uint32_t trackFramesWrittenButNotPresented =
385 nativeFramesWrittenButNotPresented;
Glenn Kasten732845c2013-08-23 09:26:31 -0700386 uint32_t trackFramesWritten = fastTrack->mBufferProvider->framesReleased();
387 // Can't provide an AudioTimestamp before first frame presented,
388 // or during the brief 32-bit wraparound window
389 if (trackFramesWritten >= trackFramesWrittenButNotPresented) {
390 AudioTimestamp perTrackTimestamp;
391 perTrackTimestamp.mPosition =
392 trackFramesWritten - trackFramesWrittenButNotPresented;
393 perTrackTimestamp.mTime = timestamp.mTime;
394 fastTrack->mBufferProvider->onTimestamp(perTrackTimestamp);
395 }
396 }
397
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700398 int name = fastTrackNames[i];
399 ALOG_ASSERT(name >= 0);
400 if (fastTrack->mVolumeProvider != NULL) {
401 uint32_t vlr = fastTrack->mVolumeProvider->getVolumeLR();
402 mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME0,
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000403 (void *)(uintptr_t)(vlr & 0xFFFF));
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700404 mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME1,
Kévin PETIT377b2ec2014-02-03 12:35:36 +0000405 (void *)(uintptr_t)(vlr >> 16));
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700406 }
Glenn Kasten288ed212012-04-25 17:52:27 -0700407 // FIXME The current implementation of framesReady() for fast tracks
408 // takes a tryLock, which can block
409 // up to 1 ms. If enough active tracks all blocked in sequence, this would result
410 // in the overall fast mix cycle being delayed. Should use a non-blocking FIFO.
411 size_t framesReady = fastTrack->mBufferProvider->framesReady();
Alex Rayb3a83642012-11-30 19:42:28 -0800412 if (ATRACE_ENABLED()) {
413 // I wish we had formatted trace names
414 char traceName[16];
Glenn Kastenc9b2e202013-02-26 11:32:32 -0800415 strcpy(traceName, "fRdy");
416 traceName[4] = i + (i < 10 ? '0' : 'A' - 10);
417 traceName[5] = '\0';
Alex Rayb3a83642012-11-30 19:42:28 -0800418 ATRACE_INT(traceName, framesReady);
419 }
Glenn Kasten288ed212012-04-25 17:52:27 -0700420 FastTrackDump *ftDump = &dumpState->mTracks[i];
Glenn Kasten09474df2012-05-10 14:48:07 -0700421 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten288ed212012-04-25 17:52:27 -0700422 if (framesReady < frameCount) {
Glenn Kasten288ed212012-04-25 17:52:27 -0700423 if (framesReady == 0) {
Glenn Kasten09474df2012-05-10 14:48:07 -0700424 underruns.mBitFields.mEmpty++;
425 underruns.mBitFields.mMostRecent = UNDERRUN_EMPTY;
Glenn Kasten288ed212012-04-25 17:52:27 -0700426 mixer->disable(name);
427 } else {
428 // allow mixing partial buffer
Glenn Kasten09474df2012-05-10 14:48:07 -0700429 underruns.mBitFields.mPartial++;
430 underruns.mBitFields.mMostRecent = UNDERRUN_PARTIAL;
Glenn Kasten288ed212012-04-25 17:52:27 -0700431 mixer->enable(name);
432 }
Glenn Kasten09474df2012-05-10 14:48:07 -0700433 } else {
434 underruns.mBitFields.mFull++;
435 underruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten288ed212012-04-25 17:52:27 -0700436 mixer->enable(name);
437 }
Glenn Kasten09474df2012-05-10 14:48:07 -0700438 ftDump->mUnderruns = underruns;
Glenn Kasten1295bb4d2012-05-31 07:43:43 -0700439 ftDump->mFramesReady = framesReady;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700440 }
John Grossman2c3b2da2012-08-02 17:08:54 -0700441
442 int64_t pts;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700443 if (outputSink == NULL || (OK != outputSink->getNextWriteTimestamp(&pts))) {
John Grossman2c3b2da2012-08-02 17:08:54 -0700444 pts = AudioBufferProvider::kInvalidPTS;
Glenn Kasten6e2ebe92013-08-13 09:14:51 -0700445 }
John Grossman2c3b2da2012-08-02 17:08:54 -0700446
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700447 // process() is CPU-bound
John Grossman2c3b2da2012-08-02 17:08:54 -0700448 mixer->process(pts);
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700449 mixBufferState = MIXED;
450 } else if (mixBufferState == MIXED) {
451 mixBufferState = UNDEFINED;
452 }
Glenn Kasten288ed212012-04-25 17:52:27 -0700453 bool attemptedWrite = false;
454 //bool didFullWrite = false; // dumpsys could display a count of partial writes
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700455 if ((command & FastMixerState::WRITE) && (outputSink != NULL) && (mixBuffer != NULL)) {
456 if (mixBufferState == UNDEFINED) {
Glenn Kasten7fc97ba2013-07-16 17:18:58 -0700457 memset(mixBuffer, 0, frameCount * FCC_2 * sizeof(short));
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700458 mixBufferState = ZEROED;
459 }
Glenn Kastenfbae5da2012-05-21 09:17:20 -0700460 if (teeSink != NULL) {
461 (void) teeSink->write(mixBuffer, frameCount);
462 }
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700463 // FIXME write() is non-blocking and lock-free for a properly implemented NBAIO sink,
464 // but this code should be modified to handle both non-blocking and blocking sinks
465 dumpState->mWriteSequence++;
Simon Wilson2d590962012-11-29 15:18:50 -0800466 ATRACE_BEGIN("write");
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700467 ssize_t framesWritten = outputSink->write(mixBuffer, frameCount);
Simon Wilson2d590962012-11-29 15:18:50 -0800468 ATRACE_END();
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700469 dumpState->mWriteSequence++;
470 if (framesWritten >= 0) {
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800471 ALOG_ASSERT((size_t) framesWritten <= frameCount);
Glenn Kasten732845c2013-08-23 09:26:31 -0700472 totalNativeFramesWritten += framesWritten;
473 dumpState->mFramesWritten = totalNativeFramesWritten;
Glenn Kasten288ed212012-04-25 17:52:27 -0700474 //if ((size_t) framesWritten == frameCount) {
475 // didFullWrite = true;
476 //}
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700477 } else {
478 dumpState->mWriteErrors++;
479 }
Glenn Kasten288ed212012-04-25 17:52:27 -0700480 attemptedWrite = true;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700481 // FIXME count # of writes blocked excessively, CPU usage, etc. for dump
Glenn Kasten732845c2013-08-23 09:26:31 -0700482
483 timestampStatus = outputSink->getTimestamp(timestamp);
484 if (timestampStatus == NO_ERROR) {
485 uint32_t totalNativeFramesPresented = timestamp.mPosition;
486 if (totalNativeFramesPresented <= totalNativeFramesWritten) {
487 nativeFramesWrittenButNotPresented =
488 totalNativeFramesWritten - totalNativeFramesPresented;
489 } else {
490 // HAL reported that more frames were presented than were written
491 timestampStatus = INVALID_OPERATION;
492 }
493 }
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700494 }
495
496 // To be exactly periodic, compute the next sleep time based on current time.
497 // This code doesn't have long-term stability when the sink is non-blocking.
498 // FIXME To avoid drift, use the local audio clock or watch the sink's fill status.
499 struct timespec newTs;
500 int rc = clock_gettime(CLOCK_MONOTONIC, &newTs);
501 if (rc == 0) {
Glenn Kastenab7d72f2013-02-27 09:05:28 -0800502 //logWriter->logTimestamp(newTs);
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700503 if (oldTsValid) {
504 time_t sec = newTs.tv_sec - oldTs.tv_sec;
505 long nsec = newTs.tv_nsec - oldTs.tv_nsec;
Glenn Kasten80b32732012-09-24 11:29:00 -0700506 ALOGE_IF(sec < 0 || (sec == 0 && nsec < 0),
507 "clock_gettime(CLOCK_MONOTONIC) failed: was %ld.%09ld but now %ld.%09ld",
508 oldTs.tv_sec, oldTs.tv_nsec, newTs.tv_sec, newTs.tv_nsec);
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700509 if (nsec < 0) {
510 --sec;
511 nsec += 1000000000;
512 }
Glenn Kasten288ed212012-04-25 17:52:27 -0700513 // To avoid an initial underrun on fast tracks after exiting standby,
514 // do not start pulling data from tracks and mixing until warmup is complete.
515 // Warmup is considered complete after the earlier of:
Glenn Kasteneb157162012-06-13 14:59:07 -0700516 // MIN_WARMUP_CYCLES write() attempts and last one blocks for at least warmupNs
Glenn Kasten288ed212012-04-25 17:52:27 -0700517 // MAX_WARMUP_CYCLES write() attempts.
518 // This is overly conservative, but to get better accuracy requires a new HAL API.
519 if (!isWarm && attemptedWrite) {
520 measuredWarmupTs.tv_sec += sec;
521 measuredWarmupTs.tv_nsec += nsec;
522 if (measuredWarmupTs.tv_nsec >= 1000000000) {
523 measuredWarmupTs.tv_sec++;
524 measuredWarmupTs.tv_nsec -= 1000000000;
525 }
526 ++warmupCycles;
Glenn Kasteneb157162012-06-13 14:59:07 -0700527 if ((nsec > warmupNs && warmupCycles >= MIN_WARMUP_CYCLES) ||
Glenn Kasten288ed212012-04-25 17:52:27 -0700528 (warmupCycles >= MAX_WARMUP_CYCLES)) {
529 isWarm = true;
530 dumpState->mMeasuredWarmupTs = measuredWarmupTs;
531 dumpState->mWarmupCycles = warmupCycles;
532 }
533 }
Glenn Kasten972af222012-06-13 17:14:03 -0700534 sleepNs = -1;
Glenn Kasten3d198252013-07-10 17:20:54 -0700535 if (isWarm) {
536 if (sec > 0 || nsec > underrunNs) {
537 ATRACE_NAME("underrun");
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700538 // FIXME only log occasionally
Glenn Kasten3d198252013-07-10 17:20:54 -0700539 ALOGV("underrun: time since last cycle %d.%03ld sec",
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700540 (int) sec, nsec / 1000000L);
Glenn Kasten3d198252013-07-10 17:20:54 -0700541 dumpState->mUnderruns++;
542 ignoreNextOverrun = true;
543 } else if (nsec < overrunNs) {
544 if (ignoreNextOverrun) {
545 ignoreNextOverrun = false;
546 } else {
547 // FIXME only log occasionally
548 ALOGV("overrun: time since last cycle %d.%03ld sec",
549 (int) sec, nsec / 1000000L);
550 dumpState->mOverruns++;
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700551 }
Glenn Kasten3d198252013-07-10 17:20:54 -0700552 // This forces a minimum cycle time. It:
553 // - compensates for an audio HAL with jitter due to sample rate conversion
554 // - works with a variable buffer depth audio HAL that never pulls at a
555 // rate < than overrunNs per buffer.
556 // - recovers from overrun immediately after underrun
557 // It doesn't work with a non-blocking audio HAL.
558 sleepNs = forceNs - nsec;
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700559 } else {
Glenn Kasten3d198252013-07-10 17:20:54 -0700560 ignoreNextOverrun = false;
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700561 }
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700562 }
Glenn Kasten3d198252013-07-10 17:20:54 -0700563#ifdef FAST_MIXER_STATISTICS
564 if (isWarm) {
565 // advance the FIFO queue bounds
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700566 size_t i = bounds & (dumpState->mSamplingN - 1);
Glenn Kasten3d198252013-07-10 17:20:54 -0700567 bounds = (bounds & 0xFFFF0000) | ((bounds + 1) & 0xFFFF);
568 if (full) {
569 bounds += 0x10000;
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700570 } else if (!(bounds & (dumpState->mSamplingN - 1))) {
Glenn Kasten3d198252013-07-10 17:20:54 -0700571 full = true;
572 }
573 // compute the delta value of clock_gettime(CLOCK_MONOTONIC)
574 uint32_t monotonicNs = nsec;
575 if (sec > 0 && sec < 4) {
576 monotonicNs += sec * 1000000000;
577 }
578 // compute raw CPU load = delta value of clock_gettime(CLOCK_THREAD_CPUTIME_ID)
579 uint32_t loadNs = 0;
580 struct timespec newLoad;
581 rc = clock_gettime(CLOCK_THREAD_CPUTIME_ID, &newLoad);
582 if (rc == 0) {
583 if (oldLoadValid) {
584 sec = newLoad.tv_sec - oldLoad.tv_sec;
585 nsec = newLoad.tv_nsec - oldLoad.tv_nsec;
586 if (nsec < 0) {
587 --sec;
588 nsec += 1000000000;
589 }
590 loadNs = nsec;
591 if (sec > 0 && sec < 4) {
592 loadNs += sec * 1000000000;
593 }
594 } else {
595 // first time through the loop
596 oldLoadValid = true;
597 }
598 oldLoad = newLoad;
599 }
Glenn Kasten0a14c4c2012-06-13 14:58:49 -0700600#ifdef CPU_FREQUENCY_STATISTICS
Glenn Kasten3d198252013-07-10 17:20:54 -0700601 // get the absolute value of CPU clock frequency in kHz
602 int cpuNum = sched_getcpu();
603 uint32_t kHz = tcu.getCpukHz(cpuNum);
604 kHz = (kHz << 4) | (cpuNum & 0xF);
Glenn Kasten0a14c4c2012-06-13 14:58:49 -0700605#endif
Glenn Kasten3d198252013-07-10 17:20:54 -0700606 // save values in FIFO queues for dumpsys
607 // these stores #1, #2, #3 are not atomic with respect to each other,
608 // or with respect to store #4 below
609 dumpState->mMonotonicNs[i] = monotonicNs;
610 dumpState->mLoadNs[i] = loadNs;
Glenn Kasten0a14c4c2012-06-13 14:58:49 -0700611#ifdef CPU_FREQUENCY_STATISTICS
Glenn Kasten3d198252013-07-10 17:20:54 -0700612 dumpState->mCpukHz[i] = kHz;
Glenn Kasten0a14c4c2012-06-13 14:58:49 -0700613#endif
Glenn Kasten3d198252013-07-10 17:20:54 -0700614 // this store #4 is not atomic with respect to stores #1, #2, #3 above, but
615 // the newest open & oldest closed halves are atomic with respect to each other
616 dumpState->mBounds = bounds;
617 ATRACE_INT("cycle_ms", monotonicNs / 1000000);
618 ATRACE_INT("load_us", loadNs / 1000);
619 }
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700620#endif
621 } else {
622 // first time through the loop
623 oldTsValid = true;
624 sleepNs = periodNs;
625 ignoreNextOverrun = true;
626 }
627 oldTs = newTs;
628 } else {
629 // monotonic clock is broken
630 oldTsValid = false;
631 sleepNs = periodNs;
632 }
633
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700634
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700635 } // for (;;)
636
637 // never return 'true'; Thread::_threadLoop() locks mutex which can result in priority inversion
638}
639
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700640FastMixerDumpState::FastMixerDumpState(
641#ifdef FAST_MIXER_STATISTICS
642 uint32_t samplingN
643#endif
644 ) :
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700645 mCommand(FastMixerState::INITIAL), mWriteSequence(0), mFramesWritten(0),
Glenn Kasten21e8c502012-04-12 09:39:42 -0700646 mNumTracks(0), mWriteErrors(0), mUnderruns(0), mOverruns(0),
Glenn Kasten1295bb4d2012-05-31 07:43:43 -0700647 mSampleRate(0), mFrameCount(0), /* mMeasuredWarmupTs({0, 0}), */ mWarmupCycles(0),
648 mTrackMask(0)
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700649#ifdef FAST_MIXER_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700650 , mSamplingN(0), mBounds(0)
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700651#endif
652{
Glenn Kasten288ed212012-04-25 17:52:27 -0700653 mMeasuredWarmupTs.tv_sec = 0;
654 mMeasuredWarmupTs.tv_nsec = 0;
Glenn Kasten153b9fe2013-07-15 11:23:36 -0700655#ifdef FAST_MIXER_STATISTICS
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700656 increaseSamplingN(samplingN);
Glenn Kasten153b9fe2013-07-15 11:23:36 -0700657#endif
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700658}
659
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700660#ifdef FAST_MIXER_STATISTICS
661void FastMixerDumpState::increaseSamplingN(uint32_t samplingN)
662{
663 if (samplingN <= mSamplingN || samplingN > kSamplingN || roundup(samplingN) != samplingN) {
664 return;
665 }
666 uint32_t additional = samplingN - mSamplingN;
667 // sample arrays aren't accessed atomically with respect to the bounds,
668 // so clearing reduces chance for dumpsys to read random uninitialized samples
669 memset(&mMonotonicNs[mSamplingN], 0, sizeof(mMonotonicNs[0]) * additional);
670 memset(&mLoadNs[mSamplingN], 0, sizeof(mLoadNs[0]) * additional);
671#ifdef CPU_FREQUENCY_STATISTICS
672 memset(&mCpukHz[mSamplingN], 0, sizeof(mCpukHz[0]) * additional);
673#endif
674 mSamplingN = samplingN;
675}
676#endif
677
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700678FastMixerDumpState::~FastMixerDumpState()
679{
680}
681
Glenn Kasten1ab212cf2012-09-07 12:58:38 -0700682// helper function called by qsort()
683static int compare_uint32_t(const void *pa, const void *pb)
684{
685 uint32_t a = *(const uint32_t *)pa;
686 uint32_t b = *(const uint32_t *)pb;
687 if (a < b) {
688 return -1;
689 } else if (a > b) {
690 return 1;
691 } else {
692 return 0;
693 }
694}
695
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700696void FastMixerDumpState::dump(int fd) const
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700697{
Glenn Kasten868c0ab2012-06-13 14:59:17 -0700698 if (mCommand == FastMixerState::INITIAL) {
Marco Nelissenb2208842014-02-07 14:00:50 -0800699 fdprintf(fd, " FastMixer not initialized\n");
Glenn Kasten868c0ab2012-06-13 14:59:17 -0700700 return;
701 }
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700702#define COMMAND_MAX 32
703 char string[COMMAND_MAX];
704 switch (mCommand) {
705 case FastMixerState::INITIAL:
706 strcpy(string, "INITIAL");
707 break;
708 case FastMixerState::HOT_IDLE:
709 strcpy(string, "HOT_IDLE");
710 break;
711 case FastMixerState::COLD_IDLE:
712 strcpy(string, "COLD_IDLE");
713 break;
714 case FastMixerState::EXIT:
715 strcpy(string, "EXIT");
716 break;
717 case FastMixerState::MIX:
718 strcpy(string, "MIX");
719 break;
720 case FastMixerState::WRITE:
721 strcpy(string, "WRITE");
722 break;
723 case FastMixerState::MIX_WRITE:
724 strcpy(string, "MIX_WRITE");
725 break;
726 default:
727 snprintf(string, COMMAND_MAX, "%d", mCommand);
728 break;
729 }
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700730 double measuredWarmupMs = (mMeasuredWarmupTs.tv_sec * 1000.0) +
Glenn Kasten288ed212012-04-25 17:52:27 -0700731 (mMeasuredWarmupTs.tv_nsec / 1000000.0);
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700732 double mixPeriodSec = (double) mFrameCount / (double) mSampleRate;
Marco Nelissenb2208842014-02-07 14:00:50 -0800733 fdprintf(fd, " FastMixer command=%s writeSequence=%u framesWritten=%u\n"
734 " numTracks=%u writeErrors=%u underruns=%u overruns=%u\n"
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000735 " sampleRate=%u frameCount=%zu measuredWarmup=%.3g ms, warmupCycles=%u\n"
Marco Nelissenb2208842014-02-07 14:00:50 -0800736 " mixPeriod=%.2f ms\n",
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700737 string, mWriteSequence, mFramesWritten,
Glenn Kasten21e8c502012-04-12 09:39:42 -0700738 mNumTracks, mWriteErrors, mUnderruns, mOverruns,
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700739 mSampleRate, mFrameCount, measuredWarmupMs, mWarmupCycles,
740 mixPeriodSec * 1e3);
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700741#ifdef FAST_MIXER_STATISTICS
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700742 // find the interval of valid samples
743 uint32_t bounds = mBounds;
744 uint32_t newestOpen = bounds & 0xFFFF;
745 uint32_t oldestClosed = bounds >> 16;
746 uint32_t n = (newestOpen - oldestClosed) & 0xFFFF;
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700747 if (n > mSamplingN) {
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700748 ALOGE("too many samples %u", n);
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700749 n = mSamplingN;
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700750 }
751 // statistics for monotonic (wall clock) time, thread raw CPU load in time, CPU clock frequency,
752 // and adjusted CPU load in MHz normalized for CPU clock frequency
Glenn Kasten0a14c4c2012-06-13 14:58:49 -0700753 CentralTendencyStatistics wall, loadNs;
754#ifdef CPU_FREQUENCY_STATISTICS
755 CentralTendencyStatistics kHz, loadMHz;
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700756 uint32_t previousCpukHz = 0;
Glenn Kasten0a14c4c2012-06-13 14:58:49 -0700757#endif
Glenn Kasten1ab212cf2012-09-07 12:58:38 -0700758 // Assuming a normal distribution for cycle times, three standard deviations on either side of
759 // the mean account for 99.73% of the population. So if we take each tail to be 1/1000 of the
760 // sample set, we get 99.8% combined, or close to three standard deviations.
761 static const uint32_t kTailDenominator = 1000;
762 uint32_t *tail = n >= kTailDenominator ? new uint32_t[n] : NULL;
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700763 // loop over all the samples
Glenn Kasten1ab212cf2012-09-07 12:58:38 -0700764 for (uint32_t j = 0; j < n; ++j) {
Glenn Kasten4182c4e2013-07-15 14:45:07 -0700765 size_t i = oldestClosed++ & (mSamplingN - 1);
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700766 uint32_t wallNs = mMonotonicNs[i];
Glenn Kasten1ab212cf2012-09-07 12:58:38 -0700767 if (tail != NULL) {
768 tail[j] = wallNs;
769 }
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700770 wall.sample(wallNs);
771 uint32_t sampleLoadNs = mLoadNs[i];
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700772 loadNs.sample(sampleLoadNs);
Glenn Kasten0a14c4c2012-06-13 14:58:49 -0700773#ifdef CPU_FREQUENCY_STATISTICS
774 uint32_t sampleCpukHz = mCpukHz[i];
Glenn Kastenc059bd42012-05-14 17:41:09 -0700775 // skip bad kHz samples
776 if ((sampleCpukHz & ~0xF) != 0) {
777 kHz.sample(sampleCpukHz >> 4);
778 if (sampleCpukHz == previousCpukHz) {
779 double megacycles = (double) sampleLoadNs * (double) (sampleCpukHz >> 4) * 1e-12;
780 double adjMHz = megacycles / mixPeriodSec; // _not_ wallNs * 1e9
781 loadMHz.sample(adjMHz);
782 }
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700783 }
784 previousCpukHz = sampleCpukHz;
Glenn Kasten0a14c4c2012-06-13 14:58:49 -0700785#endif
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700786 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800787 if (n) {
788 fdprintf(fd, " Simple moving statistics over last %.1f seconds:\n",
789 wall.n() * mixPeriodSec);
790 fdprintf(fd, " wall clock time in ms per mix cycle:\n"
791 " mean=%.2f min=%.2f max=%.2f stddev=%.2f\n",
792 wall.mean()*1e-6, wall.minimum()*1e-6, wall.maximum()*1e-6,
793 wall.stddev()*1e-6);
794 fdprintf(fd, " raw CPU load in us per mix cycle:\n"
795 " mean=%.0f min=%.0f max=%.0f stddev=%.0f\n",
796 loadNs.mean()*1e-3, loadNs.minimum()*1e-3, loadNs.maximum()*1e-3,
797 loadNs.stddev()*1e-3);
798 } else {
799 fdprintf(fd, " No FastMixer statistics available currently\n");
800 }
Glenn Kasten0a14c4c2012-06-13 14:58:49 -0700801#ifdef CPU_FREQUENCY_STATISTICS
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700802 fdprintf(fd, " CPU clock frequency in MHz:\n"
803 " mean=%.0f min=%.0f max=%.0f stddev=%.0f\n",
804 kHz.mean()*1e-3, kHz.minimum()*1e-3, kHz.maximum()*1e-3, kHz.stddev()*1e-3);
805 fdprintf(fd, " adjusted CPU load in MHz (i.e. normalized for CPU clock frequency):\n"
806 " mean=%.1f min=%.1f max=%.1f stddev=%.1f\n",
807 loadMHz.mean(), loadMHz.minimum(), loadMHz.maximum(), loadMHz.stddev());
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700808#endif
Glenn Kasten1ab212cf2012-09-07 12:58:38 -0700809 if (tail != NULL) {
810 qsort(tail, n, sizeof(uint32_t), compare_uint32_t);
811 // assume same number of tail samples on each side, left and right
812 uint32_t count = n / kTailDenominator;
813 CentralTendencyStatistics left, right;
814 for (uint32_t i = 0; i < count; ++i) {
815 left.sample(tail[i]);
816 right.sample(tail[n - (i + 1)]);
817 }
Marco Nelissenb2208842014-02-07 14:00:50 -0800818 fdprintf(fd, " Distribution of mix cycle times in ms for the tails (> ~3 stddev outliers):\n"
819 " left tail: mean=%.2f min=%.2f max=%.2f stddev=%.2f\n"
820 " right tail: mean=%.2f min=%.2f max=%.2f stddev=%.2f\n",
Glenn Kasten1ab212cf2012-09-07 12:58:38 -0700821 left.mean()*1e-6, left.minimum()*1e-6, left.maximum()*1e-6, left.stddev()*1e-6,
822 right.mean()*1e-6, right.minimum()*1e-6, right.maximum()*1e-6,
823 right.stddev()*1e-6);
824 delete[] tail;
825 }
Glenn Kasten0a14c4c2012-06-13 14:58:49 -0700826#endif
Glenn Kasten1295bb4d2012-05-31 07:43:43 -0700827 // The active track mask and track states are updated non-atomically.
828 // So if we relied on isActive to decide whether to display,
829 // then we might display an obsolete track or omit an active track.
830 // Instead we always display all tracks, with an indication
831 // of whether we think the track is active.
832 uint32_t trackMask = mTrackMask;
Marco Nelissenb2208842014-02-07 14:00:50 -0800833 fdprintf(fd, " Fast tracks: kMaxFastTracks=%u activeMask=%#x\n",
Glenn Kasten1295bb4d2012-05-31 07:43:43 -0700834 FastMixerState::kMaxFastTracks, trackMask);
Marco Nelissenb2208842014-02-07 14:00:50 -0800835 fdprintf(fd, " Index Active Full Partial Empty Recent Ready\n");
Glenn Kasten1295bb4d2012-05-31 07:43:43 -0700836 for (uint32_t i = 0; i < FastMixerState::kMaxFastTracks; ++i, trackMask >>= 1) {
837 bool isActive = trackMask & 1;
838 const FastTrackDump *ftDump = &mTracks[i];
839 const FastTrackUnderruns& underruns = ftDump->mUnderruns;
840 const char *mostRecent;
841 switch (underruns.mBitFields.mMostRecent) {
842 case UNDERRUN_FULL:
843 mostRecent = "full";
844 break;
845 case UNDERRUN_PARTIAL:
846 mostRecent = "partial";
847 break;
848 case UNDERRUN_EMPTY:
849 mostRecent = "empty";
850 break;
851 default:
852 mostRecent = "?";
853 break;
854 }
Narayan Kamath1d6fa7a2014-02-11 13:47:53 +0000855 fdprintf(fd, " %5u %6s %4u %7u %5u %7s %5zu\n", i, isActive ? "yes" : "no",
Glenn Kasten1295bb4d2012-05-31 07:43:43 -0700856 (underruns.mBitFields.mFull) & UNDERRUN_MASK,
857 (underruns.mBitFields.mPartial) & UNDERRUN_MASK,
858 (underruns.mBitFields.mEmpty) & UNDERRUN_MASK,
859 mostRecent, ftDump->mFramesReady);
860 }
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700861}
862
863} // namespace android