PR #25971 opened by shmuelzon
URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/25971
Patch URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/25971.patch

rtpdec returns the RTP timestamps already unwrapped to 64 bits and,
once RTCP sender reports have been received, relative to an NTP based
origin shared by all streams. The streams created from the SDP were
nevertheless declared with 32-bit timestamps (33 bits for static
payload types without an rtpmap), so the generic timestamp overflow
correction in demux.c was applied on top of that.

A stream whose first packet was sampled before that origin starts with
a small negative timestamp, which is common for audio.
update_wrap_reference() masks it to the wrap bits, takes it for a
timestamp just below the wrap point and picks AV_PTS_WRAP_SUB_OFFSET
with a reference about 60 seconds before 2^32. From then on, every
timestamp past the reference has 2^32 subtracted from it, although
nothing wrapped.

When the first packet is audio, the reference is computed in the audio
time base and copied as is to the video stream. With H.264 video and
48 kHz AAC audio, and the first audio packet 20 ms before the origin,
the video timestamps jump back by 2^32 / 90000 seconds (13h15m) after
47689.8 seconds. With -r on the output, ffmpeg then drops every
following frame as being in the past. On an IP camera, this made the
output of an RTSP to RTMP transcode silently freeze 13h14m50s into the
session.

Declare the RTP streams with 64-bit timestamps, as there is nothing
left to correct. MPEG-TS over RTP is not affected: those streams are
created by the MPEG-TS demuxer and keep their 33-bit wrap correction.

Add a FATE test that feeds a 28 hour H.264 and AAC session with sender
reports through the SDP demuxer using custom I/O and checks that the
timestamps of both streams stay continuous.

Signed-off-by: Assaf Inbal <[email protected]>

# Summary of changes

Briefly describe what this PR does and why.

<!--
If this PR requires new FATE test samples, attach them to the PR and
list their target paths below (relative to the fate-suite root).

Attached filenames must match the sample's filename:

```fate-samples
# e.g. vorbis/new-sample.ogg
```
-->



>From a42496577a8d006fedd43ab78e8eb754f8472433 Mon Sep 17 00:00:00 2001
From: Assaf Inbal <[email protected]>
Date: Thu, 12 Nov 2026 14:16:04 +0200
Subject: [PATCH] avformat/rtsp: mark RTP stream timestamps as non-wrapping

rtpdec returns the RTP timestamps already unwrapped to 64 bits and,
once RTCP sender reports have been received, relative to an NTP based
origin shared by all streams. The streams created from the SDP were
nevertheless declared with 32-bit timestamps (33 bits for static
payload types without an rtpmap), so the generic timestamp overflow
correction in demux.c was applied on top of that.

A stream whose first packet was sampled before that origin starts with
a small negative timestamp, which is common for audio.
update_wrap_reference() masks it to the wrap bits, takes it for a
timestamp just below the wrap point and picks AV_PTS_WRAP_SUB_OFFSET
with a reference about 60 seconds before 2^32. From then on, every
timestamp past the reference has 2^32 subtracted from it, although
nothing wrapped.

When the first packet is audio, the reference is computed in the audio
time base and copied as is to the video stream. With H.264 video and
48 kHz AAC audio, and the first audio packet 20 ms before the origin,
the video timestamps jump back by 2^32 / 90000 seconds (13h15m) after
47689.8 seconds. With -r on the output, ffmpeg then drops every
following frame as being in the past. On an IP camera, this made the
output of an RTSP to RTMP transcode silently freeze 13h14m50s into the
session.

Declare the RTP streams with 64-bit timestamps, as there is nothing
left to correct. MPEG-TS over RTP is not affected: those streams are
created by the MPEG-TS demuxer and keep their 33-bit wrap correction.

Add a FATE test that feeds a 28 hour H.264 and AAC session with sender
reports through the SDP demuxer using custom I/O and checks that the
timestamps of both streams stay continuous.

Signed-off-by: Assaf Inbal <[email protected]>
---
 libavformat/Makefile               |   1 +
 libavformat/rtsp.c                 |   9 +-
 libavformat/tests/rtp_timestamps.c | 244 +++++++++++++++++++++++++++++
 tests/fate/libavformat.mak         |   4 +
 tests/ref/fate/rtp-timestamps      |  58 +++++++
 5 files changed, 313 insertions(+), 3 deletions(-)
 create mode 100644 libavformat/tests/rtp_timestamps.c
 create mode 100644 tests/ref/fate/rtp-timestamps

