From 2a2ef23829059ebdee6fc5248ba22c046aae8102 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Sebastian=20Dr=C3=B6ge?= <sebastian@centricular.com>
Date: Thu, 14 Sep 2023 01:35:10 +0300
Subject: [PATCH] rtpsource: Don't store invalid running times and calculate
 with it

If we end up with GST_CLOCK_TIME_NONE as running time for an RTP packet
then this can't be used for bitrate estimation, and also not for
constructing the next RTCP SR. Both would end up with completely wrong
values, and an RTCP SR with wrong values can easily break
synchronization in receivers.

Part-of: <https://gitlab.freedesktop.org/gstreamer/gstreamer/-/merge_requests/5329>
---
 .../gst-plugins-good/gst/rtpmanager/rtpsource.c | 17 +++++++++++------
 1 file changed, 11 insertions(+), 6 deletions(-)

diff --git a/subprojects/gst-plugins-good/gst/rtpmanager/rtpsource.c b/subprojects/gst-plugins-good/gst/rtpmanager/rtpsource.c
index 04d0ff32f8..673f1ad682 100644
--- a/subprojects/gst-plugins-good/gst/rtpmanager/rtpsource.c
+++ b/subprojects/gst-plugins-good/gst/rtpmanager/rtpsource.c
@@ -1415,7 +1415,8 @@ rtp_source_send_rtp (RTPSource * src, RTPPacketInfo * pinfo)
 
   running_time = pinfo->running_time;
 
-  do_bitrate_estimation (src, running_time, &src->bytes_sent);
+  if (GST_CLOCK_TIME_IS_VALID (running_time))
+    do_bitrate_estimation (src, running_time, &src->bytes_sent);
 
   rtptime = pinfo->rtptime;
 
@@ -1427,7 +1428,9 @@ rtp_source_send_rtp (RTPSource * src, RTPPacketInfo * pinfo)
 
   if (ext_rtptime > src->last_rtptime) {
     rtp_diff = ext_rtptime - src->last_rtptime;
-    rt_diff = running_time - src->last_rtime;
+    rt_diff =
+        GST_CLOCK_TIME_IS_VALID (running_time) ? running_time -
+        src->last_rtime : GST_CLOCK_TIME_NONE;
 
     /* calc the diff so we can detect drift at the sender. This can also be used
      * to guestimate the clock rate if the NTP time is locked to the RTP
@@ -1436,10 +1439,12 @@ rtp_source_send_rtp (RTPSource * src, RTPPacketInfo * pinfo)
         GST_TIME_FORMAT, src->ssrc, rtp_diff, GST_TIME_ARGS (rt_diff));
   }
 
-  /* we keep track of the last received RTP timestamp and the corresponding
-   * buffer running_time so that we can use this info when constructing SR reports */
-  src->last_rtime = running_time;
-  src->last_rtptime = ext_rtptime;
+  if (GST_CLOCK_TIME_IS_VALID (running_time)) {
+    /* we keep track of the last received RTP timestamp and the corresponding
+     * buffer running_time so that we can use this info when constructing SR reports */
+    src->last_rtime = running_time;
+    src->last_rtptime = ext_rtptime;
+  }
 
   /* push packet */
   if (!src->callbacks.push_rtp)