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

# Summary of changes

setts has kept every packet until the next one arrives since the NEXT_PTS,
NEXT_DTS and NEXT_DURATION constants were added (9ed3139a76), even when no
expression uses them. Expressions that do not, such as
`max(PTS,PREV_OUTDTS+1)` to keep timestamps from going back, give the same
values without that wait.

The wait shows when streaming. With a sparse stream, for example a timed
metadata track, the muxer holds the other streams back until the held packet
is released, so the output is delayed by up to the interval between that
stream's packets. Once the interval exceeds max_interleave_delta the muxer
stops waiting, and the held packet is written after later packets of the other
streams.

This change holds a packet back only when an expression uses a NEXT_*
constant, and documents the added latency. Output is unchanged for
expressions that do not.

To see it: stream copy a file with a video and a data stream at real-time
speed (`-re`) with `-bsf:d 
"setts=pts='max(PTS,PREV_OUTDTS+1)':dts='max(DTS,PREV_OUTDTS+1)'"`
to MPEG-TS. With one data packet every ~2 s, video leaves about 1.7 s later
without this change. With one every ~12 s, each data packet is written after
30–40 later video frames. The file output is byte-identical with and without
the change when the data stream has a packet on every frame.

Testing:
- New unit test `fate-setts-latency`: checks when each packet can be received
  and its timestamps, with and without NEXT_PTS. It fails without this change.
- `make fate` (no samples) passes on macOS arm64 (clang) and Linux aarch64
  (gcc 14).
- `fate-ffmpeg-setts-bsf` and the 51 `fate-ffmpeg-trim-bsf-*` tests pass with
  their samples.
- The unit test is clean under valgrind and under ASan/UBSan (Linux, gcc), and
  passes on x86-64 (Linux, gcc).

AI assistance: an LLM coding agent wrote this change, the test and this
description, and ran the builds and tests listed above.
I reviewed the diff and re-ran `make fate-setts-latency` and `make fate` in my
own build; both pass.


From 580a3abfc676eb49983744a656e448acb04a3da0 Mon Sep 17 00:00:00 2001
From: Brendan Miesch <[email protected]>
Date: Sat, 14 Nov 2026 19:19:27 -0800
Subject: [PATCH] avcodec/bsf/setts: only hold back a packet when an expression
 uses NEXT_*

Since the NEXT_PTS, NEXT_DTS and NEXT_DURATION constants were added in
9ed3139a76, setts keeps every packet until the following one arrives,
whether or not any expression uses them. Expressions that do not, such as
max(TS,PREV_OUTDTS+1) used to keep timestamps from going back, evaluate to
the same values without that wait.

The wait is visible when streaming: the muxer cannot interleave past the
held packet, so with a sparse stream, such as a timed metadata track, every
stream of the output is delayed by up to the interval between that stream's
packets. Once that interval exceeds max_interleave_delta the muxer stops
waiting and the held packet is written after later packets of the other
streams.

Only hold a packet back when an expression needs the next one, document the
added latency, and add a test for when packets can be received.

Signed-off-by: Brendan Miesch <[email protected]>
---
 doc/bitstream_filters.texi |   4 ++
 libavcodec/Makefile        |   1 +
 libavcodec/bsf/setts.c     |  17 +++++-
 libavcodec/tests/setts.c   | 107 +++++++++++++++++++++++++++++++++++++
 tests/fate/libavcodec.mak  |   5 ++
 5 files changed, 133 insertions(+), 1 deletion(-)
 create mode 100644 libavcodec/tests/setts.c

diff --git a/doc/bitstream_filters.texi b/doc/bitstream_filters.texi
index 1e6438d46b6..93bfaf90bfe 100644
--- a/doc/bitstream_filters.texi
+++ b/doc/bitstream_filters.texi
@@ -1050,6 +1050,10 @@ The sample rate of stream packet belongs.
 The AV_NOPTS_VALUE constant.
 @end table
 
