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