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