Commit e260c25e3a for ffmpeg
commit e260c25e3a20c7a50522ebe2c5ea2ed206f440b1
Author: Zhao Zhili <quinkblack@foxmail.com>
Date: Thu Oct 1 18:05:09 2026 +0800
avcodec/dts_gen: add a helper deriving dts from the pts of packets
Encoders that wrap an external API often get no usable decode
timestamp back, and each of them derives dts from pts in its own way.
Add a helper implementing the ordered window that
compute_muxer_pkt_fields() uses when muxing, so those encoders can
share it, along with the reorder_delay option they offer.
The caller supplies an upper bound on the reorder depth. A smaller
value yields dts values that do not increase, which the helper logs; a
larger one lowers every dts by the excess frames. Packets carry no
reliable duration when the helper runs, so the dts values of the first
packets are extrapolated back from the first input pts, with the
interval between the first input frames. The caller records both. The
first packet does not always carry the earliest pts: an encoder can
emit a reference picture before the pictures that precede it in
presentation order.
A FATE test checks the generated dts against exact values with and
without reordering, at a variable frame rate, and with a delay above
the real depth. It also covers the three ways the first dts values are
spaced, a first packet that is not the earliest, a repeated pts, delay
skipping, a codec that does not reorder, reset, and rejection of
invalid delays.
Signed-off-by: Zhao Zhili <zhilizhao@tencent.com>
diff --git a/libavcodec/Makefile b/libavcodec/Makefile
index 3029b43139..64b404c2a3 100644
--- a/libavcodec/Makefile
+++ b/libavcodec/Makefile
@@ -43,6 +43,7 @@ OBJS = ac3_parser.o \
d3d11va.o \
decode.o \
dirac.o \
+ dts_gen.o \
dv_profile.o \
encode.o \
exif.o \
@@ -1390,6 +1391,7 @@ TESTPROGS = avcodec \
bitstream_be \
bitstream_le \
codec_desc \
+ dts_gen \
htmlsubtitles \
jpeg2000dwt \
mathops \
diff --git a/libavcodec/dts_gen.c b/libavcodec/dts_gen.c
new file mode 100644
index 0000000000..072dd7a903
--- /dev/null
+++ b/libavcodec/dts_gen.c
@@ -0,0 +1,138 @@
+/*
+ * Copyright (c) 2026 Zhao Zhili <quinkblack@foxmail.com>
+ *
+ * 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 "libavutil/common.h"
+#include "libavutil/log.h"
+#include "libavutil/mathematics.h"
+
+#include "codec_desc.h"
+#include "dts_gen.h"
+
+av_cold int ff_dts_gen_init(const AVCodecContext *avctx, FFDTSGen *g,
+ int delay)
+{
+ if (delay < FF_DTS_GEN_DELAY_SKIP || delay > FF_DTS_GEN_DELAY_MAX ||
+ delay == FF_DTS_GEN_DELAY_AUTO)
+ return AVERROR(EINVAL);
+
+ /* Without reordering dts equals pts, and receive_packet encoders get no
+ * generic fallback that sets it, so FF_DTS_GEN_DELAY_SKIP is not honoured.
+ */
+ if (!(avctx->codec_descriptor->props & AV_CODEC_PROP_REORDER))
+ delay = 0;
+
+ *g = (FFDTSGen) {
+ .delay = delay,
+ .prev_dts = AV_NOPTS_VALUE,
+ .first_in_pts = AV_NOPTS_VALUE,
+ .prev_in_pts = AV_NOPTS_VALUE,
+ };
+
+ return 0;
+}
+
+void ff_dts_gen_record_pts(FFDTSGen *g, int64_t pts)
+{
+ if (pts == AV_NOPTS_VALUE)
+ return;
+
+ if (g->first_in_pts == AV_NOPTS_VALUE)
+ g->first_in_pts = pts;
+
+ if (!g->step && g->prev_in_pts != AV_NOPTS_VALUE && pts > g->prev_in_pts)
+ g->step = av_sat_sub64(pts, g->prev_in_pts);
+
+ g->prev_in_pts = pts;
+}
+
+static int64_t dts_gen_step(const AVCodecContext *avctx)
+{
+ if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {
+ int64_t step = av_rescale_q(1,
+ (AVRational) { avctx->framerate.den,
+ avctx->framerate.num },
+ avctx->time_base);
+ if (step > 0)
+ return step;
+ }
+
+ return 1;
+}
+
+void ff_dts_gen_fill_pkt(AVCodecContext *avctx, FFDTSGen *g, AVPacket *pkt)
+{
+ int64_t dts;
+
+ if (g->delay == FF_DTS_GEN_DELAY_SKIP || pkt->pts == AV_NOPTS_VALUE) {
+ pkt->dts = AV_NOPTS_VALUE;
+ return;
+ }
+
+ if (!g->started) {
+ /* A decoder needs delay frames of reordering buffer, so the first
+ * delay packets decode before the first frame is presented and get
+ * timestamps extrapolated from the interval between input frames.
+ * The first packet need not carry the earliest pts, for instance
+ * when an encoder emits a reference picture before the pictures
+ * that precede it in presentation order, so the first input frame
+ * anchors the extrapolation as well.
+ */
+ int64_t step = g->step > 0 ? g->step : dts_gen_step(avctx);
+ int64_t first_pts = g->first_in_pts != AV_NOPTS_VALUE ?
+ FFMIN(g->first_in_pts, pkt->pts) : pkt->pts;
+
+ /* Any positive step keeps these timestamps increasing, so clamping
+ * an absurd interval only keeps the product in range.
+ */
+ step = FFMIN(step, INT64_MAX / (FF_DTS_GEN_DELAY_MAX + 1));
+
+ for (int i = 1; i <= g->delay; i++)
+ g->window[i] = av_sat_sub64(first_pts, (g->delay + 1 - i) * step);
+ g->started = 1;
+ }
+
+ g->window[0] = pkt->pts;
+ for (int i = 0; i < g->delay && g->window[i] > g->window[i + 1]; i++)
+ FFSWAP(int64_t, g->window[i], g->window[i + 1]);
+
+ dts = g->window[0];
+
+ /* Reached when delay is below the real reorder depth, or when two input
+ * frames share a pts, which no delay can fix.
+ */
+ if (g->prev_dts != AV_NOPTS_VALUE && dts <= g->prev_dts)
+ av_log_once(avctx, AV_LOG_ERROR, AV_LOG_VERBOSE, &g->warned,
+ "Generated dts %"PRId64" does not increase over %"PRId64"; "
+ "raise reorder_delay, or check that the input pts values "
+ "are strictly increasing.\n", dts, g->prev_dts);
+
+ g->prev_dts = dts;
+ pkt->dts = dts;
+}
+
+av_cold void ff_dts_gen_reset(FFDTSGen *g)
+{
+ g->first_in_pts = AV_NOPTS_VALUE;
+ g->prev_in_pts = AV_NOPTS_VALUE;
+ g->step = 0;
+ g->prev_dts = AV_NOPTS_VALUE;
+ g->started = 0;
+ g->warned = 0;
+}
diff --git a/libavcodec/dts_gen.h b/libavcodec/dts_gen.h
new file mode 100644
index 0000000000..5e603742c4
--- /dev/null
+++ b/libavcodec/dts_gen.h
@@ -0,0 +1,108 @@
+/*
+ * Copyright (c) 2026 Zhao Zhili <quinkblack@foxmail.com>
+ *
+ * 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
+ */
+
+#ifndef AVCODEC_DTS_GEN_H
+#define AVCODEC_DTS_GEN_H
+
+#include <stdint.h>
+
+#include "libavutil/opt.h"
+
+#include "avcodec.h"
+
+// Special value for reorder delay.
+// Asks the encoder to pick a value itself.
+#define FF_DTS_GEN_DELAY_AUTO -1
+// Leaves pkt->dts unset.
+#define FF_DTS_GEN_DELAY_SKIP -2
+#define FF_DTS_GEN_DELAY_MAX 16
+
+/* AVOption entries for the reorder_delay option. The encoder resolves
+ * FF_DTS_GEN_DELAY_AUTO before passing the value to ff_dts_gen_init().
+ */
+#define FF_DTS_GEN_REORDER_DELAY_OPTION(offset, flags) \
+ { "reorder_delay", "Reorder delay in frames used to generate dts; a value below the real reorder depth makes dts non-monotonic", \
+ offset, AV_OPT_TYPE_INT, { .i64 = FF_DTS_GEN_DELAY_AUTO }, FF_DTS_GEN_DELAY_SKIP, FF_DTS_GEN_DELAY_MAX, flags, .unit = "reorder_delay" }, \
+ { "auto", "Derive the delay from the encoder configuration", \
+ 0, AV_OPT_TYPE_CONST, { .i64 = FF_DTS_GEN_DELAY_AUTO }, 0, 0, flags, .unit = "reorder_delay" }, \
+ { "skip", "Leave dts unset for codecs that support reordering", \
+ 0, AV_OPT_TYPE_CONST, { .i64 = FF_DTS_GEN_DELAY_SKIP }, 0, 0, flags, .unit = "reorder_delay" }
+
+/* Derives pkt->dts for packets emitted in decode order from their pts and
+ * the reorder delay. Packets are not reordered.
+ */
+typedef struct FFDTSGen {
+ /* Configuration, fixed by ff_dts_gen_init(). */
+ int delay;
+
+ /* Input side: the pts of input frames. */
+ int64_t first_in_pts;
+ int64_t prev_in_pts;
+ /* First increasing interval between two input pts. */
+ int64_t step;
+
+ /* Output side: the dts of output packets. */
+ /* pts values kept in ascending order; window[0] is the next dts. */
+ int64_t window[FF_DTS_GEN_DELAY_MAX + 1];
+ int64_t prev_dts;
+ int started;
+ int warned;
+} FFDTSGen;
+
+/* Prepares g for packets emitted in decode order. delay is the reorder
+ * depth: the largest number of frames that precede a frame in decode
+ * order but follow it in display order. It is FF_DTS_GEN_DELAY_SKIP or a
+ * count in [0, FF_DTS_GEN_DELAY_MAX]; the caller resolves
+ * FF_DTS_GEN_DELAY_AUTO.
+ *
+ * Codecs without AV_CODEC_PROP_REORDER get dts == pts whatever delay is.
+ * g->delay holds the effective value, which a caller can publish as
+ * avctx->has_b_frames. A count above the real depth lowers every dts by
+ * the excess frames; a count below it produces dts values that do not
+ * increase, which is logged.
+ *
+ * Returns 0 on success or AVERROR(EINVAL) for any other delay.
+ */
+av_cold int ff_dts_gen_init(const AVCodecContext *avctx, FFDTSGen *g,
+ int delay);
+
+/* Records the pts of an input frame, in display order. The first
+ * increasing interval spaces the dts values of the first packets, so it is
+ * latched. AV_NOPTS_VALUE is ignored.
+ */
+void ff_dts_gen_record_pts(FFDTSGen *g, int64_t pts);
+
+/* Sets pkt->dts. Call once per output packet, in output order, after
+ * setting pkt->pts. pkt->dts becomes AV_NOPTS_VALUE when g uses
+ * FF_DTS_GEN_DELAY_SKIP or pkt->pts is AV_NOPTS_VALUE.
+ *
+ * The first delay packets get dts values below the first input pts, or
+ * below the pts of the first packet when that is earlier, spaced by the
+ * interval recorded by ff_dts_gen_record_pts(), or by avctx->framerate, or
+ * by one tick when neither is known.
+ */
+void ff_dts_gen_fill_pkt(AVCodecContext *avctx, FFDTSGen *g, AVPacket *pkt);
+
+/* Drops the buffered timestamps and the recorded input pts and interval,
+ * keeping the configured delay.
+ */
+av_cold void ff_dts_gen_reset(FFDTSGen *g);
+
+#endif /* AVCODEC_DTS_GEN_H */
diff --git a/libavcodec/tests/dts_gen.c b/libavcodec/tests/dts_gen.c
new file mode 100644
index 0000000000..652f7e560d
--- /dev/null
+++ b/libavcodec/tests/dts_gen.c
@@ -0,0 +1,198 @@
+/*
+ * 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 <stdio.h>
+
+#include "libavutil/macros.h"
+
+#include "libavcodec/avcodec.h"
+#include "libavcodec/codec_desc.h"
+#include "libavcodec/dts_gen.h"
+
+#define NP AV_NOPTS_VALUE
+
+/* Pts of the input frames, in display order. */
+static const int64_t cfr[] = { 0, 10, 20, 30, 40, 50, 60, 70, 80 };
+static const int64_t vfr[] = { 0, 5, 25, 45, 65, 85, 105, 125, 145 };
+
+/* Pts of the output packets, in decode order. */
+static const int64_t cfr_out[] = { 0, 40, 20, 10, 30, 80, 60, 50, 70 };
+static const int64_t vfr_out[] = { 0, 65, 25, 5, 45, 145, 105, 85, 125 };
+
+typedef struct Case {
+ const char *name;
+ enum AVCodecID id;
+ int delay;
+ AVRational framerate;
+ const int64_t *input; /* passed to ff_dts_gen_record_pts() */
+ int nb_input;
+ const int64_t *pts; /* pts of the output packets */
+ int nb;
+ const int64_t *dts; /* expected dts of each output packet */
+ int warned; /* whether a dts that does not increase is reported */
+} Case;
+
+#define ARRAY(a) a, FF_ARRAY_ELEMS(a)
+#define SEQ(...) (const int64_t[]) { __VA_ARGS__ }, \
+ FF_ARRAY_ELEMS(((const int64_t[]) { __VA_ARGS__ }))
+#define DTS(...) (const int64_t[]) { __VA_ARGS__ }
+
+static const Case cases[] = {
+ { "no reordering", AV_CODEC_ID_H264, 0, { 0, 0 },
+ ARRAY(cfr), ARRAY(cfr), DTS(0, 10, 20, 30, 40, 50, 60, 70, 80) },
+ { "reordering", AV_CODEC_ID_H264, 2, { 0, 0 },
+ ARRAY(cfr), ARRAY(cfr_out), DTS(-20, -10, 0, 10, 20, 30, 40, 50, 60) },
+ { "variable frame rate", AV_CODEC_ID_H264, 2, { 0, 0 },
+ ARRAY(vfr), ARRAY(vfr_out), DTS(-10, -5, 0, 5, 25, 45, 65, 85, 105) },
+ { "delay above depth", AV_CODEC_ID_H264, 4, { 0, 0 },
+ ARRAY(cfr), ARRAY(cfr_out), DTS(-40, -30, -20, -10, 0, 10, 20, 30, 40) },
+ { "skip", AV_CODEC_ID_H264, FF_DTS_GEN_DELAY_SKIP, { 0, 0 },
+ ARRAY(cfr), ARRAY(cfr_out), DTS(NP, NP, NP, NP, NP, NP, NP, NP, NP) },
+ /* The window reproduces the repeated pts, so dts stalls. */
+ { "repeated pts", AV_CODEC_ID_H264, 1, { 0, 0 },
+ SEQ(0, 1, 1, 2), SEQ(0, 1, 1, 2), DTS(-1, 0, 1, 1), 1 },
+ /* The first dts values step by the recorded interval, else by the
+ * frame rate, else by one tick.
+ */
+ { "recorded interval", AV_CODEC_ID_H264, 2, { 50, 1 },
+ ARRAY(cfr), ARRAY(cfr_out), DTS(-20, -10, 0, 10, 20, 30, 40, 50, 60) },
+ { "frame rate", AV_CODEC_ID_H264, 2, { 50, 1 },
+ NULL, 0, ARRAY(cfr_out), DTS(-40, -20, 0, 10, 20, 30, 40, 50, 60) },
+ { "one tick", AV_CODEC_ID_H264, 2, { 0, 0 },
+ NULL, 0, ARRAY(cfr_out), DTS(-2, -1, 0, 10, 20, 30, 40, 50, 60) },
+ /* The first packet follows frames that precede it in presentation
+ * order, so the first input pts anchors the first dts values.
+ */
+ { "first packet not earliest", AV_CODEC_ID_H264, 2, { 0, 0 },
+ SEQ(0, 10, 20, 30, 40, 50), SEQ(20, 0, 10, 50, 30, 40),
+ DTS(-20, -10, 0, 10, 20, 30) },
+ /* AV1 does not reorder, so dts equals pts whatever the delay. */
+ { "codec without reordering", AV_CODEC_ID_AV1, FF_DTS_GEN_DELAY_SKIP,
+ { 0, 0 }, ARRAY(cfr), ARRAY(cfr), DTS(0, 10, 20, 30, 40, 50, 60, 70, 80) },
+};
+
+static AVCodecContext *alloc_context(enum AVCodecID id, AVRational framerate)
+{
+ AVCodecContext *avctx = avcodec_alloc_context3(NULL);
+
+ if (avctx) {
+ avctx->codec_id = id;
+ avctx->codec_descriptor = avcodec_descriptor_get(id);
+ avctx->time_base = (AVRational) { 1, 1000 };
+ avctx->framerate = framerate;
+ }
+ return avctx;
+}
+
+static int run_case(const Case *c)
+{
+ AVCodecContext *avctx = alloc_context(c->id, c->framerate);
+ FFDTSGen g;
+ int err = 0;
+
+ if (!avctx || ff_dts_gen_init(avctx, &g, c->delay) < 0) {
+ avcodec_free_context(&avctx);
+ return 1;
+ }
+
+ for (int i = 0; i < c->nb_input; i++)
+ ff_dts_gen_record_pts(&g, c->input[i]);
+
+ for (int i = 0; i < c->nb; i++) {
+ AVPacket pkt = { .pts = c->pts[i] };
+
+ ff_dts_gen_fill_pkt(avctx, &g, &pkt);
+ if (pkt.dts != c->dts[i]) {
+ fprintf(stderr, "%s: packet %d: dts %"PRId64", expected %"PRId64"\n",
+ c->name, i, pkt.dts, c->dts[i]);
+ err = 1;
+ }
+ }
+ if (g.warned != c->warned) {
+ fprintf(stderr, "%s: warned %d, expected %d\n",
+ c->name, g.warned, c->warned);
+ err = 1;
+ }
+
+ avcodec_free_context(&avctx);
+ return err;
+}
+
+/* ff_dts_gen_reset() must drop the recorded interval and the window. */
+static int run_reset(void)
+{
+ AVCodecContext *avctx = alloc_context(AV_CODEC_ID_H264, (AVRational) { 50, 1 });
+ AVPacket pkt = { .pts = 0 };
+ FFDTSGen g;
+ int err = 0;
+
+ if (!avctx || ff_dts_gen_init(avctx, &g, 1) < 0) {
+ avcodec_free_context(&avctx);
+ return 1;
+ }
+
+ ff_dts_gen_record_pts(&g, 0);
+ ff_dts_gen_record_pts(&g, 40);
+ ff_dts_gen_fill_pkt(avctx, &g, &pkt);
+
+ ff_dts_gen_reset(&g);
+ pkt.pts = 100;
+ ff_dts_gen_fill_pkt(avctx, &g, &pkt);
+ if (pkt.dts != 80) {
+ fprintf(stderr, "reset: dts %"PRId64", expected 80\n", pkt.dts);
+ err = 1;
+ }
+
+ avcodec_free_context(&avctx);
+ return err;
+}
+
+static int run_invalid_delays(void)
+{
+ static const int delays[] = { FF_DTS_GEN_DELAY_AUTO,
+ FF_DTS_GEN_DELAY_SKIP - 1,
+ FF_DTS_GEN_DELAY_MAX + 1 };
+ AVCodecContext *avctx = alloc_context(AV_CODEC_ID_H264, (AVRational) { 0, 0 });
+ FFDTSGen g;
+ int err = 0;
+
+ if (!avctx)
+ return 1;
+
+ for (int i = 0; i < FF_ARRAY_ELEMS(delays); i++) {
+ if (ff_dts_gen_init(avctx, &g, delays[i]) != AVERROR(EINVAL)) {
+ fprintf(stderr, "init accepted delay %d\n", delays[i]);
+ err = 1;
+ }
+ }
+
+ avcodec_free_context(&avctx);
+ return err;
+}
+
+int main(void)
+{
+ int err = 0;
+
+ for (int i = 0; i < FF_ARRAY_ELEMS(cases); i++)
+ err |= run_case(&cases[i]);
+ err |= run_reset();
+ err |= run_invalid_delays();
+
+ return err;
+}
diff --git a/tests/fate/libavcodec.mak b/tests/fate/libavcodec.mak
index 11b02ae77c..1b17c6e6de 100644
--- a/tests/fate/libavcodec.mak
+++ b/tests/fate/libavcodec.mak
@@ -56,6 +56,11 @@ fate-golomb: libavcodec/tests/golomb$(EXESUF)
fate-golomb: CMD = run libavcodec/tests/golomb$(EXESUF)
fate-golomb: CMP = null
+FATE_LIBAVCODEC-yes += fate-dts-gen
+fate-dts-gen: libavcodec/tests/dts_gen$(EXESUF)
+fate-dts-gen: CMD = run libavcodec/tests/dts_gen$(EXESUF)
+fate-dts-gen: CMP = null
+
FATE_LIBAVCODEC-$(CONFIG_DXV_ENCODER) += fate-hashtable
fate-hashtable: libavcodec/tests/hashtable$(EXESUF)
fate-hashtable: CMD = run libavcodec/tests/hashtable$(EXESUF)