+When any expression uses @code{NEXT_DTS}, @code{NEXT_PTS} or 
@code{NEXT_DURATION}, each
+packet is output only once the packet after it has been received, which adds 
one packet of
+latency. Otherwise each packet is output as soon as it is received.
+
 For example, to set PTS equal to DTS (not recommended if B-frames are 
involved):
 @example
 ffmpeg -i INPUT -c:a copy -bsf:a setts=pts=DTS out.mkv
diff --git a/libavcodec/Makefile b/libavcodec/Makefile
index f12ad9c8e8d..3b2beb29afb 100644
--- a/libavcodec/Makefile
+++ b/libavcodec/Makefile
@@ -1409,6 +1409,7 @@ TESTPROGS-$(CONFIG_MPEGVIDEO)             += 
mpeg12framerate
 TESTPROGS-$(CONFIG_H264_METADATA_BSF)     += h264_levels
 TESTPROGS-$(CONFIG_HEVC_METADATA_BSF)     += h265_levels
 TESTPROGS-$(CONFIG_RANGECODER)            += rangecoder
+TESTPROGS-$(CONFIG_SETTS_BSF)             += setts
 TESTPROGS-$(CONFIG_SNOW_ENCODER)          += snowenc
 
 TESTOBJS = dctref.o
diff --git a/libavcodec/bsf/setts.c b/libavcodec/bsf/setts.c
index 4106eb950e7..22e4bc02685 100644
--- a/libavcodec/bsf/setts.c
+++ b/libavcodec/bsf/setts.c
@@ -92,6 +92,7 @@ typedef struct SetTSContext {
     int prescale;
 
     int64_t frame_number;
+    int lookahead; ///< an expression uses NEXT_*: each packet waits for the 
next one
 
     double var_values[VAR_VARS_NB];
 
@@ -105,6 +106,15 @@ typedef struct SetTSContext {
     AVPacket *cur_pkt;
 } SetTSContext;
 
+static int uses_next_vars(AVExpr *e)
+{
+    unsigned counts[VAR_VARS_NB] = { 0 };
+
+    if (av_expr_count_vars(e, counts, VAR_VARS_NB) < 0)
+        return 0;
+    return counts[VAR_NEXT_PTS] || counts[VAR_NEXT_DTS] || 
counts[VAR_NEXT_DUR];
+}
+
 static int setts_init(AVBSFContext *ctx)
 {
     SetTSContext *s = ctx->priv_data;
@@ -144,6 +154,9 @@ static int setts_init(AVBSFContext *ctx)
         }
     }
 
