video-dev / hls.js

HLS.js is a JavaScript library that plays HLS in browsers with support for MSE.
https://hlsjs.video-dev.org/demo
Other
14.86k stars 2.58k forks source link

Frame accurate seeking in HLS #6649

Closed fredrikj closed 1 month ago

fredrikj commented 2 months ago

My HLS streams (transcoded from MP4 files with AWS MediaConvert) always get a time offset of 0.213 seconds. This causes time update events and seeking to be off by this much time. Is it an inevitable deficiency of HLS to not be frame accurate, or does HLS.js have a way to solve this?

robwalch commented 2 months ago

This is usually the result of audio priming or video composition time pushing frame rendering times on the HTMLVideoElements timeline out a bit.

does HLS.js have a way to solve this?

On Hls.Events.BUFFER_APPENDED get the different between the start of the video buffer and the fragment start time of the first appended segment with video:

let tOffset = 0;
const getAppendedOffset = (eventName, { frag }) => {
  if (frag.type === 'main' && frag.sn !== 'initSegment' && frag.elementaryStreams.video) {
    const { start, startDTS, startPTS, maxStartPTS, elementaryStreams } = frag;
    tOffset = elementaryStreams.video.startPTS - start;
    hls.off(Hls.Events.BUFFER_APPENDED, getAppendedOffset);
    console.log('video timestamp offset:', tOffset, { start, startDTS, startPTS, maxStartPTS, elementaryStreams });
  }
}
hls.on(Hls.Events.BUFFER_APPENDED, getAppendedOffset);
fredrikj commented 2 months ago

Thank you! That solves my issue. Seems to me that this information deserves a place in the documentation, such as in https://github.com/video-dev/hls.js/tree/master?tab=readme-ov-file#using-hlsjs

robwalch commented 2 months ago

Thank you for the suggestion @fredrikj. Would you submit a PR adding that documentation?

robwalch commented 1 month ago

Marking as closed with #6658. Thank you @fredrikj 😃