blob: b0af6edce05c600b6c4db53675541a54d58c7d68 [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
17#define LOG_TAG "FastMixer"
18//#define LOG_NDEBUG 0
19
20#include <sys/atomics.h>
21#include <time.h>
22#include <utils/Log.h>
Glenn Kastend8e6fd32012-05-07 11:07:57 -070023#include <utils/Trace.h>
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070024#include <system/audio.h>
25#ifdef FAST_MIXER_STATISTICS
26#include <cpustats/CentralTendencyStatistics.h>
Glenn Kasten42d45cf2012-05-02 10:34:47 -070027#include <cpustats/ThreadCpuUsage.h>
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070028#endif
29#include "AudioMixer.h"
30#include "FastMixer.h"
31
32#define FAST_HOT_IDLE_NS 1000000L // 1 ms: time to sleep while hot idling
33#define FAST_DEFAULT_NS 999999999L // ~1 sec: default time to sleep
Glenn Kasten288ed212012-04-25 17:52:27 -070034#define MAX_WARMUP_CYCLES 10 // maximum number of loop cycles to wait for warmup
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070035
36namespace android {
37
38// Fast mixer thread
39bool FastMixer::threadLoop()
40{
41 static const FastMixerState initial;
42 const FastMixerState *previous = &initial, *current = &initial;
43 FastMixerState preIdle; // copy of state before we went into idle
44 struct timespec oldTs = {0, 0};
45 bool oldTsValid = false;
46 long slopNs = 0; // accumulated time we've woken up too early (> 0) or too late (< 0)
47 long sleepNs = -1; // -1: busy wait, 0: sched_yield, > 0: nanosleep
48 int fastTrackNames[FastMixerState::kMaxFastTracks]; // handles used by mixer to identify tracks
49 int generations[FastMixerState::kMaxFastTracks]; // last observed mFastTracks[i].mGeneration
50 unsigned i;
51 for (i = 0; i < FastMixerState::kMaxFastTracks; ++i) {
52 fastTrackNames[i] = -1;
53 generations[i] = 0;
54 }
55 NBAIO_Sink *outputSink = NULL;
56 int outputSinkGen = 0;
57 AudioMixer* mixer = NULL;
58 short *mixBuffer = NULL;
59 enum {UNDEFINED, MIXED, ZEROED} mixBufferState = UNDEFINED;
60 NBAIO_Format format = Format_Invalid;
61 unsigned sampleRate = 0;
62 int fastTracksGen = 0;
63 long periodNs = 0; // expected period; the time required to render one mix buffer
Glenn Kasten288ed212012-04-25 17:52:27 -070064 long underrunNs = 0; // underrun likely when write cycle is greater than this value
65 long overrunNs = 0; // overrun likely when write cycle is less than this value
66 long warmupNs = 0; // warmup complete when write cycle is greater than to this value
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070067 FastMixerDumpState dummyDumpState, *dumpState = &dummyDumpState;
68 bool ignoreNextOverrun = true; // used to ignore initial overrun and first after an underrun
69#ifdef FAST_MIXER_STATISTICS
Glenn Kasten42d45cf2012-05-02 10:34:47 -070070 struct timespec oldLoad = {0, 0}; // previous value of clock_gettime(CLOCK_THREAD_CPUTIME_ID)
71 bool oldLoadValid = false; // whether oldLoad is valid
72 uint32_t bounds = 0;
73 bool full = false; // whether we have collected at least kSamplingN samples
74 ThreadCpuUsage tcu; // for reading the current CPU clock frequency in kHz
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070075#endif
76 unsigned coldGen = 0; // last observed mColdGen
Glenn Kasten288ed212012-04-25 17:52:27 -070077 bool isWarm = false; // true means ready to mix, false means wait for warmup before mixing
78 struct timespec measuredWarmupTs = {0, 0}; // how long did it take for warmup to complete
79 uint32_t warmupCycles = 0; // counter of number of loop cycles required to warmup
Glenn Kastenfbae5da2012-05-21 09:17:20 -070080 NBAIO_Sink* teeSink = NULL; // if non-NULL, then duplicate write() to this non-blocking sink
Glenn Kasten97b5d0d2012-03-23 18:54:19 -070081
82 for (;;) {
83
84 // either nanosleep, sched_yield, or busy wait
85 if (sleepNs >= 0) {
86 if (sleepNs > 0) {
87 ALOG_ASSERT(sleepNs < 1000000000);
88 const struct timespec req = {0, sleepNs};
89 nanosleep(&req, NULL);
90 } else {
91 sched_yield();
92 }
93 }
94 // default to long sleep for next cycle
95 sleepNs = FAST_DEFAULT_NS;
96
97 // poll for state change
98 const FastMixerState *next = mSQ.poll();
99 if (next == NULL) {
100 // continue to use the default initial state until a real state is available
101 ALOG_ASSERT(current == &initial && previous == &initial);
102 next = current;
103 }
104
105 FastMixerState::Command command = next->mCommand;
106 if (next != current) {
107
108 // As soon as possible of learning of a new dump area, start using it
109 dumpState = next->mDumpState != NULL ? next->mDumpState : &dummyDumpState;
Glenn Kastenfbae5da2012-05-21 09:17:20 -0700110 teeSink = next->mTeeSink;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700111
112 // We want to always have a valid reference to the previous (non-idle) state.
113 // However, the state queue only guarantees access to current and previous states.
114 // So when there is a transition from a non-idle state into an idle state, we make a
115 // copy of the last known non-idle state so it is still available on return from idle.
116 // The possible transitions are:
117 // non-idle -> non-idle update previous from current in-place
118 // non-idle -> idle update previous from copy of current
119 // idle -> idle don't update previous
120 // idle -> non-idle don't update previous
121 if (!(current->mCommand & FastMixerState::IDLE)) {
122 if (command & FastMixerState::IDLE) {
123 preIdle = *current;
124 current = &preIdle;
125 oldTsValid = false;
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700126 oldLoadValid = false;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700127 ignoreNextOverrun = true;
128 }
129 previous = current;
130 }
131 current = next;
132 }
133#if !LOG_NDEBUG
134 next = NULL; // not referenced again
135#endif
136
137 dumpState->mCommand = command;
138
139 switch (command) {
140 case FastMixerState::INITIAL:
141 case FastMixerState::HOT_IDLE:
142 sleepNs = FAST_HOT_IDLE_NS;
143 continue;
144 case FastMixerState::COLD_IDLE:
145 // only perform a cold idle command once
Glenn Kasten21e8c502012-04-12 09:39:42 -0700146 // FIXME consider checking previous state and only perform if previous != COLD_IDLE
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700147 if (current->mColdGen != coldGen) {
148 int32_t *coldFutexAddr = current->mColdFutexAddr;
149 ALOG_ASSERT(coldFutexAddr != NULL);
150 int32_t old = android_atomic_dec(coldFutexAddr);
151 if (old <= 0) {
152 __futex_syscall4(coldFutexAddr, FUTEX_WAIT_PRIVATE, old - 1, NULL);
153 }
Glenn Kasten288ed212012-04-25 17:52:27 -0700154 // This may be overly conservative; there could be times that the normal mixer
155 // requests such a brief cold idle that it doesn't require resetting this flag.
156 isWarm = false;
157 measuredWarmupTs.tv_sec = 0;
158 measuredWarmupTs.tv_nsec = 0;
159 warmupCycles = 0;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700160 sleepNs = -1;
161 coldGen = current->mColdGen;
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700162 bounds = 0;
163 full = false;
Glenn Kasten04a4ca42012-06-01 10:49:51 -0700164 oldTsValid = !clock_gettime(CLOCK_MONOTONIC, &oldTs);
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700165 } else {
166 sleepNs = FAST_HOT_IDLE_NS;
167 }
168 continue;
169 case FastMixerState::EXIT:
170 delete mixer;
171 delete[] mixBuffer;
172 return false;
173 case FastMixerState::MIX:
174 case FastMixerState::WRITE:
175 case FastMixerState::MIX_WRITE:
176 break;
177 default:
178 LOG_FATAL("bad command %d", command);
179 }
180
181 // there is a non-idle state available to us; did the state change?
182 size_t frameCount = current->mFrameCount;
183 if (current != previous) {
184
185 // handle state change here, but since we want to diff the state,
186 // we're prepared for previous == &initial the first time through
187 unsigned previousTrackMask;
188
189 // check for change in output HAL configuration
190 NBAIO_Format previousFormat = format;
191 if (current->mOutputSinkGen != outputSinkGen) {
192 outputSink = current->mOutputSink;
193 outputSinkGen = current->mOutputSinkGen;
194 if (outputSink == NULL) {
195 format = Format_Invalid;
196 sampleRate = 0;
197 } else {
198 format = outputSink->format();
199 sampleRate = Format_sampleRate(format);
200 ALOG_ASSERT(Format_channelCount(format) == 2);
201 }
Glenn Kasten21e8c502012-04-12 09:39:42 -0700202 dumpState->mSampleRate = sampleRate;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700203 }
204
205 if ((format != previousFormat) || (frameCount != previous->mFrameCount)) {
206 // FIXME to avoid priority inversion, don't delete here
207 delete mixer;
208 mixer = NULL;
209 delete[] mixBuffer;
210 mixBuffer = NULL;
211 if (frameCount > 0 && sampleRate > 0) {
212 // FIXME new may block for unbounded time at internal mutex of the heap
213 // implementation; it would be better to have normal mixer allocate for us
214 // to avoid blocking here and to prevent possible priority inversion
215 mixer = new AudioMixer(frameCount, sampleRate, FastMixerState::kMaxFastTracks);
216 mixBuffer = new short[frameCount * 2];
217 periodNs = (frameCount * 1000000000LL) / sampleRate; // 1.00
218 underrunNs = (frameCount * 1750000000LL) / sampleRate; // 1.75
219 overrunNs = (frameCount * 250000000LL) / sampleRate; // 0.25
Glenn Kasten288ed212012-04-25 17:52:27 -0700220 warmupNs = (frameCount * 500000000LL) / sampleRate; // 0.50
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700221 } else {
222 periodNs = 0;
223 underrunNs = 0;
224 overrunNs = 0;
225 }
226 mixBufferState = UNDEFINED;
227#if !LOG_NDEBUG
228 for (i = 0; i < FastMixerState::kMaxFastTracks; ++i) {
229 fastTrackNames[i] = -1;
230 }
231#endif
232 // we need to reconfigure all active tracks
233 previousTrackMask = 0;
234 fastTracksGen = current->mFastTracksGen - 1;
Glenn Kasten21e8c502012-04-12 09:39:42 -0700235 dumpState->mFrameCount = frameCount;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700236 } else {
237 previousTrackMask = previous->mTrackMask;
238 }
239
240 // check for change in active track set
241 unsigned currentTrackMask = current->mTrackMask;
242 if (current->mFastTracksGen != fastTracksGen) {
243 ALOG_ASSERT(mixBuffer != NULL);
244 int name;
245
246 // process removed tracks first to avoid running out of track names
247 unsigned removedTracks = previousTrackMask & ~currentTrackMask;
248 while (removedTracks != 0) {
249 i = __builtin_ctz(removedTracks);
250 removedTracks &= ~(1 << i);
251 const FastTrack* fastTrack = &current->mFastTracks[i];
Glenn Kasten288ed212012-04-25 17:52:27 -0700252 ALOG_ASSERT(fastTrack->mBufferProvider == NULL);
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700253 if (mixer != NULL) {
254 name = fastTrackNames[i];
255 ALOG_ASSERT(name >= 0);
256 mixer->deleteTrackName(name);
257 }
258#if !LOG_NDEBUG
259 fastTrackNames[i] = -1;
260#endif
Glenn Kasten288ed212012-04-25 17:52:27 -0700261 // don't reset track dump state, since other side is ignoring it
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700262 generations[i] = fastTrack->mGeneration;
263 }
264
265 // now process added tracks
266 unsigned addedTracks = currentTrackMask & ~previousTrackMask;
267 while (addedTracks != 0) {
268 i = __builtin_ctz(addedTracks);
269 addedTracks &= ~(1 << i);
270 const FastTrack* fastTrack = &current->mFastTracks[i];
271 AudioBufferProvider *bufferProvider = fastTrack->mBufferProvider;
272 ALOG_ASSERT(bufferProvider != NULL && fastTrackNames[i] == -1);
273 if (mixer != NULL) {
Jean-Michel Trivi9bd23222012-04-16 13:43:48 -0700274 // calling getTrackName with default channel mask
275 name = mixer->getTrackName(AUDIO_CHANNEL_OUT_STEREO);
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700276 ALOG_ASSERT(name >= 0);
277 fastTrackNames[i] = name;
278 mixer->setBufferProvider(name, bufferProvider);
279 mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::MAIN_BUFFER,
280 (void *) mixBuffer);
281 // newly allocated track names default to full scale volume
Glenn Kasten21e8c502012-04-12 09:39:42 -0700282 if (fastTrack->mSampleRate != 0 && fastTrack->mSampleRate != sampleRate) {
283 mixer->setParameter(name, AudioMixer::RESAMPLE,
284 AudioMixer::SAMPLE_RATE, (void*) fastTrack->mSampleRate);
285 }
286 mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::CHANNEL_MASK,
287 (void *) fastTrack->mChannelMask);
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700288 mixer->enable(name);
289 }
290 generations[i] = fastTrack->mGeneration;
291 }
292
293 // finally process modified tracks; these use the same slot
294 // but may have a different buffer provider or volume provider
295 unsigned modifiedTracks = currentTrackMask & previousTrackMask;
296 while (modifiedTracks != 0) {
297 i = __builtin_ctz(modifiedTracks);
298 modifiedTracks &= ~(1 << i);
299 const FastTrack* fastTrack = &current->mFastTracks[i];
300 if (fastTrack->mGeneration != generations[i]) {
301 AudioBufferProvider *bufferProvider = fastTrack->mBufferProvider;
302 ALOG_ASSERT(bufferProvider != NULL);
303 if (mixer != NULL) {
304 name = fastTrackNames[i];
305 ALOG_ASSERT(name >= 0);
306 mixer->setBufferProvider(name, bufferProvider);
307 if (fastTrack->mVolumeProvider == NULL) {
308 mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME0,
309 (void *)0x1000);
310 mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME1,
311 (void *)0x1000);
312 }
Glenn Kasten21e8c502012-04-12 09:39:42 -0700313 if (fastTrack->mSampleRate != 0 &&
314 fastTrack->mSampleRate != sampleRate) {
315 mixer->setParameter(name, AudioMixer::RESAMPLE,
316 AudioMixer::SAMPLE_RATE, (void*) fastTrack->mSampleRate);
317 } else {
318 mixer->setParameter(name, AudioMixer::RESAMPLE,
319 AudioMixer::REMOVE, NULL);
320 }
321 mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::CHANNEL_MASK,
322 (void *) fastTrack->mChannelMask);
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700323 // already enabled
324 }
325 generations[i] = fastTrack->mGeneration;
326 }
327 }
328
329 fastTracksGen = current->mFastTracksGen;
330
331 dumpState->mNumTracks = popcount(currentTrackMask);
332 }
333
334#if 1 // FIXME shouldn't need this
335 // only process state change once
336 previous = current;
337#endif
338 }
339
340 // do work using current state here
Glenn Kasten288ed212012-04-25 17:52:27 -0700341 if ((command & FastMixerState::MIX) && (mixer != NULL) && isWarm) {
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700342 ALOG_ASSERT(mixBuffer != NULL);
Glenn Kasten288ed212012-04-25 17:52:27 -0700343 // for each track, update volume and check for underrun
344 unsigned currentTrackMask = current->mTrackMask;
345 while (currentTrackMask != 0) {
346 i = __builtin_ctz(currentTrackMask);
347 currentTrackMask &= ~(1 << i);
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700348 const FastTrack* fastTrack = &current->mFastTracks[i];
349 int name = fastTrackNames[i];
350 ALOG_ASSERT(name >= 0);
351 if (fastTrack->mVolumeProvider != NULL) {
352 uint32_t vlr = fastTrack->mVolumeProvider->getVolumeLR();
353 mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME0,
354 (void *)(vlr & 0xFFFF));
355 mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME1,
356 (void *)(vlr >> 16));
357 }
Glenn Kasten288ed212012-04-25 17:52:27 -0700358 // FIXME The current implementation of framesReady() for fast tracks
359 // takes a tryLock, which can block
360 // up to 1 ms. If enough active tracks all blocked in sequence, this would result
361 // in the overall fast mix cycle being delayed. Should use a non-blocking FIFO.
362 size_t framesReady = fastTrack->mBufferProvider->framesReady();
Glenn Kasten99c99d02012-05-14 16:37:13 -0700363#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
364 // I wish we had formatted trace names
365 char traceName[16];
366 strcpy(traceName, "framesReady");
367 traceName[11] = i + (i < 10 ? '0' : 'A' - 10);
368 traceName[12] = '\0';
369 ATRACE_INT(traceName, framesReady);
370#endif
Glenn Kasten288ed212012-04-25 17:52:27 -0700371 FastTrackDump *ftDump = &dumpState->mTracks[i];
Glenn Kasten09474df2012-05-10 14:48:07 -0700372 FastTrackUnderruns underruns = ftDump->mUnderruns;
Glenn Kasten288ed212012-04-25 17:52:27 -0700373 if (framesReady < frameCount) {
Glenn Kasten288ed212012-04-25 17:52:27 -0700374 if (framesReady == 0) {
Glenn Kasten09474df2012-05-10 14:48:07 -0700375 underruns.mBitFields.mEmpty++;
376 underruns.mBitFields.mMostRecent = UNDERRUN_EMPTY;
Glenn Kasten288ed212012-04-25 17:52:27 -0700377 mixer->disable(name);
378 } else {
379 // allow mixing partial buffer
Glenn Kasten09474df2012-05-10 14:48:07 -0700380 underruns.mBitFields.mPartial++;
381 underruns.mBitFields.mMostRecent = UNDERRUN_PARTIAL;
Glenn Kasten288ed212012-04-25 17:52:27 -0700382 mixer->enable(name);
383 }
Glenn Kasten09474df2012-05-10 14:48:07 -0700384 } else {
385 underruns.mBitFields.mFull++;
386 underruns.mBitFields.mMostRecent = UNDERRUN_FULL;
Glenn Kasten288ed212012-04-25 17:52:27 -0700387 mixer->enable(name);
388 }
Glenn Kasten09474df2012-05-10 14:48:07 -0700389 ftDump->mUnderruns = underruns;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700390 }
391 // process() is CPU-bound
392 mixer->process(AudioBufferProvider::kInvalidPTS);
393 mixBufferState = MIXED;
394 } else if (mixBufferState == MIXED) {
395 mixBufferState = UNDEFINED;
396 }
Glenn Kasten288ed212012-04-25 17:52:27 -0700397 bool attemptedWrite = false;
398 //bool didFullWrite = false; // dumpsys could display a count of partial writes
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700399 if ((command & FastMixerState::WRITE) && (outputSink != NULL) && (mixBuffer != NULL)) {
400 if (mixBufferState == UNDEFINED) {
401 memset(mixBuffer, 0, frameCount * 2 * sizeof(short));
402 mixBufferState = ZEROED;
403 }
Glenn Kastenfbae5da2012-05-21 09:17:20 -0700404 if (teeSink != NULL) {
405 (void) teeSink->write(mixBuffer, frameCount);
406 }
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700407 // FIXME write() is non-blocking and lock-free for a properly implemented NBAIO sink,
408 // but this code should be modified to handle both non-blocking and blocking sinks
409 dumpState->mWriteSequence++;
Glenn Kasten99c99d02012-05-14 16:37:13 -0700410#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -0700411 Tracer::traceBegin(ATRACE_TAG, "write");
Glenn Kasten99c99d02012-05-14 16:37:13 -0700412#endif
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700413 ssize_t framesWritten = outputSink->write(mixBuffer, frameCount);
Glenn Kasten99c99d02012-05-14 16:37:13 -0700414#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -0700415 Tracer::traceEnd(ATRACE_TAG);
Glenn Kasten99c99d02012-05-14 16:37:13 -0700416#endif
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700417 dumpState->mWriteSequence++;
418 if (framesWritten >= 0) {
Glenn Kasten288ed212012-04-25 17:52:27 -0700419 ALOG_ASSERT(framesWritten <= frameCount);
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700420 dumpState->mFramesWritten += framesWritten;
Glenn Kasten288ed212012-04-25 17:52:27 -0700421 //if ((size_t) framesWritten == frameCount) {
422 // didFullWrite = true;
423 //}
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700424 } else {
425 dumpState->mWriteErrors++;
426 }
Glenn Kasten288ed212012-04-25 17:52:27 -0700427 attemptedWrite = true;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700428 // FIXME count # of writes blocked excessively, CPU usage, etc. for dump
429 }
430
431 // To be exactly periodic, compute the next sleep time based on current time.
432 // This code doesn't have long-term stability when the sink is non-blocking.
433 // FIXME To avoid drift, use the local audio clock or watch the sink's fill status.
434 struct timespec newTs;
435 int rc = clock_gettime(CLOCK_MONOTONIC, &newTs);
436 if (rc == 0) {
437 if (oldTsValid) {
438 time_t sec = newTs.tv_sec - oldTs.tv_sec;
439 long nsec = newTs.tv_nsec - oldTs.tv_nsec;
440 if (nsec < 0) {
441 --sec;
442 nsec += 1000000000;
443 }
Glenn Kasten288ed212012-04-25 17:52:27 -0700444 // To avoid an initial underrun on fast tracks after exiting standby,
445 // do not start pulling data from tracks and mixing until warmup is complete.
446 // Warmup is considered complete after the earlier of:
447 // first successful single write() that blocks for more than warmupNs
448 // MAX_WARMUP_CYCLES write() attempts.
449 // This is overly conservative, but to get better accuracy requires a new HAL API.
450 if (!isWarm && attemptedWrite) {
451 measuredWarmupTs.tv_sec += sec;
452 measuredWarmupTs.tv_nsec += nsec;
453 if (measuredWarmupTs.tv_nsec >= 1000000000) {
454 measuredWarmupTs.tv_sec++;
455 measuredWarmupTs.tv_nsec -= 1000000000;
456 }
457 ++warmupCycles;
458 if ((attemptedWrite && nsec > warmupNs) ||
459 (warmupCycles >= MAX_WARMUP_CYCLES)) {
460 isWarm = true;
461 dumpState->mMeasuredWarmupTs = measuredWarmupTs;
462 dumpState->mWarmupCycles = warmupCycles;
463 }
464 }
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700465 if (sec > 0 || nsec > underrunNs) {
Glenn Kasten99c99d02012-05-14 16:37:13 -0700466#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
Glenn Kastend8e6fd32012-05-07 11:07:57 -0700467 ScopedTrace st(ATRACE_TAG, "underrun");
Glenn Kasten99c99d02012-05-14 16:37:13 -0700468#endif
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700469 // FIXME only log occasionally
470 ALOGV("underrun: time since last cycle %d.%03ld sec",
471 (int) sec, nsec / 1000000L);
472 dumpState->mUnderruns++;
473 sleepNs = -1;
474 ignoreNextOverrun = true;
475 } else if (nsec < overrunNs) {
476 if (ignoreNextOverrun) {
477 ignoreNextOverrun = false;
478 } else {
479 // FIXME only log occasionally
480 ALOGV("overrun: time since last cycle %d.%03ld sec",
481 (int) sec, nsec / 1000000L);
482 dumpState->mOverruns++;
483 }
484 sleepNs = periodNs - overrunNs;
485 } else {
486 sleepNs = -1;
487 ignoreNextOverrun = false;
488 }
489#ifdef FAST_MIXER_STATISTICS
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700490 // advance the FIFO queue bounds
491 size_t i = bounds & (FastMixerDumpState::kSamplingN - 1);
Glenn Kastene58ccce2012-05-11 15:19:24 -0700492 bounds = (bounds & 0xFFFF0000) | ((bounds + 1) & 0xFFFF);
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700493 if (full) {
494 bounds += 0x10000;
495 } else if (!(bounds & (FastMixerDumpState::kSamplingN - 1))) {
496 full = true;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700497 }
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700498 // compute the delta value of clock_gettime(CLOCK_MONOTONIC)
499 uint32_t monotonicNs = nsec;
500 if (sec > 0 && sec < 4) {
501 monotonicNs += sec * 1000000000;
502 }
503 // compute the raw CPU load = delta value of clock_gettime(CLOCK_THREAD_CPUTIME_ID)
504 uint32_t loadNs = 0;
505 struct timespec newLoad;
506 rc = clock_gettime(CLOCK_THREAD_CPUTIME_ID, &newLoad);
507 if (rc == 0) {
508 if (oldLoadValid) {
509 sec = newLoad.tv_sec - oldLoad.tv_sec;
510 nsec = newLoad.tv_nsec - oldLoad.tv_nsec;
511 if (nsec < 0) {
512 --sec;
513 nsec += 1000000000;
514 }
515 loadNs = nsec;
516 if (sec > 0 && sec < 4) {
517 loadNs += sec * 1000000000;
518 }
519 } else {
520 // first time through the loop
521 oldLoadValid = true;
522 }
523 oldLoad = newLoad;
524 }
525 // get the absolute value of CPU clock frequency in kHz
526 int cpuNum = sched_getcpu();
527 uint32_t kHz = tcu.getCpukHz(cpuNum);
Glenn Kastenc059bd42012-05-14 17:41:09 -0700528 kHz = (kHz << 4) | (cpuNum & 0xF);
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700529 // save values in FIFO queues for dumpsys
530 // these stores #1, #2, #3 are not atomic with respect to each other,
531 // or with respect to store #4 below
532 dumpState->mMonotonicNs[i] = monotonicNs;
533 dumpState->mLoadNs[i] = loadNs;
534 dumpState->mCpukHz[i] = kHz;
535 // this store #4 is not atomic with respect to stores #1, #2, #3 above, but
536 // the newest open and oldest closed halves are atomic with respect to each other
537 dumpState->mBounds = bounds;
Glenn Kasten99c99d02012-05-14 16:37:13 -0700538#if defined(ATRACE_TAG) && (ATRACE_TAG != ATRACE_TAG_NEVER)
539 ATRACE_INT("cycle_ms", monotonicNs / 1000000);
540 ATRACE_INT("load_us", loadNs / 1000);
541#endif
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700542#endif
543 } else {
544 // first time through the loop
545 oldTsValid = true;
546 sleepNs = periodNs;
547 ignoreNextOverrun = true;
548 }
549 oldTs = newTs;
550 } else {
551 // monotonic clock is broken
552 oldTsValid = false;
553 sleepNs = periodNs;
554 }
555
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700556
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700557 } // for (;;)
558
559 // never return 'true'; Thread::_threadLoop() locks mutex which can result in priority inversion
560}
561
562FastMixerDumpState::FastMixerDumpState() :
563 mCommand(FastMixerState::INITIAL), mWriteSequence(0), mFramesWritten(0),
Glenn Kasten21e8c502012-04-12 09:39:42 -0700564 mNumTracks(0), mWriteErrors(0), mUnderruns(0), mOverruns(0),
Glenn Kasten288ed212012-04-25 17:52:27 -0700565 mSampleRate(0), mFrameCount(0), /* mMeasuredWarmupTs({0, 0}), */ mWarmupCycles(0)
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700566#ifdef FAST_MIXER_STATISTICS
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700567 , mBounds(0)
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700568#endif
569{
Glenn Kasten288ed212012-04-25 17:52:27 -0700570 mMeasuredWarmupTs.tv_sec = 0;
571 mMeasuredWarmupTs.tv_nsec = 0;
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700572 // sample arrays aren't accessed atomically with respect to the bounds,
573 // so clearing reduces chance for dumpsys to read random uninitialized samples
574 memset(&mMonotonicNs, 0, sizeof(mMonotonicNs));
575 memset(&mLoadNs, 0, sizeof(mLoadNs));
576 memset(&mCpukHz, 0, sizeof(mCpukHz));
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700577}
578
579FastMixerDumpState::~FastMixerDumpState()
580{
581}
582
583void FastMixerDumpState::dump(int fd)
584{
585#define COMMAND_MAX 32
586 char string[COMMAND_MAX];
587 switch (mCommand) {
588 case FastMixerState::INITIAL:
589 strcpy(string, "INITIAL");
590 break;
591 case FastMixerState::HOT_IDLE:
592 strcpy(string, "HOT_IDLE");
593 break;
594 case FastMixerState::COLD_IDLE:
595 strcpy(string, "COLD_IDLE");
596 break;
597 case FastMixerState::EXIT:
598 strcpy(string, "EXIT");
599 break;
600 case FastMixerState::MIX:
601 strcpy(string, "MIX");
602 break;
603 case FastMixerState::WRITE:
604 strcpy(string, "WRITE");
605 break;
606 case FastMixerState::MIX_WRITE:
607 strcpy(string, "MIX_WRITE");
608 break;
609 default:
610 snprintf(string, COMMAND_MAX, "%d", mCommand);
611 break;
612 }
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700613 double measuredWarmupMs = (mMeasuredWarmupTs.tv_sec * 1000.0) +
Glenn Kasten288ed212012-04-25 17:52:27 -0700614 (mMeasuredWarmupTs.tv_nsec / 1000000.0);
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700615 double mixPeriodSec = (double) mFrameCount / (double) mSampleRate;
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700616 fdprintf(fd, "FastMixer command=%s writeSequence=%u framesWritten=%u\n"
Glenn Kasten21e8c502012-04-12 09:39:42 -0700617 " numTracks=%u writeErrors=%u underruns=%u overruns=%u\n"
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700618 " sampleRate=%u frameCount=%u measuredWarmup=%.3g ms, warmupCycles=%u\n"
619 " mixPeriod=%.2f ms\n",
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700620 string, mWriteSequence, mFramesWritten,
Glenn Kasten21e8c502012-04-12 09:39:42 -0700621 mNumTracks, mWriteErrors, mUnderruns, mOverruns,
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700622 mSampleRate, mFrameCount, measuredWarmupMs, mWarmupCycles,
623 mixPeriodSec * 1e3);
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700624#ifdef FAST_MIXER_STATISTICS
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700625 // find the interval of valid samples
626 uint32_t bounds = mBounds;
627 uint32_t newestOpen = bounds & 0xFFFF;
628 uint32_t oldestClosed = bounds >> 16;
629 uint32_t n = (newestOpen - oldestClosed) & 0xFFFF;
630 if (n > kSamplingN) {
631 ALOGE("too many samples %u", n);
632 n = kSamplingN;
633 }
634 // statistics for monotonic (wall clock) time, thread raw CPU load in time, CPU clock frequency,
635 // and adjusted CPU load in MHz normalized for CPU clock frequency
636 CentralTendencyStatistics wall, loadNs, kHz, loadMHz;
637 // only compute adjusted CPU load in Hz if current CPU number and CPU clock frequency are stable
638 bool valid = false;
639 uint32_t previousCpukHz = 0;
640 // loop over all the samples
641 for (; n > 0; --n) {
642 size_t i = oldestClosed++ & (kSamplingN - 1);
643 uint32_t wallNs = mMonotonicNs[i];
644 wall.sample(wallNs);
645 uint32_t sampleLoadNs = mLoadNs[i];
646 uint32_t sampleCpukHz = mCpukHz[i];
647 loadNs.sample(sampleLoadNs);
Glenn Kastenc059bd42012-05-14 17:41:09 -0700648 // skip bad kHz samples
649 if ((sampleCpukHz & ~0xF) != 0) {
650 kHz.sample(sampleCpukHz >> 4);
651 if (sampleCpukHz == previousCpukHz) {
652 double megacycles = (double) sampleLoadNs * (double) (sampleCpukHz >> 4) * 1e-12;
653 double adjMHz = megacycles / mixPeriodSec; // _not_ wallNs * 1e9
654 loadMHz.sample(adjMHz);
655 }
Glenn Kasten42d45cf2012-05-02 10:34:47 -0700656 }
657 previousCpukHz = sampleCpukHz;
658 }
659 fdprintf(fd, "Simple moving statistics over last %.1f seconds:\n", wall.n() * mixPeriodSec);
660 fdprintf(fd, " wall clock time in ms per mix cycle:\n"
661 " mean=%.2f min=%.2f max=%.2f stddev=%.2f\n",
662 wall.mean()*1e-6, wall.minimum()*1e-6, wall.maximum()*1e-6, wall.stddev()*1e-6);
663 fdprintf(fd, " raw CPU load in us per mix cycle:\n"
664 " mean=%.0f min=%.0f max=%.0f stddev=%.0f\n",
665 loadNs.mean()*1e-3, loadNs.minimum()*1e-3, loadNs.maximum()*1e-3,
666 loadNs.stddev()*1e-3);
667 fdprintf(fd, " CPU clock frequency in MHz:\n"
668 " mean=%.0f min=%.0f max=%.0f stddev=%.0f\n",
669 kHz.mean()*1e-3, kHz.minimum()*1e-3, kHz.maximum()*1e-3, kHz.stddev()*1e-3);
670 fdprintf(fd, " adjusted CPU load in MHz (i.e. normalized for CPU clock frequency):\n"
671 " mean=%.1f min=%.1f max=%.1f stddev=%.1f\n",
672 loadMHz.mean(), loadMHz.minimum(), loadMHz.maximum(), loadMHz.stddev());
Glenn Kasten97b5d0d2012-03-23 18:54:19 -0700673#endif
674}
675
676} // namespace android