FastMixer.cpp revision bc6ae9bd4ee93e91e212ad35be038f21797ef31e
1/*
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// <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
23#define LOG_TAG "FastMixer"
24//#define LOG_NDEBUG 0
25
26#define ATRACE_TAG ATRACE_TAG_AUDIO
27
28#include "Configuration.h"
29#include <sys/atomics.h>
30#include <time.h>
31#include <utils/Log.h>
32#include <utils/Trace.h>
33#include <system/audio.h>
34#ifdef FAST_MIXER_STATISTICS
35#include <cpustats/CentralTendencyStatistics.h>
36#ifdef CPU_FREQUENCY_STATISTICS
37#include <cpustats/ThreadCpuUsage.h>
38#endif
39#endif
40#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
45#define MIN_WARMUP_CYCLES          2    // minimum number of loop cycles to wait for warmup
46#define MAX_WARMUP_CYCLES         10    // maximum number of loop cycles to wait for warmup
47
48#define FCC_2                       2   // fixed channel count assumption
49
50namespace 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
78    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
80    long forceNs = 0;       // if overrun detected, force the write cycle to take this much time
81    long warmupNs = 0;      // warmup complete when write cycle is greater than to this value
82    FastMixerDumpState dummyDumpState, *dumpState = &dummyDumpState;
83    bool ignoreNextOverrun = true;  // used to ignore initial overrun and first after an underrun
84#ifdef FAST_MIXER_STATISTICS
85    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;
88    bool full = false;      // whether we have collected at least mSamplingN samples
89#ifdef CPU_FREQUENCY_STATISTICS
90    ThreadCpuUsage tcu;     // for reading the current CPU clock frequency in kHz
91#endif
92#endif
93    unsigned coldGen = 0;   // last observed mColdGen
94    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
97    NBAIO_Sink* teeSink = NULL; // if non-NULL, then duplicate write() to this non-blocking sink
98    NBLog::Writer dummyLogWriter, *logWriter = &dummyLogWriter;
99    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;
105
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;
134            teeSink = next->mTeeSink;
135            logWriter = next->mNBLogWriter != NULL ? next->mNBLogWriter : &dummyLogWriter;
136            if (mixer != NULL) {
137                mixer->setLog(logWriter);
138            }
139
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;
154#ifdef FAST_MIXER_STATISTICS
155                    oldLoadValid = false;
156#endif
157                    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
176            // FIXME consider checking previous state and only perform if previous != COLD_IDLE
177            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                }
184                int policy = sched_getscheduler(0);
185                if (!(policy == SCHED_FIFO || policy == SCHED_RR)) {
186                    ALOGE("did not receive expected priority boost");
187                }
188                // 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;
194                sleepNs = -1;
195                coldGen = current->mColdGen;
196#ifdef FAST_MIXER_STATISTICS
197                bounds = 0;
198                full = false;
199#endif
200                oldTsValid = !clock_gettime(CLOCK_MONOTONIC, &oldTs);
201                timestampStatus = INVALID_OPERATION;
202            } 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_ALWAYS_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);
237                    ALOG_ASSERT(Format_channelCount(format) == FCC_2);
238                }
239                dumpState->mSampleRate = sampleRate;
240            }
241
242            if ((!Format_isEqual(format, previousFormat)) || (frameCount != previous->mFrameCount)) {
243                // FIXME to avoid priority inversion, don't delete here
244                delete mixer;
245                mixer = NULL;
246                delete[] mixBuffer;
247                mixBuffer = NULL;
248                if (frameCount > 0 && sampleRate > 0) {
249                    // FIXME new may block for unbounded time at internal mutex of the heap
250                    //       implementation; it would be better to have normal mixer allocate for us
251                    //       to avoid blocking here and to prevent possible priority inversion
252                    mixer = new AudioMixer(frameCount, sampleRate, FastMixerState::kMaxFastTracks);
253                    mixBuffer = new short[frameCount * FCC_2];
254                    periodNs = (frameCount * 1000000000LL) / sampleRate;    // 1.00
255                    underrunNs = (frameCount * 1750000000LL) / sampleRate;  // 1.75
256                    overrunNs = (frameCount * 500000000LL) / sampleRate;    // 0.50
257                    forceNs = (frameCount * 950000000LL) / sampleRate;      // 0.95
258                    warmupNs = (frameCount * 500000000LL) / sampleRate;     // 0.50
259                } else {
260                    periodNs = 0;
261                    underrunNs = 0;
262                    overrunNs = 0;
263                    forceNs = 0;
264                    warmupNs = 0;
265                }
266                mixBufferState = UNDEFINED;
267#if !LOG_NDEBUG
268                for (i = 0; i < FastMixerState::kMaxFastTracks; ++i) {
269                    fastTrackNames[i] = -1;
270                }
271#endif
272                // we need to reconfigure all active tracks
273                previousTrackMask = 0;
274                fastTracksGen = current->mFastTracksGen - 1;
275                dumpState->mFrameCount = frameCount;
276            } else {
277                previousTrackMask = previous->mTrackMask;
278            }
279
280            // check for change in active track set
281            unsigned currentTrackMask = current->mTrackMask;
282            dumpState->mTrackMask = currentTrackMask;
283            if (current->mFastTracksGen != fastTracksGen) {
284                ALOG_ASSERT(mixBuffer != NULL);
285                int name;
286
287                // process removed tracks first to avoid running out of track names
288                unsigned removedTracks = previousTrackMask & ~currentTrackMask;
289                while (removedTracks != 0) {
290                    i = __builtin_ctz(removedTracks);
291                    removedTracks &= ~(1 << i);
292                    const FastTrack* fastTrack = &current->mFastTracks[i];
293                    ALOG_ASSERT(fastTrack->mBufferProvider == NULL);
294                    if (mixer != NULL) {
295                        name = fastTrackNames[i];
296                        ALOG_ASSERT(name >= 0);
297                        mixer->deleteTrackName(name);
298                    }
299#if !LOG_NDEBUG
300                    fastTrackNames[i] = -1;
301#endif
302                    // don't reset track dump state, since other side is ignoring it
303                    generations[i] = fastTrack->mGeneration;
304                }
305
306                // now process added tracks
307                unsigned addedTracks = currentTrackMask & ~previousTrackMask;
308                while (addedTracks != 0) {
309                    i = __builtin_ctz(addedTracks);
310                    addedTracks &= ~(1 << i);
311                    const FastTrack* fastTrack = &current->mFastTracks[i];
312                    AudioBufferProvider *bufferProvider = fastTrack->mBufferProvider;
313                    ALOG_ASSERT(bufferProvider != NULL && fastTrackNames[i] == -1);
314                    if (mixer != NULL) {
315                        // calling getTrackName with default channel mask and a random invalid
316                        //   sessionId (no effects here)
317                        name = mixer->getTrackName(AUDIO_CHANNEL_OUT_STEREO, -555);
318                        ALOG_ASSERT(name >= 0);
319                        fastTrackNames[i] = name;
320                        mixer->setBufferProvider(name, bufferProvider);
321                        mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::MAIN_BUFFER,
322                                (void *) mixBuffer);
323                        // newly allocated track names default to full scale volume
324                        mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::CHANNEL_MASK,
325                                (void *)(uintptr_t)fastTrack->mChannelMask);
326                        mixer->enable(name);
327                    }
328                    generations[i] = fastTrack->mGeneration;
329                }
330
331                // finally process (potentially) modified tracks; these use the same slot
332                // but may have a different buffer provider or volume provider
333                unsigned modifiedTracks = currentTrackMask & previousTrackMask;
334                while (modifiedTracks != 0) {
335                    i = __builtin_ctz(modifiedTracks);
336                    modifiedTracks &= ~(1 << i);
337                    const FastTrack* fastTrack = &current->mFastTracks[i];
338                    if (fastTrack->mGeneration != generations[i]) {
339                        // this track was actually modified
340                        AudioBufferProvider *bufferProvider = fastTrack->mBufferProvider;
341                        ALOG_ASSERT(bufferProvider != NULL);
342                        if (mixer != NULL) {
343                            name = fastTrackNames[i];
344                            ALOG_ASSERT(name >= 0);
345                            mixer->setBufferProvider(name, bufferProvider);
346                            if (fastTrack->mVolumeProvider == NULL) {
347                                mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME0,
348                                        (void *)0x1000);
349                                mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME1,
350                                        (void *)0x1000);
351                            }
352                            mixer->setParameter(name, AudioMixer::RESAMPLE,
353                                    AudioMixer::REMOVE, NULL);
354                            mixer->setParameter(name, AudioMixer::TRACK, AudioMixer::CHANNEL_MASK,
355                                    (void *)(uintptr_t) fastTrack->mChannelMask);
356                            // already enabled
357                        }
358                        generations[i] = fastTrack->mGeneration;
359                    }
360                }
361
362                fastTracksGen = current->mFastTracksGen;
363
364                dumpState->mNumTracks = popcount(currentTrackMask);
365            }
366
367#if 1   // FIXME shouldn't need this
368            // only process state change once
369            previous = current;
370#endif
371        }
372
373        // do work using current state here
374        if ((command & FastMixerState::MIX) && (mixer != NULL) && isWarm) {
375            ALOG_ASSERT(mixBuffer != NULL);
376            // for each track, update volume and check for underrun
377            unsigned currentTrackMask = current->mTrackMask;
378            while (currentTrackMask != 0) {
379                i = __builtin_ctz(currentTrackMask);
380                currentTrackMask &= ~(1 << i);
381                const FastTrack* fastTrack = &current->mFastTracks[i];
382
383                // Refresh the per-track timestamp
384                if (timestampStatus == NO_ERROR) {
385                    uint32_t trackFramesWrittenButNotPresented =
386                        nativeFramesWrittenButNotPresented;
387                    uint32_t trackFramesWritten = fastTrack->mBufferProvider->framesReleased();
388                    // Can't provide an AudioTimestamp before first frame presented,
389                    // or during the brief 32-bit wraparound window
390                    if (trackFramesWritten >= trackFramesWrittenButNotPresented) {
391                        AudioTimestamp perTrackTimestamp;
392                        perTrackTimestamp.mPosition =
393                                trackFramesWritten - trackFramesWrittenButNotPresented;
394                        perTrackTimestamp.mTime = timestamp.mTime;
395                        fastTrack->mBufferProvider->onTimestamp(perTrackTimestamp);
396                    }
397                }
398
399                int name = fastTrackNames[i];
400                ALOG_ASSERT(name >= 0);
401                if (fastTrack->mVolumeProvider != NULL) {
402                    uint32_t vlr = fastTrack->mVolumeProvider->getVolumeLR();
403                    mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME0,
404                            (void *)(uintptr_t)(vlr & 0xFFFF));
405                    mixer->setParameter(name, AudioMixer::VOLUME, AudioMixer::VOLUME1,
406                            (void *)(uintptr_t)(vlr >> 16));
407                }
408                // FIXME The current implementation of framesReady() for fast tracks
409                // takes a tryLock, which can block
410                // up to 1 ms.  If enough active tracks all blocked in sequence, this would result
411                // in the overall fast mix cycle being delayed.  Should use a non-blocking FIFO.
412                size_t framesReady = fastTrack->mBufferProvider->framesReady();
413                if (ATRACE_ENABLED()) {
414                    // I wish we had formatted trace names
415                    char traceName[16];
416                    strcpy(traceName, "fRdy");
417                    traceName[4] = i + (i < 10 ? '0' : 'A' - 10);
418                    traceName[5] = '\0';
419                    ATRACE_INT(traceName, framesReady);
420                }
421                FastTrackDump *ftDump = &dumpState->mTracks[i];
422                FastTrackUnderruns underruns = ftDump->mUnderruns;
423                if (framesReady < frameCount) {
424                    if (framesReady == 0) {
425                        underruns.mBitFields.mEmpty++;
426                        underruns.mBitFields.mMostRecent = UNDERRUN_EMPTY;
427                        mixer->disable(name);
428                    } else {
429                        // allow mixing partial buffer
430                        underruns.mBitFields.mPartial++;
431                        underruns.mBitFields.mMostRecent = UNDERRUN_PARTIAL;
432                        mixer->enable(name);
433                    }
434                } else {
435                    underruns.mBitFields.mFull++;
436                    underruns.mBitFields.mMostRecent = UNDERRUN_FULL;
437                    mixer->enable(name);
438                }
439                ftDump->mUnderruns = underruns;
440                ftDump->mFramesReady = framesReady;
441            }
442
443            int64_t pts;
444            if (outputSink == NULL || (OK != outputSink->getNextWriteTimestamp(&pts))) {
445                pts = AudioBufferProvider::kInvalidPTS;
446            }
447
448            // process() is CPU-bound
449            mixer->process(pts);
450            mixBufferState = MIXED;
451        } else if (mixBufferState == MIXED) {
452            mixBufferState = UNDEFINED;
453        }
454        bool attemptedWrite = false;
455        //bool didFullWrite = false;    // dumpsys could display a count of partial writes
456        if ((command & FastMixerState::WRITE) && (outputSink != NULL) && (mixBuffer != NULL)) {
457            if (mixBufferState == UNDEFINED) {
458                memset(mixBuffer, 0, frameCount * FCC_2 * sizeof(short));
459                mixBufferState = ZEROED;
460            }
461            if (teeSink != NULL) {
462                (void) teeSink->write(mixBuffer, frameCount);
463            }
464            // FIXME write() is non-blocking and lock-free for a properly implemented NBAIO sink,
465            //       but this code should be modified to handle both non-blocking and blocking sinks
466            dumpState->mWriteSequence++;
467            ATRACE_BEGIN("write");
468            ssize_t framesWritten = outputSink->write(mixBuffer, frameCount);
469            ATRACE_END();
470            dumpState->mWriteSequence++;
471            if (framesWritten >= 0) {
472                ALOG_ASSERT((size_t) framesWritten <= frameCount);
473                totalNativeFramesWritten += framesWritten;
474                dumpState->mFramesWritten = totalNativeFramesWritten;
475                //if ((size_t) framesWritten == frameCount) {
476                //    didFullWrite = true;
477                //}
478            } else {
479                dumpState->mWriteErrors++;
480            }
481            attemptedWrite = true;
482            // FIXME count # of writes blocked excessively, CPU usage, etc. for dump
483
484            timestampStatus = outputSink->getTimestamp(timestamp);
485            if (timestampStatus == NO_ERROR) {
486                uint32_t totalNativeFramesPresented = timestamp.mPosition;
487                if (totalNativeFramesPresented <= totalNativeFramesWritten) {
488                    nativeFramesWrittenButNotPresented =
489                        totalNativeFramesWritten - totalNativeFramesPresented;
490                } else {
491                    // HAL reported that more frames were presented than were written
492                    timestampStatus = INVALID_OPERATION;
493                }
494            }
495        }
496
497        // To be exactly periodic, compute the next sleep time based on current time.
498        // This code doesn't have long-term stability when the sink is non-blocking.
499        // FIXME To avoid drift, use the local audio clock or watch the sink's fill status.
500        struct timespec newTs;
501        int rc = clock_gettime(CLOCK_MONOTONIC, &newTs);
502        if (rc == 0) {
503            //logWriter->logTimestamp(newTs);
504            if (oldTsValid) {
505                time_t sec = newTs.tv_sec - oldTs.tv_sec;
506                long nsec = newTs.tv_nsec - oldTs.tv_nsec;
507                ALOGE_IF(sec < 0 || (sec == 0 && nsec < 0),
508                        "clock_gettime(CLOCK_MONOTONIC) failed: was %ld.%09ld but now %ld.%09ld",
509                        oldTs.tv_sec, oldTs.tv_nsec, newTs.tv_sec, newTs.tv_nsec);
510                if (nsec < 0) {
511                    --sec;
512                    nsec += 1000000000;
513                }
514                // To avoid an initial underrun on fast tracks after exiting standby,
515                // do not start pulling data from tracks and mixing until warmup is complete.
516                // Warmup is considered complete after the earlier of:
517                //      MIN_WARMUP_CYCLES write() attempts and last one blocks for at least warmupNs
518                //      MAX_WARMUP_CYCLES write() attempts.
519                // This is overly conservative, but to get better accuracy requires a new HAL API.
520                if (!isWarm && attemptedWrite) {
521                    measuredWarmupTs.tv_sec += sec;
522                    measuredWarmupTs.tv_nsec += nsec;
523                    if (measuredWarmupTs.tv_nsec >= 1000000000) {
524                        measuredWarmupTs.tv_sec++;
525                        measuredWarmupTs.tv_nsec -= 1000000000;
526                    }
527                    ++warmupCycles;
528                    if ((nsec > warmupNs && warmupCycles >= MIN_WARMUP_CYCLES) ||
529                            (warmupCycles >= MAX_WARMUP_CYCLES)) {
530                        isWarm = true;
531                        dumpState->mMeasuredWarmupTs = measuredWarmupTs;
532                        dumpState->mWarmupCycles = warmupCycles;
533                    }
534                }
535                sleepNs = -1;
536                if (isWarm) {
537                    if (sec > 0 || nsec > underrunNs) {
538                        ATRACE_NAME("underrun");
539                        // FIXME only log occasionally
540                        ALOGV("underrun: time since last cycle %d.%03ld sec",
541                                (int) sec, nsec / 1000000L);
542                        dumpState->mUnderruns++;
543                        ignoreNextOverrun = true;
544                    } else if (nsec < overrunNs) {
545                        if (ignoreNextOverrun) {
546                            ignoreNextOverrun = false;
547                        } else {
548                            // FIXME only log occasionally
549                            ALOGV("overrun: time since last cycle %d.%03ld sec",
550                                    (int) sec, nsec / 1000000L);
551                            dumpState->mOverruns++;
552                        }
553                        // This forces a minimum cycle time. It:
554                        //  - compensates for an audio HAL with jitter due to sample rate conversion
555                        //  - works with a variable buffer depth audio HAL that never pulls at a
556                        //    rate < than overrunNs per buffer.
557                        //  - recovers from overrun immediately after underrun
558                        // It doesn't work with a non-blocking audio HAL.
559                        sleepNs = forceNs - nsec;
560                    } else {
561                        ignoreNextOverrun = false;
562                    }
563                }
564#ifdef FAST_MIXER_STATISTICS
565                if (isWarm) {
566                    // advance the FIFO queue bounds
567                    size_t i = bounds & (dumpState->mSamplingN - 1);
568                    bounds = (bounds & 0xFFFF0000) | ((bounds + 1) & 0xFFFF);
569                    if (full) {
570                        bounds += 0x10000;
571                    } else if (!(bounds & (dumpState->mSamplingN - 1))) {
572                        full = true;
573                    }
574                    // compute the delta value of clock_gettime(CLOCK_MONOTONIC)
575                    uint32_t monotonicNs = nsec;
576                    if (sec > 0 && sec < 4) {
577                        monotonicNs += sec * 1000000000;
578                    }
579                    // compute raw CPU load = delta value of clock_gettime(CLOCK_THREAD_CPUTIME_ID)
580                    uint32_t loadNs = 0;
581                    struct timespec newLoad;
582                    rc = clock_gettime(CLOCK_THREAD_CPUTIME_ID, &newLoad);
583                    if (rc == 0) {
584                        if (oldLoadValid) {
585                            sec = newLoad.tv_sec - oldLoad.tv_sec;
586                            nsec = newLoad.tv_nsec - oldLoad.tv_nsec;
587                            if (nsec < 0) {
588                                --sec;
589                                nsec += 1000000000;
590                            }
591                            loadNs = nsec;
592                            if (sec > 0 && sec < 4) {
593                                loadNs += sec * 1000000000;
594                            }
595                        } else {
596                            // first time through the loop
597                            oldLoadValid = true;
598                        }
599                        oldLoad = newLoad;
600                    }
601#ifdef CPU_FREQUENCY_STATISTICS
602                    // get the absolute value of CPU clock frequency in kHz
603                    int cpuNum = sched_getcpu();
604                    uint32_t kHz = tcu.getCpukHz(cpuNum);
605                    kHz = (kHz << 4) | (cpuNum & 0xF);
606#endif
607                    // save values in FIFO queues for dumpsys
608                    // these stores #1, #2, #3 are not atomic with respect to each other,
609                    // or with respect to store #4 below
610                    dumpState->mMonotonicNs[i] = monotonicNs;
611                    dumpState->mLoadNs[i] = loadNs;
612#ifdef CPU_FREQUENCY_STATISTICS
613                    dumpState->mCpukHz[i] = kHz;
614#endif
615                    // this store #4 is not atomic with respect to stores #1, #2, #3 above, but
616                    // the newest open & oldest closed halves are atomic with respect to each other
617                    dumpState->mBounds = bounds;
618                    ATRACE_INT("cycle_ms", monotonicNs / 1000000);
619                    ATRACE_INT("load_us", loadNs / 1000);
620                }
621#endif
622            } else {
623                // first time through the loop
624                oldTsValid = true;
625                sleepNs = periodNs;
626                ignoreNextOverrun = true;
627            }
628            oldTs = newTs;
629        } else {
630            // monotonic clock is broken
631            oldTsValid = false;
632            sleepNs = periodNs;
633        }
634
635
636    }   // for (;;)
637
638    // never return 'true'; Thread::_threadLoop() locks mutex which can result in priority inversion
639}
640
641FastMixerDumpState::FastMixerDumpState(
642#ifdef FAST_MIXER_STATISTICS
643        uint32_t samplingN
644#endif
645        ) :
646    mCommand(FastMixerState::INITIAL), mWriteSequence(0), mFramesWritten(0),
647    mNumTracks(0), mWriteErrors(0), mUnderruns(0), mOverruns(0),
648    mSampleRate(0), mFrameCount(0), /* mMeasuredWarmupTs({0, 0}), */ mWarmupCycles(0),
649    mTrackMask(0)
650#ifdef FAST_MIXER_STATISTICS
651    , mSamplingN(0), mBounds(0)
652#endif
653{
654    mMeasuredWarmupTs.tv_sec = 0;
655    mMeasuredWarmupTs.tv_nsec = 0;
656#ifdef FAST_MIXER_STATISTICS
657    increaseSamplingN(samplingN);
658#endif
659}
660
661#ifdef FAST_MIXER_STATISTICS
662void FastMixerDumpState::increaseSamplingN(uint32_t samplingN)
663{
664    if (samplingN <= mSamplingN || samplingN > kSamplingN || roundup(samplingN) != samplingN) {
665        return;
666    }
667    uint32_t additional = samplingN - mSamplingN;
668    // sample arrays aren't accessed atomically with respect to the bounds,
669    // so clearing reduces chance for dumpsys to read random uninitialized samples
670    memset(&mMonotonicNs[mSamplingN], 0, sizeof(mMonotonicNs[0]) * additional);
671    memset(&mLoadNs[mSamplingN], 0, sizeof(mLoadNs[0]) * additional);
672#ifdef CPU_FREQUENCY_STATISTICS
673    memset(&mCpukHz[mSamplingN], 0, sizeof(mCpukHz[0]) * additional);
674#endif
675    mSamplingN = samplingN;
676}
677#endif
678
679FastMixerDumpState::~FastMixerDumpState()
680{
681}
682
683// helper function called by qsort()
684static int compare_uint32_t(const void *pa, const void *pb)
685{
686    uint32_t a = *(const uint32_t *)pa;
687    uint32_t b = *(const uint32_t *)pb;
688    if (a < b) {
689        return -1;
690    } else if (a > b) {
691        return 1;
692    } else {
693        return 0;
694    }
695}
696
697void FastMixerDumpState::dump(int fd) const
698{
699    if (mCommand == FastMixerState::INITIAL) {
700        fdprintf(fd, "  FastMixer not initialized\n");
701        return;
702    }
703#define COMMAND_MAX 32
704    char string[COMMAND_MAX];
705    switch (mCommand) {
706    case FastMixerState::INITIAL:
707        strcpy(string, "INITIAL");
708        break;
709    case FastMixerState::HOT_IDLE:
710        strcpy(string, "HOT_IDLE");
711        break;
712    case FastMixerState::COLD_IDLE:
713        strcpy(string, "COLD_IDLE");
714        break;
715    case FastMixerState::EXIT:
716        strcpy(string, "EXIT");
717        break;
718    case FastMixerState::MIX:
719        strcpy(string, "MIX");
720        break;
721    case FastMixerState::WRITE:
722        strcpy(string, "WRITE");
723        break;
724    case FastMixerState::MIX_WRITE:
725        strcpy(string, "MIX_WRITE");
726        break;
727    default:
728        snprintf(string, COMMAND_MAX, "%d", mCommand);
729        break;
730    }
731    double measuredWarmupMs = (mMeasuredWarmupTs.tv_sec * 1000.0) +
732            (mMeasuredWarmupTs.tv_nsec / 1000000.0);
733    double mixPeriodSec = (double) mFrameCount / (double) mSampleRate;
734    fdprintf(fd, "  FastMixer command=%s writeSequence=%u framesWritten=%u\n"
735                 "            numTracks=%u writeErrors=%u underruns=%u overruns=%u\n"
736                 "            sampleRate=%u frameCount=%zu measuredWarmup=%.3g ms, warmupCycles=%u\n"
737                 "            mixPeriod=%.2f ms\n",
738                 string, mWriteSequence, mFramesWritten,
739                 mNumTracks, mWriteErrors, mUnderruns, mOverruns,
740                 mSampleRate, mFrameCount, measuredWarmupMs, mWarmupCycles,
741                 mixPeriodSec * 1e3);
742#ifdef FAST_MIXER_STATISTICS
743    // find the interval of valid samples
744    uint32_t bounds = mBounds;
745    uint32_t newestOpen = bounds & 0xFFFF;
746    uint32_t oldestClosed = bounds >> 16;
747    uint32_t n = (newestOpen - oldestClosed) & 0xFFFF;
748    if (n > mSamplingN) {
749        ALOGE("too many samples %u", n);
750        n = mSamplingN;
751    }
752    // statistics for monotonic (wall clock) time, thread raw CPU load in time, CPU clock frequency,
753    // and adjusted CPU load in MHz normalized for CPU clock frequency
754    CentralTendencyStatistics wall, loadNs;
755#ifdef CPU_FREQUENCY_STATISTICS
756    CentralTendencyStatistics kHz, loadMHz;
757    uint32_t previousCpukHz = 0;
758#endif
759    // Assuming a normal distribution for cycle times, three standard deviations on either side of
760    // the mean account for 99.73% of the population.  So if we take each tail to be 1/1000 of the
761    // sample set, we get 99.8% combined, or close to three standard deviations.
762    static const uint32_t kTailDenominator = 1000;
763    uint32_t *tail = n >= kTailDenominator ? new uint32_t[n] : NULL;
764    // loop over all the samples
765    for (uint32_t j = 0; j < n; ++j) {
766        size_t i = oldestClosed++ & (mSamplingN - 1);
767        uint32_t wallNs = mMonotonicNs[i];
768        if (tail != NULL) {
769            tail[j] = wallNs;
770        }
771        wall.sample(wallNs);
772        uint32_t sampleLoadNs = mLoadNs[i];
773        loadNs.sample(sampleLoadNs);
774#ifdef CPU_FREQUENCY_STATISTICS
775        uint32_t sampleCpukHz = mCpukHz[i];
776        // skip bad kHz samples
777        if ((sampleCpukHz & ~0xF) != 0) {
778            kHz.sample(sampleCpukHz >> 4);
779            if (sampleCpukHz == previousCpukHz) {
780                double megacycles = (double) sampleLoadNs * (double) (sampleCpukHz >> 4) * 1e-12;
781                double adjMHz = megacycles / mixPeriodSec;  // _not_ wallNs * 1e9
782                loadMHz.sample(adjMHz);
783            }
784        }
785        previousCpukHz = sampleCpukHz;
786#endif
787    }
788    if (n) {
789        fdprintf(fd, "  Simple moving statistics over last %.1f seconds:\n",
790                     wall.n() * mixPeriodSec);
791        fdprintf(fd, "    wall clock time in ms per mix cycle:\n"
792                     "      mean=%.2f min=%.2f max=%.2f stddev=%.2f\n",
793                     wall.mean()*1e-6, wall.minimum()*1e-6, wall.maximum()*1e-6,
794                     wall.stddev()*1e-6);
795        fdprintf(fd, "    raw CPU load in us per mix cycle:\n"
796                     "      mean=%.0f min=%.0f max=%.0f stddev=%.0f\n",
797                     loadNs.mean()*1e-3, loadNs.minimum()*1e-3, loadNs.maximum()*1e-3,
798                     loadNs.stddev()*1e-3);
799    } else {
800        fdprintf(fd, "  No FastMixer statistics available currently\n");
801    }
802#ifdef CPU_FREQUENCY_STATISTICS
803    fdprintf(fd, "  CPU clock frequency in MHz:\n"
804                 "    mean=%.0f min=%.0f max=%.0f stddev=%.0f\n",
805                 kHz.mean()*1e-3, kHz.minimum()*1e-3, kHz.maximum()*1e-3, kHz.stddev()*1e-3);
806    fdprintf(fd, "  adjusted CPU load in MHz (i.e. normalized for CPU clock frequency):\n"
807                 "    mean=%.1f min=%.1f max=%.1f stddev=%.1f\n",
808                 loadMHz.mean(), loadMHz.minimum(), loadMHz.maximum(), loadMHz.stddev());
809#endif
810    if (tail != NULL) {
811        qsort(tail, n, sizeof(uint32_t), compare_uint32_t);
812        // assume same number of tail samples on each side, left and right
813        uint32_t count = n / kTailDenominator;
814        CentralTendencyStatistics left, right;
815        for (uint32_t i = 0; i < count; ++i) {
816            left.sample(tail[i]);
817            right.sample(tail[n - (i + 1)]);
818        }
819        fdprintf(fd, "  Distribution of mix cycle times in ms for the tails (> ~3 stddev outliers):\n"
820                     "    left tail: mean=%.2f min=%.2f max=%.2f stddev=%.2f\n"
821                     "    right tail: mean=%.2f min=%.2f max=%.2f stddev=%.2f\n",
822                     left.mean()*1e-6, left.minimum()*1e-6, left.maximum()*1e-6, left.stddev()*1e-6,
823                     right.mean()*1e-6, right.minimum()*1e-6, right.maximum()*1e-6,
824                     right.stddev()*1e-6);
825        delete[] tail;
826    }
827#endif
828    // The active track mask and track states are updated non-atomically.
829    // So if we relied on isActive to decide whether to display,
830    // then we might display an obsolete track or omit an active track.
831    // Instead we always display all tracks, with an indication
832    // of whether we think the track is active.
833    uint32_t trackMask = mTrackMask;
834    fdprintf(fd, "  Fast tracks: kMaxFastTracks=%u activeMask=%#x\n",
835            FastMixerState::kMaxFastTracks, trackMask);
836    fdprintf(fd, "  Index Active Full Partial Empty  Recent Ready\n");
837    for (uint32_t i = 0; i < FastMixerState::kMaxFastTracks; ++i, trackMask >>= 1) {
838        bool isActive = trackMask & 1;
839        const FastTrackDump *ftDump = &mTracks[i];
840        const FastTrackUnderruns& underruns = ftDump->mUnderruns;
841        const char *mostRecent;
842        switch (underruns.mBitFields.mMostRecent) {
843        case UNDERRUN_FULL:
844            mostRecent = "full";
845            break;
846        case UNDERRUN_PARTIAL:
847            mostRecent = "partial";
848            break;
849        case UNDERRUN_EMPTY:
850            mostRecent = "empty";
851            break;
852        default:
853            mostRecent = "?";
854            break;
855        }
856        fdprintf(fd, "  %5u %6s %4u %7u %5u %7s %5zu\n", i, isActive ? "yes" : "no",
857                (underruns.mBitFields.mFull) & UNDERRUN_MASK,
858                (underruns.mBitFields.mPartial) & UNDERRUN_MASK,
859                (underruns.mBitFields.mEmpty) & UNDERRUN_MASK,
860                mostRecent, ftDump->mFramesReady);
861    }
862}
863
864}   // namespace android
865