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 <time.h>
30 #include <utils/Debug.h>
31 #include <utils/Log.h>
32 #include <utils/Trace.h>
33 #include <system/audio.h>
34 #ifdef FAST_THREAD_STATISTICS
35 #include <audio_utils/Statistics.h>
36 #ifdef CPU_FREQUENCY_STATISTICS
37 #include <cpustats/ThreadCpuUsage.h>
38 #endif
39 #endif
40 #include <audio_utils/channels.h>
41 #include <audio_utils/format.h>
42 #include <audio_utils/mono_blend.h>
43 #include <media/AudioMixer.h>
44 #include "FastMixer.h"
45 #include "TypedLogger.h"
46 
47 namespace android {
48 
49 /*static*/ const FastMixerState FastMixer::sInitial;
50 
FastMixer(audio_io_handle_t parentIoHandle)51 FastMixer::FastMixer(audio_io_handle_t parentIoHandle)
52     : FastThread("cycle_ms", "load_us"),
53     // mFastTrackNames
54     // mGenerations
55     mOutputSink(NULL),
56     mOutputSinkGen(0),
57     mMixer(NULL),
58     mSinkBuffer(NULL),
59     mSinkBufferSize(0),
60     mSinkChannelCount(FCC_2),
61     mMixerBuffer(NULL),
62     mMixerBufferSize(0),
63     mMixerBufferState(UNDEFINED),
64     mFormat(Format_Invalid),
65     mSampleRate(0),
66     mFastTracksGen(0),
67     mTotalNativeFramesWritten(0),
68     // timestamp
69     mNativeFramesWrittenButNotPresented(0),   // the = 0 is to silence the compiler
70     mMasterMono(false),
71     mThreadIoHandle(parentIoHandle)
72 {
73     (void)mThreadIoHandle; // prevent unused warning, see C++17 [[maybe_unused]]
74 
75     // FIXME pass sInitial as parameter to base class constructor, and make it static local
76     mPrevious = &sInitial;
77     mCurrent = &sInitial;
78 
79     mDummyDumpState = &mDummyFastMixerDumpState;
80     // TODO: Add channel mask to NBAIO_Format.
81     // We assume that the channel mask must be a valid positional channel mask.
82     mSinkChannelMask = audio_channel_out_mask_from_count(mSinkChannelCount);
83 
84     unsigned i;
85     for (i = 0; i < FastMixerState::sMaxFastTracks; ++i) {
86         mGenerations[i] = 0;
87     }
88 #ifdef FAST_THREAD_STATISTICS
89     mOldLoad.tv_sec = 0;
90     mOldLoad.tv_nsec = 0;
91 #endif
92 }
93 
~FastMixer()94 FastMixer::~FastMixer()
95 {
96 }
97 
sq()98 FastMixerStateQueue* FastMixer::sq()
99 {
100     return &mSQ;
101 }
102 
poll()103 const FastThreadState *FastMixer::poll()
104 {
105     return mSQ.poll();
106 }
107 
setNBLogWriter(NBLog::Writer * logWriter __unused)108 void FastMixer::setNBLogWriter(NBLog::Writer *logWriter __unused)
109 {
110 }
111 
onIdle()112 void FastMixer::onIdle()
113 {
114     mPreIdle = *(const FastMixerState *)mCurrent;
115     mCurrent = &mPreIdle;
116 }
117 
onExit()118 void FastMixer::onExit()
119 {
120     delete mMixer;
121     free(mMixerBuffer);
122     free(mSinkBuffer);
123 }
124 
isSubClassCommand(FastThreadState::Command command)125 bool FastMixer::isSubClassCommand(FastThreadState::Command command)
126 {
127     switch ((FastMixerState::Command) command) {
128     case FastMixerState::MIX:
129     case FastMixerState::WRITE:
130     case FastMixerState::MIX_WRITE:
131         return true;
132     default:
133         return false;
134     }
135 }
136 
updateMixerTrack(int index,Reason reason)137 void FastMixer::updateMixerTrack(int index, Reason reason) {
138     const FastMixerState * const current = (const FastMixerState *) mCurrent;
139     const FastTrack * const fastTrack = &current->mFastTracks[index];
140 
141     // check and update generation
142     if (reason == REASON_MODIFY && mGenerations[index] == fastTrack->mGeneration) {
143         return; // no change on an already configured track.
144     }
145     mGenerations[index] = fastTrack->mGeneration;
146 
147     // mMixer == nullptr on configuration failure (check done after generation update).
148     if (mMixer == nullptr) {
149         return;
150     }
151 
152     switch (reason) {
153     case REASON_REMOVE:
154         mMixer->destroy(index);
155         break;
156     case REASON_ADD: {
157         const status_t status = mMixer->create(
158                 index, fastTrack->mChannelMask, fastTrack->mFormat, AUDIO_SESSION_OUTPUT_MIX);
159         LOG_ALWAYS_FATAL_IF(status != NO_ERROR,
160                 "%s: cannot create fast track index"
161                 " %d, mask %#x, format %#x in AudioMixer",
162                 __func__, index, fastTrack->mChannelMask, fastTrack->mFormat);
163     }
164         [[fallthrough]];  // now fallthrough to update the newly created track.
165     case REASON_MODIFY:
166         mMixer->setBufferProvider(index, fastTrack->mBufferProvider);
167 
168         float vlf, vrf;
169         if (fastTrack->mVolumeProvider != nullptr) {
170             const gain_minifloat_packed_t vlr = fastTrack->mVolumeProvider->getVolumeLR();
171             vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
172             vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
173         } else {
174             vlf = vrf = AudioMixer::UNITY_GAIN_FLOAT;
175         }
176 
177         // set volume to avoid ramp whenever the track is updated (or created).
178         // Note: this does not distinguish from starting fresh or
179         // resuming from a paused state.
180         mMixer->setParameter(index, AudioMixer::VOLUME, AudioMixer::VOLUME0, &vlf);
181         mMixer->setParameter(index, AudioMixer::VOLUME, AudioMixer::VOLUME1, &vrf);
182 
183         mMixer->setParameter(index, AudioMixer::RESAMPLE, AudioMixer::REMOVE, nullptr);
184         mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::MAIN_BUFFER,
185                 (void *)mMixerBuffer);
186         mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::MIXER_FORMAT,
187                 (void *)(uintptr_t)mMixerBufferFormat);
188         mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::FORMAT,
189                 (void *)(uintptr_t)fastTrack->mFormat);
190         mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::CHANNEL_MASK,
191                 (void *)(uintptr_t)fastTrack->mChannelMask);
192         mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::MIXER_CHANNEL_MASK,
193                 (void *)(uintptr_t)mSinkChannelMask);
194         mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::HAPTIC_ENABLED,
195                 (void *)(uintptr_t)fastTrack->mHapticPlaybackEnabled);
196         mMixer->setParameter(index, AudioMixer::TRACK, AudioMixer::HAPTIC_INTENSITY,
197                 (void *)(uintptr_t)fastTrack->mHapticIntensity);
198 
199         mMixer->enable(index);
200         break;
201     default:
202         LOG_ALWAYS_FATAL("%s: invalid update reason %d", __func__, reason);
203     }
204 }
205 
onStateChange()206 void FastMixer::onStateChange()
207 {
208     const FastMixerState * const current = (const FastMixerState *) mCurrent;
209     const FastMixerState * const previous = (const FastMixerState *) mPrevious;
210     FastMixerDumpState * const dumpState = (FastMixerDumpState *) mDumpState;
211     const size_t frameCount = current->mFrameCount;
212 
213     // update boottime offset, in case it has changed
214     mTimestamp.mTimebaseOffset[ExtendedTimestamp::TIMEBASE_BOOTTIME] =
215             mBoottimeOffset.load();
216 
217     // handle state change here, but since we want to diff the state,
218     // we're prepared for previous == &sInitial the first time through
219     unsigned previousTrackMask;
220 
221     // check for change in output HAL configuration
222     NBAIO_Format previousFormat = mFormat;
223     if (current->mOutputSinkGen != mOutputSinkGen) {
224         mOutputSink = current->mOutputSink;
225         mOutputSinkGen = current->mOutputSinkGen;
226         mSinkChannelMask = current->mSinkChannelMask;
227         mBalance.setChannelMask(mSinkChannelMask);
228         if (mOutputSink == NULL) {
229             mFormat = Format_Invalid;
230             mSampleRate = 0;
231             mSinkChannelCount = 0;
232             mSinkChannelMask = AUDIO_CHANNEL_NONE;
233             mAudioChannelCount = 0;
234         } else {
235             mFormat = mOutputSink->format();
236             mSampleRate = Format_sampleRate(mFormat);
237             mSinkChannelCount = Format_channelCount(mFormat);
238             LOG_ALWAYS_FATAL_IF(mSinkChannelCount > AudioMixer::MAX_NUM_CHANNELS);
239 
240             if (mSinkChannelMask == AUDIO_CHANNEL_NONE) {
241                 mSinkChannelMask = audio_channel_out_mask_from_count(mSinkChannelCount);
242             }
243             mAudioChannelCount = mSinkChannelCount - audio_channel_count_from_out_mask(
244                     mSinkChannelMask & AUDIO_CHANNEL_HAPTIC_ALL);
245         }
246         dumpState->mSampleRate = mSampleRate;
247     }
248 
249     if ((!Format_isEqual(mFormat, previousFormat)) || (frameCount != previous->mFrameCount)) {
250         // FIXME to avoid priority inversion, don't delete here
251         delete mMixer;
252         mMixer = NULL;
253         free(mMixerBuffer);
254         mMixerBuffer = NULL;
255         free(mSinkBuffer);
256         mSinkBuffer = NULL;
257         if (frameCount > 0 && mSampleRate > 0) {
258             // FIXME new may block for unbounded time at internal mutex of the heap
259             //       implementation; it would be better to have normal mixer allocate for us
260             //       to avoid blocking here and to prevent possible priority inversion
261             mMixer = new AudioMixer(frameCount, mSampleRate);
262             // FIXME See the other FIXME at FastMixer::setNBLogWriter()
263             NBLog::thread_params_t params;
264             params.frameCount = frameCount;
265             params.sampleRate = mSampleRate;
266             LOG_THREAD_PARAMS(params);
267             const size_t mixerFrameSize = mSinkChannelCount
268                     * audio_bytes_per_sample(mMixerBufferFormat);
269             mMixerBufferSize = mixerFrameSize * frameCount;
270             (void)posix_memalign(&mMixerBuffer, 32, mMixerBufferSize);
271             const size_t sinkFrameSize = mSinkChannelCount
272                     * audio_bytes_per_sample(mFormat.mFormat);
273             if (sinkFrameSize > mixerFrameSize) { // need a sink buffer
274                 mSinkBufferSize = sinkFrameSize * frameCount;
275                 (void)posix_memalign(&mSinkBuffer, 32, mSinkBufferSize);
276             }
277             mPeriodNs = (frameCount * 1000000000LL) / mSampleRate;    // 1.00
278             mUnderrunNs = (frameCount * 1750000000LL) / mSampleRate;  // 1.75
279             mOverrunNs = (frameCount * 500000000LL) / mSampleRate;    // 0.50
280             mForceNs = (frameCount * 950000000LL) / mSampleRate;      // 0.95
281             mWarmupNsMin = (frameCount * 750000000LL) / mSampleRate;  // 0.75
282             mWarmupNsMax = (frameCount * 1250000000LL) / mSampleRate; // 1.25
283         } else {
284             mPeriodNs = 0;
285             mUnderrunNs = 0;
286             mOverrunNs = 0;
287             mForceNs = 0;
288             mWarmupNsMin = 0;
289             mWarmupNsMax = LONG_MAX;
290         }
291         mMixerBufferState = UNDEFINED;
292         // we need to reconfigure all active tracks
293         previousTrackMask = 0;
294         mFastTracksGen = current->mFastTracksGen - 1;
295         dumpState->mFrameCount = frameCount;
296 #ifdef TEE_SINK
297         mTee.set(mFormat, NBAIO_Tee::TEE_FLAG_OUTPUT_THREAD);
298         mTee.setId(std::string("_") + std::to_string(mThreadIoHandle) + "_F");
299 #endif
300     } else {
301         previousTrackMask = previous->mTrackMask;
302     }
303 
304     // check for change in active track set
305     const unsigned currentTrackMask = current->mTrackMask;
306     dumpState->mTrackMask = currentTrackMask;
307     dumpState->mNumTracks = popcount(currentTrackMask);
308     if (current->mFastTracksGen != mFastTracksGen) {
309 
310         // process removed tracks first to avoid running out of track names
311         unsigned removedTracks = previousTrackMask & ~currentTrackMask;
312         while (removedTracks != 0) {
313             int i = __builtin_ctz(removedTracks);
314             removedTracks &= ~(1 << i);
315             updateMixerTrack(i, REASON_REMOVE);
316             // don't reset track dump state, since other side is ignoring it
317         }
318 
319         // now process added tracks
320         unsigned addedTracks = currentTrackMask & ~previousTrackMask;
321         while (addedTracks != 0) {
322             int i = __builtin_ctz(addedTracks);
323             addedTracks &= ~(1 << i);
324             updateMixerTrack(i, REASON_ADD);
325         }
326 
327         // finally process (potentially) modified tracks; these use the same slot
328         // but may have a different buffer provider or volume provider
329         unsigned modifiedTracks = currentTrackMask & previousTrackMask;
330         while (modifiedTracks != 0) {
331             int i = __builtin_ctz(modifiedTracks);
332             modifiedTracks &= ~(1 << i);
333             updateMixerTrack(i, REASON_MODIFY);
334         }
335 
336         mFastTracksGen = current->mFastTracksGen;
337     }
338 }
339 
onWork()340 void FastMixer::onWork()
341 {
342     // TODO: pass an ID parameter to indicate which time series we want to write to in NBLog.cpp
343     // Or: pass both of these into a single call with a boolean
344     const FastMixerState * const current = (const FastMixerState *) mCurrent;
345     FastMixerDumpState * const dumpState = (FastMixerDumpState *) mDumpState;
346 
347     if (mIsWarm) {
348         // Logging timestamps for FastMixer is currently disabled to make memory room for logging
349         // other statistics in FastMixer.
350         // To re-enable, delete the #ifdef FASTMIXER_LOG_HIST_TS lines (and the #endif lines).
351 #ifdef FASTMIXER_LOG_HIST_TS
352         LOG_HIST_TS();
353 #endif
354         //ALOGD("Eric FastMixer::onWork() mIsWarm");
355     } else {
356         dumpState->mTimestampVerifier.discontinuity();
357         // See comment in if block.
358 #ifdef FASTMIXER_LOG_HIST_TS
359         LOG_AUDIO_STATE();
360 #endif
361     }
362     const FastMixerState::Command command = mCommand;
363     const size_t frameCount = current->mFrameCount;
364 
365     if ((command & FastMixerState::MIX) && (mMixer != NULL) && mIsWarm) {
366         ALOG_ASSERT(mMixerBuffer != NULL);
367 
368         // AudioMixer::mState.enabledTracks is undefined if mState.hook == process__validate,
369         // so we keep a side copy of enabledTracks
370         bool anyEnabledTracks = false;
371 
372         // for each track, update volume and check for underrun
373         unsigned currentTrackMask = current->mTrackMask;
374         while (currentTrackMask != 0) {
375             int i = __builtin_ctz(currentTrackMask);
376             currentTrackMask &= ~(1 << i);
377             const FastTrack* fastTrack = &current->mFastTracks[i];
378 
379             const int64_t trackFramesWrittenButNotPresented =
380                 mNativeFramesWrittenButNotPresented;
381             const int64_t trackFramesWritten = fastTrack->mBufferProvider->framesReleased();
382             ExtendedTimestamp perTrackTimestamp(mTimestamp);
383 
384             // Can't provide an ExtendedTimestamp before first frame presented.
385             // Also, timestamp may not go to very last frame on stop().
386             if (trackFramesWritten >= trackFramesWrittenButNotPresented &&
387                     perTrackTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] > 0) {
388                 perTrackTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
389                         trackFramesWritten - trackFramesWrittenButNotPresented;
390             } else {
391                 perTrackTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = 0;
392                 perTrackTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = -1;
393             }
394             perTrackTimestamp.mPosition[ExtendedTimestamp::LOCATION_SERVER] = trackFramesWritten;
395             fastTrack->mBufferProvider->onTimestamp(perTrackTimestamp);
396 
397             const int name = i;
398             if (fastTrack->mVolumeProvider != NULL) {
399                 gain_minifloat_packed_t vlr = fastTrack->mVolumeProvider->getVolumeLR();
400                 float vlf = float_from_gain(gain_minifloat_unpack_left(vlr));
401                 float vrf = float_from_gain(gain_minifloat_unpack_right(vlr));
402 
403                 mMixer->setParameter(name, AudioMixer::RAMP_VOLUME, AudioMixer::VOLUME0, &vlf);
404                 mMixer->setParameter(name, AudioMixer::RAMP_VOLUME, AudioMixer::VOLUME1, &vrf);
405             }
406             // FIXME The current implementation of framesReady() for fast tracks
407             // takes a tryLock, which can block
408             // up to 1 ms.  If enough active tracks all blocked in sequence, this would result
409             // in the overall fast mix cycle being delayed.  Should use a non-blocking FIFO.
410             size_t framesReady = fastTrack->mBufferProvider->framesReady();
411             if (ATRACE_ENABLED()) {
412                 // I wish we had formatted trace names
413                 char traceName[16];
414                 strcpy(traceName, "fRdy");
415                 traceName[4] = i + (i < 10 ? '0' : 'A' - 10);
416                 traceName[5] = '\0';
417                 ATRACE_INT(traceName, framesReady);
418             }
419             FastTrackDump *ftDump = &dumpState->mTracks[i];
420             FastTrackUnderruns underruns = ftDump->mUnderruns;
421             if (framesReady < frameCount) {
422                 if (framesReady == 0) {
423                     underruns.mBitFields.mEmpty++;
424                     underruns.mBitFields.mMostRecent = UNDERRUN_EMPTY;
425                     mMixer->disable(name);
426                 } else {
427                     // allow mixing partial buffer
428                     underruns.mBitFields.mPartial++;
429                     underruns.mBitFields.mMostRecent = UNDERRUN_PARTIAL;
430                     mMixer->enable(name);
431                     anyEnabledTracks = true;
432                 }
433             } else {
434                 underruns.mBitFields.mFull++;
435                 underruns.mBitFields.mMostRecent = UNDERRUN_FULL;
436                 mMixer->enable(name);
437                 anyEnabledTracks = true;
438             }
439             ftDump->mUnderruns = underruns;
440             ftDump->mFramesReady = framesReady;
441             ftDump->mFramesWritten = trackFramesWritten;
442         }
443 
444         if (anyEnabledTracks) {
445             // process() is CPU-bound
446             mMixer->process();
447             mMixerBufferState = MIXED;
448         } else if (mMixerBufferState != ZEROED) {
449             mMixerBufferState = UNDEFINED;
450         }
451 
452     } else if (mMixerBufferState == MIXED) {
453         mMixerBufferState = UNDEFINED;
454     }
455     //bool didFullWrite = false;    // dumpsys could display a count of partial writes
456     if ((command & FastMixerState::WRITE) && (mOutputSink != NULL) && (mMixerBuffer != NULL)) {
457         if (mMixerBufferState == UNDEFINED) {
458             memset(mMixerBuffer, 0, mMixerBufferSize);
459             mMixerBufferState = ZEROED;
460         }
461 
462         if (mMasterMono.load()) {  // memory_order_seq_cst
463             mono_blend(mMixerBuffer, mMixerBufferFormat, Format_channelCount(mFormat), frameCount,
464                     true /*limit*/);
465         }
466 
467         // Balance must take effect after mono conversion.
468         // mBalance detects zero balance within the class for speed (not needed here).
469         mBalance.setBalance(mMasterBalance.load());
470         mBalance.process((float *)mMixerBuffer, frameCount);
471 
472         // prepare the buffer used to write to sink
473         void *buffer = mSinkBuffer != NULL ? mSinkBuffer : mMixerBuffer;
474         if (mFormat.mFormat != mMixerBufferFormat) { // sink format not the same as mixer format
475             memcpy_by_audio_format(buffer, mFormat.mFormat, mMixerBuffer, mMixerBufferFormat,
476                     frameCount * Format_channelCount(mFormat));
477         }
478         if (mSinkChannelMask & AUDIO_CHANNEL_HAPTIC_ALL) {
479             // When there are haptic channels, the sample data is partially interleaved.
480             // Make the sample data fully interleaved here.
481             adjust_channels_non_destructive(buffer, mAudioChannelCount, buffer, mSinkChannelCount,
482                     audio_bytes_per_sample(mFormat.mFormat),
483                     frameCount * audio_bytes_per_frame(mAudioChannelCount, mFormat.mFormat));
484         }
485         // if non-NULL, then duplicate write() to this non-blocking sink
486 #ifdef TEE_SINK
487         mTee.write(buffer, frameCount);
488 #endif
489         // FIXME write() is non-blocking and lock-free for a properly implemented NBAIO sink,
490         //       but this code should be modified to handle both non-blocking and blocking sinks
491         dumpState->mWriteSequence++;
492         ATRACE_BEGIN("write");
493         ssize_t framesWritten = mOutputSink->write(buffer, frameCount);
494         ATRACE_END();
495         dumpState->mWriteSequence++;
496         if (framesWritten >= 0) {
497             ALOG_ASSERT((size_t) framesWritten <= frameCount);
498             mTotalNativeFramesWritten += framesWritten;
499             dumpState->mFramesWritten = mTotalNativeFramesWritten;
500             //if ((size_t) framesWritten == frameCount) {
501             //    didFullWrite = true;
502             //}
503         } else {
504             dumpState->mWriteErrors++;
505         }
506         mAttemptedWrite = true;
507         // FIXME count # of writes blocked excessively, CPU usage, etc. for dump
508 
509         if (mIsWarm) {
510             ExtendedTimestamp timestamp; // local
511             status_t status = mOutputSink->getTimestamp(timestamp);
512             if (status == NO_ERROR) {
513                 dumpState->mTimestampVerifier.add(
514                         timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL],
515                         timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL],
516                         mSampleRate);
517                 const int64_t totalNativeFramesPresented =
518                         timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
519                 if (totalNativeFramesPresented <= mTotalNativeFramesWritten) {
520                     mNativeFramesWrittenButNotPresented =
521                         mTotalNativeFramesWritten - totalNativeFramesPresented;
522                     mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] =
523                             timestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL];
524                     mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] =
525                             timestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
526                     // We don't compensate for server - kernel time difference and
527                     // only update latency if we have valid info.
528                     const double latencyMs =
529                             (double)mNativeFramesWrittenButNotPresented * 1000 / mSampleRate;
530                     dumpState->mLatencyMs = latencyMs;
531                     LOG_LATENCY(latencyMs);
532                 } else {
533                     // HAL reported that more frames were presented than were written
534                     mNativeFramesWrittenButNotPresented = 0;
535                     status = INVALID_OPERATION;
536                 }
537             } else {
538                 dumpState->mTimestampVerifier.error();
539             }
540             if (status == NO_ERROR) {
541                 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] =
542                         mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL];
543             } else {
544                 // fetch server time if we can't get timestamp
545                 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_SERVER] =
546                         systemTime(SYSTEM_TIME_MONOTONIC);
547                 // clear out kernel cached position as this may get rapidly stale
548                 // if we never get a new valid timestamp
549                 mTimestamp.mPosition[ExtendedTimestamp::LOCATION_KERNEL] = 0;
550                 mTimestamp.mTimeNs[ExtendedTimestamp::LOCATION_KERNEL] = -1;
551             }
552         }
553     }
554 }
555 
556 }   // namespace android
557