diff --git a/libavformat/Makefile b/libavformat/Makefile
index 1ccaad27333..32985b408fc 100644
--- a/libavformat/Makefile
+++ b/libavformat/Makefile
@@ -796,6 +796,7 @@ TESTPROGS = demux_probe                                     
            \
             url                                                         \
             seek_utils
 TESTPROGS-$(CONFIG_RTPDEC)               += rtpdec
+TESTPROGS-$(CONFIG_SDP_DEMUXER)          += rtp_timestamps
 #           async                                                       \
 
 FIFO-MUXER-TESTPROGS-$(CONFIG_NETWORK)   += fifo_muxer
diff --git a/libavformat/rtsp.c b/libavformat/rtsp.c
index 9bc389c4526..7cba8f1a563 100644
--- a/libavformat/rtsp.c
+++ b/libavformat/rtsp.c
@@ -359,7 +359,7 @@ static int sdp_parse_rtpmap(AVFormatContext *s,
         par->ch_layout = (AVChannelLayout)AV_CHANNEL_LAYOUT_MONO;
         if (i > 0) {
             par->sample_rate = i;
-            avpriv_set_pts_info(st, 32, 1, par->sample_rate);
+            avpriv_set_pts_info(st, 64, 1, par->sample_rate);
             get_word_sep(buf, sizeof(buf), "/", &p);
             i = atoi(buf);
             if (i > 0)
@@ -373,7 +373,7 @@ static int sdp_parse_rtpmap(AVFormatContext *s,
     case AVMEDIA_TYPE_VIDEO:
         av_log(s, AV_LOG_DEBUG, "video codec set to: %s\n", c_name);
         if (i > 0)
-            avpriv_set_pts_info(st, 32, 1, i);
+            avpriv_set_pts_info(st, 64, 1, i);
         break;
     default:
         break;
@@ -576,13 +576,16 @@ static void sdp_parse_line(AVFormatContext *s, 
SDPParseState *s1,
             st->id = rt->nb_rtsp_streams - 1;
             rtsp_st->stream_index = st->index;
             st->codecpar->codec_type = codec_type;
+            /* rtpdec returns the RTP timestamps already unwrapped, so they
+             * must not be corrected for a 32 (or 33) bit overflow again */
+            avpriv_set_pts_info(st, 64, 1, 90000);
             if (rtsp_st->sdp_payload_type < RTP_PT_PRIVATE) {
                 const RTPDynamicProtocolHandler *handler;
                 /* if standard payload type, we can find the codec right now */
                 ff_rtp_get_codec_info(st->codecpar, rtsp_st->sdp_payload_type);
                 if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
                     st->codecpar->sample_rate > 0)
-                    avpriv_set_pts_info(st, 32, 1, st->codecpar->sample_rate);
+                    avpriv_set_pts_info(st, 64, 1, st->codecpar->sample_rate);
                 /* Even static payload types may need a custom depacketizer */
                 handler = ff_rtp_handler_find_by_id(
                               rtsp_st->sdp_payload_type, 
st->codecpar->codec_type);
diff --git a/libavformat/tests/rtp_timestamps.c 
b/libavformat/tests/rtp_timestamps.c
new file mode 100644
index 00000000000..4bd84981f93
--- /dev/null
+++ b/libavformat/tests/rtp_timestamps.c
@@ -0,0 +1,244 @@
+/*
+ * Copyright (c) 2026 Assaf Inbal
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/*
+ * Long running RTP session through the SDP demuxer (custom I/O), checking
+ * that the timestamps returned by av_read_frame() stay continuous.
+ *
+ * rtpdec already unwraps the 32-bit RTP timestamps and, once RTCP sender
+ * reports are available, maps all streams onto a common NTP based origin.
+ * A stream whose first packet was sampled slightly before that origin thus
+ * starts with a small negative timestamp. This is the normal case for a
+ * camera with audio, since an audio packet carries the timestamp of its
+ * first sample.
+ *
+ * If the generic timestamp overflow correction in libavformat is applied
+ * on top of that, the negative first timestamp is masked to 32 bits and
+ * mistaken for one just below the wrap point, so timestamps from about
+ * 2^32 - 60 seconds onwards get 2^32 subtracted from them. The reference
+ * is computed from the first (audio) packet and shared with the video
+ * stream, so in the session below the video timestamps jump back by
+ * ~13h15m after 47689.8 seconds and the audio ones by ~24h51m after
+ * 89418 seconds.
+ *
+ * The session has one audio (AAC, 48 kHz) and one video (H.264, 90 kHz)
+ * stream, both starting at the same NTP time, with each audio packet
+ * sampled 20 ms before its sender report. An RTCP sender report and one
+ * packet per stream are sent every hour of stream time, for 28 hours.
+ */
+
+#include <inttypes.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "libavutil/intreadwrite.h"
+#include "libavutil/mem.h"
+#include "libavformat/avformat.h"
+
+#define AUDIO_RATE   48000
+#define VIDEO_RATE   90000
+#define AUDIO_SSRC   0x11111111
+#define VIDEO_SSRC   0x22222222
+#define AUDIO_PT     96
+#define VIDEO_PT     97
+#define AUDIO_START  0x89abcdefU
+#define VIDEO_START  0xfedcba98U
+#define AUDIO_LEAD   (AUDIO_RATE / 50)   /* 20 ms */
+#define NTP_START    3992601600U
+#define STEP         3600                /* seconds of stream time per step */
+#define NB_STEPS     29
+
+static const char sdp[] =
+    "v=0\r\n"
+    "o=- 0 0 IN IP4 127.0.0.1\r\n"
+    "s=test\r\n"
+    "c=IN IP4 127.0.0.1\r\n"
+    "t=0 0\r\n"
+    "m=audio 5006 RTP/AVP 96\r\n"
+    "a=rtpmap:96 mpeg4-generic/48000/2\r\n"
+    "a=fmtp:96 streamtype=5;profile-level-id=1;mode=AAC-hbr;config=1190;"
+    "sizelength=13;indexlength=3;indexdeltalength=3\r\n"
+    "a=ssrc:286331153 cname:test\r\n"
+    "m=video 5004 RTP/AVP 97\r\n"
+    "a=rtpmap:97 H264/90000\r\n"
+    "a=ssrc:572662306 cname:test\r\n";
+
+typedef struct Datagram {
+    uint8_t data[28];
+    int size;
+} Datagram;
+
+typedef struct Session {
+    Datagram dgrams[NB_STEPS * 4];
+    int nb, pos;
+    const char *sdp;
+    int sdp_pos, sdp_len;
+} Session;
+
+static void add_sr(Session *s, uint32_t ssrc, uint64_t ntp, uint32_t rtp_ts)
+{
+    Datagram *d = &s->dgrams[s->nb++];
+
+    d->data[0] = 0x80;
+    d->data[1] = 200;                   /* SR */
+    AV_WB16(d->data + 2, 6);
+    AV_WB32(d->data + 4, ssrc);
+    AV_WB64(d->data + 8, ntp);
+    AV_WB32(d->data + 16, rtp_ts);
+    AV_WB32(d->data + 20, 0);
+    AV_WB32(d->data + 24, 0);
+    d->size = 28;
+}
+
+static void add_rtp(Session *s, int pt, uint16_t seq, uint32_t rtp_ts,
+                    uint32_t ssrc, const uint8_t *payload, int size)
+{
+    Datagram *d = &s->dgrams[s->nb++];
+
+    d->data[0] = 0x80;
+    d->data[1] = 0x80 | pt;             /* marker */
+    AV_WB16(d->data + 2, seq);
+    AV_WB32(d->data + 4, rtp_ts);
+    AV_WB32(d->data + 8, ssrc);
+    memcpy(d->data + 12, payload, size);
+    d->size = 12 + size;
+}
+
+static void build_session(Session *s)
+{
+    /* AU-headers-length (16 bits), one AU-header (size 2, index 0), AU */
+    static const uint8_t audio[6] = { 0x00, 0x10, 0x00, 0x10, 0x21, 0x10 };
+    static const uint8_t video[4] = { 0x65, 0x88, 0x84, 0x00 }; /* IDR slice */
+
+    for (int i = 0; i < NB_STEPS; i++) {
+        uint64_t t     = (uint64_t)i * STEP;
+        uint64_t ntp   = (NTP_START + t) << 32;
+        uint32_t a_rtp = AUDIO_START + (uint32_t)(t * AUDIO_RATE);
+        uint32_t v_rtp = VIDEO_START + (uint32_t)(t * VIDEO_RATE);
+
+        add_sr(s, VIDEO_SSRC, ntp, v_rtp);
+        add_sr(s, AUDIO_SSRC, ntp, a_rtp);
+        add_rtp(s, AUDIO_PT, i, a_rtp - AUDIO_LEAD, AUDIO_SSRC, audio, 6);
+        add_rtp(s, VIDEO_PT, i, v_rtp, VIDEO_SSRC, video, 4);
+    }
+}
+
+static int read_sdp(void *opaque, uint8_t *buf, int buf_size)
+{
+    Session *s = opaque;
+    int len = FFMIN(buf_size, s->sdp_len - s->sdp_pos);
+
+    if (len <= 0)
+        return AVERROR_EOF;
+    memcpy(buf, s->sdp + s->sdp_pos, len);
+    s->sdp_pos += len;
+    return len;
+}
+
+static int read_datagram(void *opaque, uint8_t *buf, int buf_size)
+{
+    Session *s = opaque;
+    const Datagram *d;
+
+    if (s->pos >= s->nb)
+        return AVERROR_EOF;
+    d = &s->dgrams[s->pos++];
+    if (d->size > buf_size)
+        return AVERROR(EINVAL);
+    memcpy(buf, d->data, d->size);
+    return d->size;
+}
+
+static int write_datagram(void *opaque, const uint8_t *buf, int buf_size)
+{
+    return buf_size;                    /* RTCP receiver reports */
+}
+
+int main(void)
+{
+    static Session session;
+    AVFormatContext *ctx = NULL;
+    AVIOContext *sdp_pb = NULL, *rtp_pb = NULL;
+    AVDictionary *opts = NULL;
+    AVPacket *pkt = NULL;
+    int64_t last[2] = { INT64_MIN, INT64_MIN };
+    int nb_pkts[2] = { 0 };
+    int ret, failed = 0;
+
+    session.sdp     = sdp;
+    session.sdp_len = strlen(sdp);
+    build_session(&session);
+
+    sdp_pb = avio_alloc_context(av_malloc(4096), 4096, 0, &session,
+                                read_sdp, NULL, NULL);
+    rtp_pb = avio_alloc_context(av_malloc(4096), 4096, 1, &session,
+                                read_datagram, write_datagram, NULL);
+    ctx    = avformat_alloc_context();
+    pkt    = av_packet_alloc();
+    if (!sdp_pb || !rtp_pb || !ctx || !pkt) {
+        ret = AVERROR(ENOMEM);
+        goto end;
+    }
+
+    ctx->pb     = sdp_pb;
+    ctx->flags |= AVFMT_FLAG_NOPARSE;
+    av_dict_set(&opts, "sdp_flags", "custom_io", 0);
+    ret = avformat_open_input(&ctx, "", av_find_input_format("sdp"), &opts);
+    av_dict_free(&opts);
+    if (ret < 0) {
+        fprintf(stderr, "failed to open the SDP: %s\n", av_err2str(ret));
+        goto end;
+    }
+    /* the SDP has been consumed, the datagrams follow on the same context */
+    ctx->pb = rtp_pb;
+
+    while ((ret = av_read_frame(ctx, pkt)) >= 0) {
+        AVStream *st = ctx->streams[pkt->stream_index];
+        int audio    = st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO;
+        int idx      = audio ? 0 : 1;
+        int64_t step = nb_pkts[idx]++;
+        int64_t exp  = audio ? step * STEP * AUDIO_RATE - AUDIO_LEAD
+                             : step * STEP * VIDEO_RATE;
+
+        printf("%s %2"PRId64"h pts %12"PRId64"%s\n", audio ? "audio" : "video",
+               step, pkt->pts, pkt->pts != exp ? " (unexpected)" : "");
+        if (pkt->pts != exp || pkt->pts <= last[idx])
+            failed = 1;
+        last[idx] = pkt->pts;
+        av_packet_unref(pkt);
+    }
+    if (ret == AVERROR_EOF)
+        ret = 0;
+    if (nb_pkts[0] != NB_STEPS || nb_pkts[1] != NB_STEPS)
+        failed = 1;
+
+end:
+    av_packet_free(&pkt);
+    avformat_close_input(&ctx);
+    if (sdp_pb)
+        av_freep(&sdp_pb->buffer);
+    avio_context_free(&sdp_pb);
+    if (rtp_pb)
+        av_freep(&rtp_pb->buffer);
+    avio_context_free(&rtp_pb);
+    if (ret < 0)
+        return 2;
+    return failed;
+}
diff --git a/tests/fate/libavformat.mak b/tests/fate/libavformat.mak
index 70d5439437f..2068e3ef75b 100644
--- a/tests/fate/libavformat.mak
+++ b/tests/fate/libavformat.mak
@@ -68,6 +68,10 @@ FATE_LIBAVFORMAT-$(CONFIG_RTPDEC) += fate-rtpdec
 fate-rtpdec: libavformat/tests/rtpdec$(EXESUF)
 fate-rtpdec: CMD = run libavformat/tests/rtpdec$(EXESUF)
 
+FATE_LIBAVFORMAT-$(CONFIG_SDP_DEMUXER) += fate-rtp-timestamps
+fate-rtp-timestamps: libavformat/tests/rtp_timestamps$(EXESUF)
+fate-rtp-timestamps: CMD = run libavformat/tests/rtp_timestamps$(EXESUF)
+
 FATE_LIBAVFORMAT-$(CONFIG_SRTP) += fate-srtp
 fate-srtp: libavformat/tests/srtp$(EXESUF)
 fate-srtp: CMD = run libavformat/tests/srtp$(EXESUF)
diff --git a/tests/ref/fate/rtp-timestamps b/tests/ref/fate/rtp-timestamps
new file mode 100644
index 00000000000..3e414f5a19d
--- /dev/null
+++ b/tests/ref/fate/rtp-timestamps
@@ -0,0 +1,58 @@
+audio  0h pts         -960
+video  0h pts            0
+audio  1h pts    172799040
+video  1h pts    324000000
+audio  2h pts    345599040
+video  2h pts    648000000
+audio  3h pts    518399040
+video  3h pts    972000000
+audio  4h pts    691199040
+video  4h pts   1296000000
+audio  5h pts    863999040
+video  5h pts   1620000000
+audio  6h pts   1036799040
+video  6h pts   1944000000
+audio  7h pts   1209599040
+video  7h pts   2268000000
+audio  8h pts   1382399040
+video  8h pts   2592000000
+audio  9h pts   1555199040
+video  9h pts   2916000000
+audio 10h pts   1727999040
+video 10h pts   3240000000
+audio 11h pts   1900799040
+video 11h pts   3564000000
+audio 12h pts   2073599040
+video 12h pts   3888000000
+audio 13h pts   2246399040
+video 13h pts   4212000000
+audio 14h pts   2419199040
+video 14h pts   4536000000
+audio 15h pts   2591999040
+video 15h pts   4860000000
+audio 16h pts   2764799040
+video 16h pts   5184000000
+audio 17h pts   2937599040
+video 17h pts   5508000000
+audio 18h pts   3110399040
+video 18h pts   5832000000
+audio 19h pts   3283199040
+video 19h pts   6156000000
+audio 20h pts   3455999040
+video 20h pts   6480000000
+audio 21h pts   3628799040
+video 21h pts   6804000000
+audio 22h pts   3801599040
+video 22h pts   7128000000
+audio 23h pts   3974399040
+video 23h pts   7452000000
+audio 24h pts   4147199040
+video 24h pts   7776000000
+audio 25h pts   4319999040
+video 25h pts   8100000000
+audio 26h pts   4492799040
+video 26h pts   8424000000
+audio 27h pts   4665599040
+video 27h pts   8748000000
+audio 28h pts   4838399040
+video 28h pts   9072000000
-- 
2.54.0

_______________________________________________
ffmpeg-devel mailing list -- [email protected]
To unsubscribe send an email to [email protected]

Reply via email to