Commit 55ae5ac12f for ffmpeg

commit 55ae5ac12f4b0ce5753bb0004ebbc220714c6559
Author: Zhao Zhili <quinkblack@foxmail.com>
Date:   Thu Oct 1 18:07:30 2026 +0800

    avcodec/nvenc: derive dts with the shared helper

    nvenc already derives dts from the input pts, delayed by the reorder
    depth, which works at a variable frame rate. Move it onto the shared
    helper so the private timestamp queue and the bookkeeping for the first
    packets can go. The reorder depth is computed as before.

    Add the reorder_delay option, so a user can override the depth.

    Signed-off-by: Zhao Zhili <zhilizhao@tencent.com>

diff --git a/doc/encoders.texi b/doc/encoders.texi
index ce70150054..d85d99776b 100644
--- a/doc/encoders.texi
+++ b/doc/encoders.texi
@@ -4332,6 +4332,23 @@ The default is 0 (no override).
 @item constrained-encoding @var{boolean}
 Enable constrained-frame encoding, making each slice in a constrained
 picture independent of the other slices. The default is 0.
+
+@item reorder_delay @var{integer}
+Set the reorder delay in frames used to generate DTS, since NVENC does not
+report decoding timestamps. This only affects the generated timestamps; the
+number of B-frames is set by @option{bf}. A value below the real reorder
+depth makes DTS non-monotonic, and a larger value lowers every DTS by the
+excess frames. The range is from @code{-2} to @code{16}. The default is
+@samp{auto}.
+
+@table @samp
+@item auto
+Use the number of B-frames between two non-B-frames that the encoder is
+configured with, which comes from @option{bf} or else from the preset. The
+value is doubled when encoding MV-HEVC and limited to @code{16}.
+@item skip
+Leave DTS unset.
+@end table
 @end table

 @subsection HEVC and AV1 options
diff --git a/libavcodec/nvenc.c b/libavcodec/nvenc.c
index 9a4e84f870..48fc8df7ad 100644
--- a/libavcodec/nvenc.c
+++ b/libavcodec/nvenc.c
@@ -1965,11 +1965,6 @@ static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx)
     if (!ctx->frame_data_array)
         return AVERROR(ENOMEM);

-    ctx->timestamp_list = av_fifo_alloc2(ctx->nb_surfaces + ctx->encode_config.frameIntervalP,
-                                         sizeof(int64_t), 0);
-    if (!ctx->timestamp_list)
-        return AVERROR(ENOMEM);
-
     ctx->unused_surface_queue = av_fifo_alloc2(ctx->nb_surfaces, sizeof(NvencSurface*), 0);
     if (!ctx->unused_surface_queue)
         return AVERROR(ENOMEM);
@@ -2051,7 +2046,6 @@ av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
         p_nvenc->nvEncEncodePicture(ctx->nvencoder, &params);
     }

-    av_fifo_freep2(&ctx->timestamp_list);
     av_fifo_freep2(&ctx->output_surface_ready_queue);
     av_fifo_freep2(&ctx->output_surface_queue);
     av_fifo_freep2(&ctx->unused_surface_queue);
@@ -2121,7 +2115,7 @@ av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
 {
     NvencContext *ctx = avctx->priv_data;
-    int ret;
+    int ret, delay;

     if (IS_HWACCEL(avctx->pix_fmt)) {
         AVHWFramesContext *frames_ctx;
@@ -2167,7 +2161,21 @@ av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
             return ret;
     }

-    return 0;
+    if (ctx->reorder_delay != FF_DTS_GEN_DELAY_AUTO) {
+        delay = ctx->reorder_delay;
+    } else {
+        /* frameIntervalP - 1 B pictures sit between two anchors, which bounds
+         * the depth. MV-HEVC interleaves two views that reorder
+         * independently, so the depth doubles.
+         */
+        delay = FFMAX(ctx->encode_config.frameIntervalP - 1, 0);
+#ifdef NVENC_HAVE_MVHEVC
+        delay *= ctx->multiview ? 2 : 1;
+#endif
+        delay = FFMIN(delay, FF_DTS_GEN_DELAY_MAX);
+    }
+
+    return ff_dts_gen_init(avctx, &ctx->dts_gen, delay);
 }

 static NvencSurface *get_free_frame(NvencContext *ctx)
@@ -2488,81 +2496,14 @@ static void nvenc_codec_specific_pic_params(AVCodecContext *avctx, const AVFrame
     }
 }

