Search code examples
http-live-streamingelapsedtimehls.js

HLS protocol: get absolute elapsed time during a live streaming


I have a very basic question and I didn't get if I googled wrong or if the answer is so simple that I haven't seen it.

I'm implementing a web app using hls.js as Javascript library and I need a way to get the absolute elapsed time of a live streaming e.g. if a user join the live after 10 minutes, I need a way to detect that the user's 1st second is 601st second of the streaming.

Inspecting the streaming fragments I found some information like startPTS and endPTS, but all these information were always related to the retrieved chunks instead of the whole streaming chunks e.g. if a user join the live after 10 minutes and the chunks duration is 2 seconds, the first chunk I'll get will have startPTS = 0 and endPTS = 2, the second chunk I'll get will have startPTS = 2 and endPTS = 4 and so on (rounding the values to the nearest integer).

Is there a way to extract the absolute elapsed time as I need from an HLS live streaming ?


Solution

  • I'm having the exact same need on iOS (AVPlayer) and came with the following solution:

    1. read the m3u8 manifest, for me it looks like this:
    #EXTM3U
    #EXT-X-VERSION:3
    #EXT-X-MEDIA-SEQUENCE:410
    #EXT-X-TARGETDURATION:8
    #EXTINF:8.333,
    410.ts
    #EXTINF:8.333,
    411.ts
    #EXTINF:8.334,
    412.ts
    #EXTINF:8.333,
    413.ts
    #EXTINF:8.333,
    414.ts
    #EXTINF:8.334,
    415.ts
    
    1. Observe that the 409 first segments are not part of the manifest
    2. Multiply EXT-X-MEDIA-SEQUENCE by EXT-X-TARGETDURATION and you have an approximation of the clock time for the first available segment.

    Let's also notice that each segment is not exactly 8s long, so when I'm using the target duration, I'm actually accumulating an error of about 333ms per segment:

    410 * 8 = 3280 seconds = 54.6666 minutes
    

    In this case for me the segments are always 8.333 or 8.334, so by EXTINF instead, I get:

    410 * 8.333 = 3416.53 seconds = 56.9421 minutes
    

    These almost 56.9421 minutes is still an approximation (since we don't exactly know how many time we accumulated the new 0.001 error), but it's much much closer to the real clock time.