From 1b60d647a7ca6c1c502c821265b689b847f7255a Mon Sep 17 00:00:00 2001
From: Sebastian Zeller <SebiderSushi@t-online.de>
Date: Tue, 5 Jan 2021 07:09:34 +0100
Subject: [PATCH 3/3] avformat/webvttdec: Calculate hls_ts_offset relative to
 first fragment

---
 libavformat/webvttdec.c | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)

diff --git a/libavformat/webvttdec.c b/libavformat/webvttdec.c
index c6acf8e5bb..cf56f0c232 100644
--- a/libavformat/webvttdec.c
+++ b/libavformat/webvttdec.c
@@ -71,6 +71,7 @@ static int webvtt_read_header(AVFormatContext *s)
     AVStream *st = avformat_new_stream(s, NULL);
     int has_hls_timestamp_map = 0;
     int64_t hls_ts_offset;
+    int64_t hls_ts_offset_global = -1;
 
     if (!st)
         return AVERROR(ENOMEM);
@@ -121,7 +122,14 @@ static int webvtt_read_header(AVFormatContext *s)
                         int64_t mpegts_ts = strtoll(mpegts_str + 7, NULL, 10);
 
                         if (native_ts != AV_NOPTS_VALUE) {
-                            hls_ts_offset = mpegts_ts - native_ts * 90;
+                            /*
+                            * In livestreams the timestamp map can start at any mpegts time.
+                            * Consequently, everything should be treated relative to the first timestamp.
+                            */
+                            if (hls_ts_offset_global == -1) {
+                                hls_ts_offset_global = mpegts_ts;
+                            }
+                            hls_ts_offset = mpegts_ts - native_ts * 90 - hls_ts_offset_global;
                             has_hls_timestamp_map = 1;
                             avpriv_set_pts_info(st, 33, 1, 90000);
                         }
-- 
2.29.2