-static inline void timestamp_queue_enqueue(AVFifo *queue, int64_t timestamp)
-{
-    av_fifo_write(queue, &timestamp, 1);
-}
-
-static inline int64_t timestamp_queue_dequeue(AVFifo *queue)
-{
-    int64_t timestamp = AV_NOPTS_VALUE;
-    // The following call might fail if the queue is empty.
-    av_fifo_read(queue, &timestamp, 1);
-
-    return timestamp;
-}
-
-static inline int64_t timestamp_queue_peek(AVFifo *queue, size_t index)
-{
-    int64_t timestamp = AV_NOPTS_VALUE;
-    av_fifo_peek(queue, &timestamp, 1, index);
-
-    return timestamp;
-}
-
 static int nvenc_set_timestamp(AVCodecContext *avctx,
                                NV_ENC_LOCK_BITSTREAM *params,
                                AVPacket *pkt)
 {
     NvencContext *ctx = avctx->priv_data;
-    unsigned int delay;
-    int64_t delay_time;

     pkt->pts = params->outputTimeStamp;
-
-    if (!(avctx->codec_descriptor->props & AV_CODEC_PROP_REORDER)) {
-        pkt->dts = pkt->pts;
-        return 0;
-    }
-
-    // This can be more than necessary, but we don't know the real reorder delay.
-    delay = FFMAX(ctx->encode_config.frameIntervalP - 1, 0);
-#ifdef NVENC_HAVE_MVHEVC
-    delay *= ctx->multiview ? 2 : 1;
-#endif
-    if (ctx->output_frame_num >= delay) {
-        pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
-        ctx->output_frame_num++;
-        return 0;
-    }
-
-    delay_time = ctx->initial_delay_time;
-    if (!delay_time) {
-        int64_t t1, t2, t3;
-        t1 = timestamp_queue_peek(ctx->timestamp_list, delay);
-        t2 = timestamp_queue_peek(ctx->timestamp_list, 0);
-        t3 = (delay > 1) ? timestamp_queue_peek(ctx->timestamp_list, 1) : t1;
-
-        if (t1 != AV_NOPTS_VALUE) {
-            delay_time = t1 - t2;
-        } else if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {
-            delay_time = av_rescale_q(delay, (AVRational) {avctx->framerate.den, avctx->framerate.num},
-                                      avctx->time_base);
-        } else if (t3 != AV_NOPTS_VALUE) {
-            delay_time = delay * (t3 - t2);
-        } else {
-            delay_time = delay;
-        }
-        ctx->initial_delay_time = delay_time;
-    }
-
-    /* The following method is simple, but doesn't guarantee monotonic with VFR
-     * when delay_time isn't accurate (that is, t1 == AV_NOPTS_VALUE)
-     *
-     * dts = timestamp_queue_peek(ctx->timestamp_list, ctx->output_frame_num) - delay_time
-     */
-    pkt->dts = timestamp_queue_peek(ctx->timestamp_list, 0) - delay_time * (delay - ctx->output_frame_num) / delay;
-    ctx->output_frame_num++;
+    ff_dts_gen_fill_pkt(avctx, &ctx->dts_gen, pkt);

     return 0;
 }
@@ -2633,23 +2574,21 @@ static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSur

     nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
     if (nv_status != NV_ENC_SUCCESS) {
-        res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
-        goto error;
+        return nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
     }

     res = ff_get_encode_buffer(avctx, pkt, lock_params.bitstreamSizeInBytes, 0);

     if (res < 0) {
         p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
-        goto error;
+        return res;
     }

     memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);

     nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
     if (nv_status != NV_ENC_SUCCESS) {
-        res = nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
-        goto error;
+        return nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
     }


@@ -2658,12 +2597,10 @@ static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSur
         if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped == 0) {
             nv_status = p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[tmpoutsurf->reg_idx].in_map.mappedResource);
             if (nv_status != NV_ENC_SUCCESS) {
-                res = nvenc_print_error(avctx, nv_status, "Failed unmapping input resource");
-                goto error;
+                return nvenc_print_error(avctx, nv_status, "Failed unmapping input resource");
             }
         } else if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped < 0) {
-            res = AVERROR_BUG;
-            goto error;
+            return AVERROR_BUG;
         }

         av_frame_unref(tmpoutsurf->in_ref);
@@ -2690,8 +2627,7 @@ static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSur
     default:
         av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
         av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
-        res = AVERROR_EXTERNAL;
-        goto error;
+        return AVERROR_EXTERNAL;
     }

     ff_encode_add_stats_side_data(pkt,
@@ -2699,19 +2635,9 @@ static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSur

     res = nvenc_set_timestamp(avctx, &lock_params, pkt);
     if (res < 0)
-        goto error2;
-
-    res = nvenc_retrieve_frame_data(avctx, &lock_params, pkt);
-    if (res < 0)
-        goto error2;
-
-    return 0;
-
-error:
-    timestamp_queue_dequeue(ctx->timestamp_list);
+        return res;

-error2:
-    return res;
+    return nvenc_retrieve_frame_data(avctx, &lock_params, pkt);
 }

 static int output_ready(AVCodecContext *avctx, int flush)
