Daniel Grima
Daniel Grima

Reputation: 2825

Using video.js is it possible to get current HLS timestamp?

I have an application which is embedding a live stream in it. To cater for delays I'd like to know what is the current timestamp of the stream and compare it with the time on the server.

What I have tested up till now is checking the difference between the buffered time of the video with the current time of the video:

player.bufferedEnd() - player.currentTime()

However I'd like to compare the time with the server instead and to do so I need to get the timestamp of the last requested .ts file.

So, my question is using video.js, is there some sort of hook to get the timestamp of the last requested .ts file?

Video.js version: 7.4.1

Upvotes: 2

Views: 6102

Answers (1)

Daniel Grima
Daniel Grima

Reputation: 2825

I had managed to solve this issue, however please bear with me I don't remember where I had found the documentation for this bit of code.

In my case I was working in an Angular application, I had a video component responsible for loading a live stream with the use of video.js. Anyway let's see some code...

Video initialisation

private videoInit() {
    this.player = videojs('video', {
        aspectRatio: this.videoStream.aspectRatio,
        controls: true,
        autoplay: false,
        muted: true,
        html5: {
            hls: {
                overrideNative: true
            }
        }
    });

    this.player.src({
        src: '://some-stream-url.com',
        type: 'application/x-mpegURL'
    });

    // on video play callback
    this.player.on('play', () => {
        this.saveHlsObject();
    });
}

Save HLS Object

private saveHlsObject() {
    if (this.player !== undefined) {
        this.playerHls = (this.player.tech() as any).hls;

        // get and syncing server time...
        // make some request to get server time...
        // then calculate difference...
        this.diff = serverTime.getTime() - this.getVideoTime().getTime();
    }
}

Get Timestamp of Video Segment

// access the player's playlists, get the last segment and extract time
// in my case URI of segments were for example: 1590763989033.ts
private getVideoTime(): Date {
    const targetMedia = this.playerHls.playlists.media();

    const lastSegment = targetMedia.segments[0];

    const uri: string = lastSegment.uri;
    const segmentTimestamp: number = +uri.substring(0, uri.length - 3);

    return new Date(segmentTimestamp);
}

So above the main point is the getVideoTime function. The time of a segment can be found in the segment URI, so that function extracts the time from the segment URI and then converts it to a Date object. Now to be honest, I don't know if this URI format is something that's a standard for HLS or something that was set for the particular stream I was connecting to. Hope this helps, and sorry I don't have any more specific information!

Upvotes: 2

Related Questions