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