From 8e9266a0fb3bd8e4b59797dbd640266532ca7b6d Mon Sep 17 00:00:00 2001
From: Dale Curtis <dalecurtis@chromium.org>
Date: Thu, 30 Apr 2020 13:03:48 -0700
Subject: [PATCH] [libavformat] Avoid integer overflow on start_time with
 skip_samples.

This applies the same workaround used elsewhere in the file for handling
overflow of addition.

Signed-off-by: Dale Curtis <dalecurtis@chromium.org>
---
 libavformat/utils.c | 15 +++++++++++----
 1 file changed, 11 insertions(+), 4 deletions(-)

diff --git a/libavformat/utils.c b/libavformat/utils.c
index 3b53f97bee..c6ba5384eb 100644
--- a/libavformat/utils.c
+++ b/libavformat/utils.c
@@ -1155,8 +1155,11 @@ static void update_initial_timestamps(AVFormatContext *s, int stream_index,
 
         if (st->start_time == AV_NOPTS_VALUE && pktl_it->pkt.pts != AV_NOPTS_VALUE) {
             st->start_time = pktl_it->pkt.pts;
-            if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->sample_rate)
-                st->start_time += av_rescale_q(st->skip_samples, (AVRational){1, st->codecpar->sample_rate}, st->time_base);
+            if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->sample_rate) {
+                int64_t skip_time = av_rescale_q(st->skip_samples, (AVRational){1, st->codecpar->sample_rate}, st->time_base);
+                if (st->start_time > 0 ? skip_time <= INT64_MAX - st->start_time : skip_time >= INT64_MIN - st->start_time)
+                    st->start_time += skip_time;
+            }
         }
     }
 
@@ -1167,9 +1170,13 @@ static void update_initial_timestamps(AVFormatContext *s, int stream_index,
     if (st->start_time == AV_NOPTS_VALUE) {
         if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || !(pkt->flags & AV_PKT_FLAG_DISCARD)) {
             st->start_time = pts;
+
+            if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->sample_rate) {
+                int64_t skip_time = av_rescale_q(st->skip_samples, (AVRational){1, st->codecpar->sample_rate}, st->time_base);
+                if (st->start_time > 0 ? skip_time <= INT64_MAX - st->start_time : skip_time >= INT64_MIN - st->start_time)
+                    st->start_time += skip_time;
+            }
         }
-        if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->sample_rate)
-            st->start_time += av_rescale_q(st->skip_samples, (AVRational){1, st->codecpar->sample_rate}, st->time_base);
     }
 }
 
-- 
2.26.2.526.g744177e7f7-goog