+    s->lookahead = uses_next_vars(s->ts_expr)  || 
uses_next_vars(s->duration_expr) ||
+                   uses_next_vars(s->pts_expr) || uses_next_vars(s->dts_expr);
+
     if (s->time_base.num > 0 && s->time_base.den > 0) {
         ctx->time_base_out = s->time_base;
         s->user_outtb = 1;
@@ -180,7 +193,9 @@ static int setts_filter(AVBSFContext *ctx, AVPacket *pkt)
     if (ret < 0 && (ret != AVERROR_EOF || !s->cur_pkt->data))
         return ret;
 
-    if (!s->cur_pkt->data) {
+    if (!s->lookahead) {
+        av_packet_move_ref(s->cur_pkt, pkt);
+    } else if (!s->cur_pkt->data) {
          av_packet_move_ref(s->cur_pkt, pkt);
          return AVERROR(EAGAIN);
     }
diff --git a/libavcodec/tests/setts.c b/libavcodec/tests/setts.c
new file mode 100644
index 00000000000..2d571e8c8d8
--- /dev/null
+++ b/libavcodec/tests/setts.c
@@ -0,0 +1,107 @@
+/*
+ * 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
+ */
+
+#include <inttypes.h>
+#include <stdio.h>
+
+#include "libavcodec/bsf.h"
+#include "libavcodec/packet.h"
+#include "libavutil/error.h"
+#include "libavutil/opt.h"
+
+#define NB_PACKETS 5
+
+/** Input timestamps that step back, which max(TS, PREV_OUTDTS + 1) clamps. */
+static const int64_t in_ts[NB_PACKETS]  = { 100,  90, 120, 120, 130 };
+static const int64_t out_ts[NB_PACKETS] = { 100, 101, 120, 121, 130 };
+
+/**
+ * Send NB_PACKETS packets through setts with the given ts expression and check
+ * that each packet can be received delay packets after it was sent, or at EOF.
+ */
+static int check(const char *ts_expr, int delay)
+{
+    const AVBitStreamFilter *filter = av_bsf_get_by_name("setts");
+    AVBSFContext *bsf = NULL;
+    AVPacket *pkt = av_packet_alloc();
+    int received = 0, ret = AVERROR(ENOMEM);
+
+    if (!filter || !pkt)
+        goto end;
+    ret = av_bsf_alloc(filter, &bsf);
+    if (ret < 0)
+        goto end;
+    bsf->time_base_in = (AVRational){ 1, 90000 };
+    ret = av_opt_set(bsf->priv_data, "ts", ts_expr, 0);
+    if (ret >= 0)
+        ret = av_bsf_init(bsf);
+    if (ret < 0)
+        goto end;
+
+    for (int i = 0; i <= NB_PACKETS; i++) {
+        int expected = i < NB_PACKETS ? i + 1 - delay : NB_PACKETS;
+
+        if (i < NB_PACKETS) {
+            ret = av_new_packet(pkt, 1);
+            if (ret < 0)
+                goto end;
+            pkt->pts = pkt->dts = in_ts[i];
+            ret = av_bsf_send_packet(bsf, pkt);
+        } else {
+            ret = av_bsf_send_packet(bsf, NULL);
+        }
+        if (ret < 0)
+            goto end;
+
+        while ((ret = av_bsf_receive_packet(bsf, pkt)) >= 0) {
+            if (received >= NB_PACKETS || pkt->pts != out_ts[received] ||
+                pkt->dts != out_ts[received]) {
+                fprintf(stderr, "'%s': packet %d has pts/dts 
%"PRId64"/%"PRId64"\n",
+                        ts_expr, received, pkt->pts, pkt->dts);
+                ret = AVERROR_BUG;
+                goto end;
+            }
+            received++;
+            av_packet_unref(pkt);
+        }
+        if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
+            goto end;
+        if (received != expected) {
+            fprintf(stderr, "'%s': %d packets out after %s, expected %d\n", 
ts_expr,
+                    received, i < NB_PACKETS ? "a send" : "EOF", expected);
+            ret = AVERROR_BUG;
+            goto end;
+        }
+    }
+    ret = 0;
+
+end:
+    av_bsf_free(&bsf);
+    av_packet_free(&pkt);
+    return ret;
+}
+
+int main(void)
+{
+    if (check("max(TS, PREV_OUTDTS + 1)", 0) < 0)
+        return 1;
+    /* NEXT_PTS needs the following packet, so each packet waits for it. */
+    if (check("max(TS, PREV_OUTDTS + 1) + 0 * NEXT_PTS", 1) < 0)
+        return 1;
+    return 0;
+}
diff --git a/tests/fate/libavcodec.mak b/tests/fate/libavcodec.mak
index 2e2dabcd148..5b4c6296e95 100644
--- a/tests/fate/libavcodec.mak
+++ b/tests/fate/libavcodec.mak
@@ -108,6 +108,11 @@ fate-rangecoder: libavcodec/tests/rangecoder$(EXESUF)
 fate-rangecoder: CMD = run libavcodec/tests/rangecoder$(EXESUF)
 fate-rangecoder: CMP = null
 
+FATE_LIBAVCODEC-$(CONFIG_SETTS_BSF) += fate-setts-latency
+fate-setts-latency: libavcodec/tests/setts$(EXESUF)
+fate-setts-latency: CMD = run libavcodec/tests/setts$(EXESUF)
+fate-setts-latency: CMP = null
+
 FATE_LIBAVCODEC-$(CONFIG_SNOW_ENCODER) += fate-snow-dwt
 fate-snow-dwt: libavcodec/tests/snowenc$(EXESUF)
 fate-snow-dwt: CMD = run libavcodec/tests/snowenc$(EXESUF)
-- 
2.54.0

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

Reply via email to