@@ -3198,9 +3124,7 @@ static int nvenc_send_frame(AVCodecContext *avctx, const AVFrame *frame)

     if (frame && frame->buf[0]) {
         av_fifo_write(ctx->output_surface_queue, &in_surf, 1);
-
-        if (avctx->codec_descriptor->props & AV_CODEC_PROP_REORDER)
-            timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
+        ff_dts_gen_record_pts(&ctx->dts_gen, frame->pts);
     }

     /* all the pending buffers are now ready for output */
@@ -3268,7 +3192,5 @@ av_cold void ff_nvenc_encode_flush(AVCodecContext *avctx)
     NvencContext *ctx = avctx->priv_data;

     nvenc_send_frame(avctx, NULL);
-    av_fifo_reset2(ctx->timestamp_list);
-    ctx->output_frame_num = 0;
-    ctx->initial_delay_time = 0;
+    ff_dts_gen_reset(&ctx->dts_gen);
 }
diff --git a/libavcodec/nvenc.h b/libavcodec/nvenc.h
index 7bb74a17a9..f1ce6090ad 100644
--- a/libavcodec/nvenc.h
+++ b/libavcodec/nvenc.h
@@ -37,6 +37,7 @@ typedef void ID3D11Device;
 #include "hwconfig.h"

 #include "avcodec.h"
+#include "dts_gen.h"

 #define MAX_REGISTERED_FRAMES 64

@@ -191,10 +192,8 @@ typedef struct NvencContext
     AVFifo *unused_surface_queue;
     AVFifo *output_surface_queue;
     AVFifo *output_surface_ready_queue;
-    AVFifo *timestamp_list;
-    // This is for DTS calculating, reset after flush
-    uint64_t output_frame_num;
-    int64_t initial_delay_time;
+
+    FFDTSGen dts_gen;

     NV_ENC_SEI_PAYLOAD *sei_data;
     int sei_data_size;
@@ -277,6 +276,7 @@ typedef struct NvencContext
     int cbr_padding;
     int multiview, multiview_supported;
     int display_sei_sent;
+    int reorder_delay;
 } NvencContext;

 int ff_nvenc_encode_init(AVCodecContext *avctx);
diff --git a/libavcodec/nvenc_h264.c b/libavcodec/nvenc_h264.c
index 103c9a95fd..7a0cb8e28c 100644
--- a/libavcodec/nvenc_h264.c
+++ b/libavcodec/nvenc_h264.c
@@ -176,6 +176,7 @@ static const AVOption options[] = {
                                                             OFFSET(constrained_encoding), AV_OPT_TYPE_BOOL,  { .i64 = 0 }, 0, 1, VE },
     { "cbr_padding",  "Pad the bitstream to ensure bitrate does not drop below the target in CBR mode",
                                                             OFFSET(cbr_padding),  AV_OPT_TYPE_BOOL,  { .i64 = 0 }, 0, 1, VE },
+    FF_DTS_GEN_REORDER_DELAY_OPTION(OFFSET(reorder_delay), VE),
 #ifdef NVENC_HAVE_H264_AND_AV1_TEMPORAL_FILTER
     { "tf_level",     "Specifies the strength of the temporal filtering",
                                                             OFFSET(tf_level),     AV_OPT_TYPE_INT,   { .i64 = -1 }, -1, INT_MAX, VE, .unit = "tf_level" },
diff --git a/libavcodec/nvenc_hevc.c b/libavcodec/nvenc_hevc.c
index 94ba34c48b..17ec674d9d 100644
--- a/libavcodec/nvenc_hevc.c
+++ b/libavcodec/nvenc_hevc.c
@@ -162,6 +162,7 @@ static const AVOption options[] = {
                                                             OFFSET(constrained_encoding), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
     { "cbr_padding",  "Pad the bitstream to ensure bitrate does not drop below the target in CBR mode",
                                                             OFFSET(cbr_padding),  AV_OPT_TYPE_BOOL,  { .i64 = 0 }, 0, 1, VE },
+    FF_DTS_GEN_REORDER_DELAY_OPTION(OFFSET(reorder_delay), VE),
 #ifdef NVENC_HAVE_TEMPORAL_FILTER
     { "tf_level",     "Specifies the strength of the temporal filtering",
                                                             OFFSET(tf_level),     AV_OPT_TYPE_INT,   { .i64 = -1 }, -1, INT_MAX, VE, .unit = "tf_level" },