Search code examples
ffmpegm3u8hls.js

Why m3u8 file does not play well when i manual change m3u8 file


I use ffmpeg to change mp4 to .ts

ffmpeg -y -i [fileName].mp4 -vcodec copy  -vbsf h264_mp4toannexb [outPutFileName].ts

And get the following index.m3u8 file

#EXTM3U
#EXT-X-VERSION:3
#EXT-X-MEDIA-SEQUENCE:0
#EXT-X-ALLOW-CACHE:YES
#EXT-X-TARGETDURATION:22
#EXTINF:21.804344,
out-0000.ts
#EXTINF:10.847822,
out-0001.ts
#EXTINF:12.239122,
out-0002.ts
#EXT-X-ENDLIST

And then i use hls.js play this file

It works fine

But now i want to change this index.m3u8 file to this (copy this out02.ts twice, to repeat out02.ts)

#EXTM3U
#EXT-X-VERSION:3
#EXT-X-MEDIA-SEQUENCE:0
#EXT-X-ALLOW-CACHE:YES
#EXT-X-TARGETDURATION:22
#EXTINF:21.804344,
out-0000.ts
#EXTINF:10.847822,
out-0001.ts
#EXTINF:12.239122,
out-0002.ts
#EXTINF:12.239122,
out-0002.ts
#EXTINF:12.239122,
out-0002.ts
#EXT-X-ENDLIST

The result is this video play time change as expected

but out02 does not repeat, when it play to end of first out02.ts, screen stuck at the begin of out00

Why it does not work fine when i edit this file by myself ? or i shoule use ffmpeg update this index.m3u8 file ?


Solution

  • A similar question was asked and answered here: hls manually add second .ts file to playlist and here: How to include same segment into m3u8 playlist multiple times?

    From there, you just need the piece of information that you need to mark each and every discontinuity in the m3u8 file. You do it by adding the #EXT-X-DISCONTINUITY flag.

    For example, your m3u8 file should look like the following:

    #EXTM3U
    #EXT-X-VERSION:3
    #EXT-X-MEDIA-SEQUENCE:0
    #EXT-X-ALLOW-CACHE:YES
    #EXT-X-TARGETDURATION:22
    #EXTINF:21.804344,
    out-0000.ts
    #EXTINF:10.847822,
    out-0001.ts
    #EXTINF:12.239122,
    out-0002.ts
    #EXT-X-DISCONTINUITY
    #EXTINF:12.239122,
    out-0002.ts
    #EXT-X-DISCONTINUITY
    #EXTINF:12.239122,
    out-0002.ts
    #EXT-X-ENDLIST
    

    This is because playing over and again the out-0002.ts resets the video presentation timestamps over and again, causing a discontinuity, as the ending of the out-0002.ts file has timestamp values 12.239122 seconds after the timestamps of the beginning of the same file.

    Further information here: https://datatracker.ietf.org/doc/html/rfc8216

    The EXT-X-DISCONTINUITY tag indicates a discontinuity between the Media Segment that follows it and the one that preceded it. [...] The EXT-X-DISCONTINUITY tag MUST be present if there is a change in any of the following characteristics: file format; number, type, and identifiers of tracks; timestamp sequence. The EXT-X-DISCONTINUITY tag SHOULD be present if there is a change in any of the following characteristics: encoding parameters; encoding sequence.