Commit c605d33b01 for ffmpeg

commit c605d33b01742f8d39a35f89c064d1939ac0a338
Author: lusoris <lusoris@proton.me>
Date:   Sun Nov 8 17:01:29 2026 +0100

    avcodec/libsvtav1: add a qpfile option

    Add the qpfile option of libaom-av1 to libsvtav1, with the same file
    format, and pass each record to SVT-AV1 as a region-of-interest map
    event. SVT-AV1 keeps each map until the next event, so an event is
    sent whenever the record a frame uses differs from the one SVT-AV1
    last accepted: normally on the frame of the record, or on the next
    frame when the frame of the record is refused. A record without
    offset lines sends a neutral map, so the previous map ends there. The
    offsets are AV1 quantizer index deltas.

    The frame number counts every input frame, also one that the encoder
    refuses, so the frames after a refused frame keep their own records.

    SVT-AV1 applies ROI maps only with CRF or constant-QP rate control
    (rc 0), so another rate control mode is refused. It takes one value
    per 64x64 superblock: the offsets of the 16x16 blocks of a superblock
    are averaged, and the averages are mapped to at most 8 segment values.
    The segment values are passed in descending order with a nonnegative
    first entry, because SVT-AV1 before 4.3.0 searches the lower segment
    ids for a positive quantizer index and has no fallback below segment
    0; with an ascending or all-negative table, SVT-AV1 1.7.0 writes
    streams that do not decode.

    SVT-AV1 reads the map with the superblock positions of the scaled
    frame but the stride of the full-size map, so with superres-mode or
    resize-mode other than 0 the offsets land on other superblocks: two
    maps that differ in one superblock column give byte-identical streams
    with SVT-AV1 1.7.0 and 4.2.0. Internal scaling is therefore refused.

    SVT-AV1 can also encode the first pass of a two-pass encode at a
    reduced size and then reads the map with the layout of the reduced
    frame: two maps that differ only in the third of four superblock
    columns give byte-identical first-pass streams and statistics with
    SVT-AV1 4.2.0, while a change in the second column does show. The
    first pass is therefore refused too, whether it is selected with the
    pass1 flag or with pass=1 in svtav1-params.

    The events are built when the encoder opens, since SVT-AV1 keeps
    pointers to them for the whole encode. The 16x16 offsets are freed
    once the events are built, so the encode keeps one byte per 64x64
    superblock and record: 2,040 bytes per record at 3840x2160.

    SVT-AV1 has the ROI map API from 1.6.0 on; built against an older
    SVT-AV1, the option is refused.

    The scaling and first-pass refusals, the frame counting and the
    resending of the map in force follow Forgejo Fairy reviews of this
    option; one of them also provided the patch that frees the 16x16
    offsets.

    Signed-off-by: lusoris <lusoris@proton.me>

diff --git a/configure b/configure
index cb39b436a1..02680a01e1 100755
--- a/configure
+++ b/configure
@@ -3869,7 +3869,7 @@ libspeex_encoder_select="audio_frame_queue"
 libsvtav1_encoder_deps="libsvtav1"
 libsvtjpegxs_encoder_deps="libsvtjpegxs"
 libsvtjpegxs_decoder_deps="libsvtjpegxs"
-libsvtav1_encoder_select="dovi_rpuenc"
+libsvtav1_encoder_select="dovi_rpuenc qpfile"
 libtheora_encoder_deps="libtheora"
 libtwolame_encoder_deps="libtwolame"
 libuavs3d_decoder_deps="libuavs3d"
diff --git a/doc/encoders.texi b/doc/encoders.texi
index 7b9c29ffa1..34b8f257dd 100644
--- a/doc/encoders.texi
+++ b/doc/encoders.texi
@@ -2120,6 +2120,51 @@ Set log2 of the number of rows of tiles to use (0-6).
 @item tile_columns
 Set log2 of the number of columns of tiles to use (0-4).

+@item qpfile @var{filename}
+Read per-frame QP offsets from @var{filename} and pass them to SVT-AV1 as
+region-of-interest map events. SVT-AV1 applies the maps only with CRF or
+constant-QP rate control, so the option is refused unless the effective
+rate-control mode is 0: a target bit rate set with @option{b} selects
+another mode unless @option{crf} or @option{qp} is also set above 0, and
+@samp{rc} in @option{svtav1-params} overrides both. Internal scaling, a
+@samp{superres-mode} or @samp{resize-mode} other than 0 in
+@option{svtav1-params}, is refused too: SVT-AV1 would apply the map to the
+scaled frame with the layout of the full-size frame, moving the offsets to
+other superblocks. The first pass of a two-pass encode, the @code{pass1}
+flag or @samp{pass=1} in @option{svtav1-params}, is refused as well:
+SVT-AV1 can encode that pass at a reduced size and would then read the map
+with the layout of the reduced frame.
+
+The file is plain text. Each record starts with a header line
+@samp{@var{frame} @var{type} @var{qp}}, where @var{frame} is the 0-based
+input frame number, strictly increasing from record to record.
+@var{type} is @samp{I}, @samp{P} or @samp{B} in either case, and
+@var{qp} is an integer from 0 to 63; both are checked but not used.
+Frame numbers go up to 4294967295, and a file holds at most 1048576 records.
+Zero or more lines of whitespace-separated integer offsets follow,
+one line per row of 16x16 blocks and one value per block column; the grid
+must match the video size rounded up to 16 pixels. Offsets are clipped to
+the range -12 to 12. Lines holding only spaces or tabs and lines starting with
+@samp{#} are skipped; a line with a NUL byte is refused. A frame uses the last
+record whose number is not greater than its own. SVT-AV1 keeps each map
+until the next event, so an event is sent only when the record a frame uses
+differs from the one last sent, normally on the frame of the record; a
+record without offset lines sends a neutral map. The offsets are AV1
+quantizer index deltas, so the same offset changes the quality less than
+with libaom-av1.
+
+The ROI map contains one value per 64x64 cell: the offsets of up to
+sixteen 16x16 blocks are averaged, and each frame's averages are mapped
+to at most 8 segment values. A region smaller than a cell can disappear
+through averaging. When SVT-AV1 uses 128x128 superblocks, a coded block
+spanning multiple map cells selects the coarsest mapped offset among
+those cells, subject to the library's quantizer-range adjustments.
+The maps replace SVT-AV1's segmentation-based adaptive quantization
+(@samp{aq-mode=1}) for the rest of the encode: a neutral map ends the
+offsets but does not bring that adaptive quantization back.
+
+Requires at least SVT-AV1 1.6.0.
+
 @item svtav1-params
 Set SVT-AV1 options using a list of @var{key}=@var{value} pairs separated
 by ":". See the SVT-AV1 encoder user guide for a list of accepted parameters.
diff --git a/libavcodec/libsvtav1.c b/libavcodec/libsvtav1.c
index 1e5732f45d..4b5fa6951c 100644
--- a/libavcodec/libsvtav1.c
+++ b/libavcodec/libsvtav1.c
@@ -43,6 +43,7 @@
 #include "encode.h"
 #include "avcodec.h"
 #include "profiles.h"
+#include "qpfile_parser.h"

 typedef enum eos_status {
     EOS_NOT_REACHED = 0,
@@ -75,6 +76,32 @@ typedef struct SvtContext {
     int enc_mode;
     int crf;
     int qp;
+    char *qpfile_path;
+
+    /* qpfile state. Populated by ff_qpfile_load() in
+     * eb_enc_init() when qpfile_path is set, consumed per-frame in
+     * eb_send_frame(), released in eb_enc_close().
+     * The ROI map requires the versioned ROI ABI and is
+     * gated on the SVT-AV1 1.6.0+ ROI ABI (enable_roi_map flag and
+     * the ROI_MAP_EVENT priv-data type); older releases reject qpfile.
+     *
+     * roi_evts / roi_seg_maps are heap-owned arrays parallel to
+     * qpfile.frames; SVT-AV1 keeps the ROI-map pointer alive across
+     * the asynchronous encode pipeline (copy_private_data_list shallow-
+     * copies ROI_MAP_EVENT data), so we must preserve these until
+     * eb_enc_close().
+     */
+    FFQpFile  qpfile;
+    int             qpfile_loaded;
+#if SVT_AV1_CHECK_VERSION(1, 6, 0)
+    SvtAv1RoiMapEvt *roi_evts;
+    uint8_t        **roi_seg_maps;
+    unsigned int     roi_evt_count;
+    unsigned int     roi_b64_cols;
+    unsigned int     roi_b64_rows;
+    unsigned int     roi_input_frame;  /* input frames seen: the qpfile's frame index */
+    const SvtAv1RoiMapEvt *roi_evt_sent; /* last event SVT-AV1 accepted; it stays in force */
+#endif
 } SvtContext;

 static const struct {
@@ -482,6 +509,225 @@ static int read_in_data(EbSvtAv1EncConfiguration *param, const AVFrame *frame,
     return 0;
 }

+#if SVT_AV1_CHECK_VERSION(1, 6, 0)
+/* Translate a per-frame QP-offset file into an array of per-frame
+ * SvtAv1RoiMapEvt records.
+ *
+ * Strategy:
+ *   1. Average the 16x16 block offsets of each 64x64 superblock.
+ *   2. Pick up to QPFILE_SVTAV1_MAX_SEGMENTS segment values from the
+ *      averages (each distinct value when they fit, else uniform binning),
+ *      ordered descending with a nonnegative first entry: SVT-AV1 before
+ *      4.3.0 searches lower segment ids for a positive quantizer index and
+ *      has no fallback below segment 0.
+ *   3. Give each superblock the nearest segment through a lookup table.
+ *   4. Size b64_seg_map at the encoder's actual SB grid stride
+ *      ((max_input_luma_width+63)/64) so segmentation.c can index
+ *      it correctly even if the qpfile was cut against a smaller
+ *      preview.
+ *
+ * Per-SB rectangles fall out naturally -- SVT-AV1 consumes a dense
+ * per-SB segment map, so explicit rectangle decomposition would
+ * be redundant. Trade-off: per-MB qpfile resolution is rounded
+ * to per-SB granularity, losing spatial detail finer than 64x64
+ * px (a salient face smaller than that gets averaged with its
+ * surroundings). Suitable for object-sized ROIs generated by
+ * an external tool; finer granularity would require an SVT-AV1 ABI
+ * change.
+ *
+ * Lifetime: the library shallow-copies ROI_MAP_EVENT pointers
+ * (copy_private_data_list in enc_handle.c) and reads them later
+ * on async pipeline threads, so the SvtAv1RoiMapEvt and its
+ * b64_seg_map must outlive svt_av1_enc_send_picture() -- they
+ * are owned by SvtContext and freed in eb_enc_close().
+ */
+#define QPFILE_SVTAV1_MAX_SEGMENTS 8
+#define QPFILE_SVTAV1_SB_SIDE      4   /* 4 MBs (16 px each) per SB (64 px) */
+
+/* Average macroblock QP offsets into 64x64 superblock averages. */
+static void roi_average_map(const FFQpFrame *qf, unsigned dest_b64_cols,
+                            unsigned dest_b64_rows, int8_t *avg)
+{
+    unsigned mb_cols = qf->block_cols, mb_rows = qf->block_rows;
+    unsigned sb_y, sb_x;
+
+    for (sb_y = 0; sb_y < dest_b64_rows; sb_y++) {
+        for (sb_x = 0; sb_x < dest_b64_cols; sb_x++) {
+            long sum = 0;
+            unsigned count = 0;
+            unsigned mb_y0 = sb_y * QPFILE_SVTAV1_SB_SIDE;
+            unsigned mb_x0 = sb_x * QPFILE_SVTAV1_SB_SIDE;
+            unsigned mb_y1 = FFMIN(mb_y0 + QPFILE_SVTAV1_SB_SIDE, mb_rows);
+            unsigned mb_x1 = FFMIN(mb_x0 + QPFILE_SVTAV1_SB_SIDE, mb_cols);
+            unsigned i, j;
+
+            if (mb_x0 < mb_cols && mb_y0 < mb_rows) {
+                for (i = mb_y0; i < mb_y1; i++) {
+                    for (j = mb_x0; j < mb_x1; j++) {
+                        sum += qf->block_offsets[i * mb_cols + j];
+                        count++;
+                    }
+                }
+            }
+            avg[sb_y * dest_b64_cols + sb_x] =
+                count ? (int8_t)(int)(sum / (long)count) : 0;
+        }
+    }
+}
+
+/* Build a descending segment palette for SVT-AV1 with nonnegative segment 0. */
+static unsigned roi_palette(const int8_t *avg, size_t n_sb, int *seg_values)
+{
+    int max_avg = QPFILE_DELTA_MIN;
+    unsigned max_seg, n;
+    size_t i;
+
+    for (i = 0; i < n_sb; i++)
+        max_avg = FFMAX(max_avg, avg[i]);
+
+    max_seg = max_avg >= 0 ? QPFILE_SVTAV1_MAX_SEGMENTS
+                           : QPFILE_SVTAV1_MAX_SEGMENTS - 1;
+    n = ff_qpfile_palette(avg, n_sb, seg_values, max_seg);
+    if (max_avg < 0)
+        seg_values[n++] = 0;
+
+    for (unsigned k = 0; k < n / 2; k++)
+        FFSWAP(int, seg_values[k], seg_values[n - 1 - k]);
+
+    return n;
+}
+
+/* Build an SVT-AV1 ROI event and map for a frame, returning 0 or an error. */
+static int build_one_roi_evt(const FFQpFrame *qf,
+                             unsigned dest_b64_cols,
+                             unsigned dest_b64_rows,
+                             int8_t *avg,
+                             SvtAv1RoiMapEvt *out_evt,
+                             uint8_t **out_seg_map)
+{
+    int seg_values[QPFILE_SVTAV1_MAX_SEGMENTS];
+    uint8_t lut[QPFILE_LUT_SIZE];
+    uint8_t *seg_map = NULL;
+    size_t n_sb;
+    unsigned n_seg, i;
+
+    if (!dest_b64_cols || !dest_b64_rows)
+        return AVERROR(EINVAL);
+
+    n_sb = (size_t)dest_b64_rows * dest_b64_cols;
+    seg_map = av_calloc(n_sb, sizeof(*seg_map));
+    if (!seg_map)
+        return AVERROR(ENOMEM);
+
+    memset(out_evt, 0, sizeof(*out_evt));
+    out_evt->start_picture_number = qf->frame_index;
+    out_evt->b64_seg_map          = seg_map;
+    out_evt->max_seg_id           = 0;
+    out_evt->next                 = NULL;
+    *out_seg_map = seg_map;
+
+    if (!qf->block_offsets)
+        return 0;
+
+    roi_average_map(qf, dest_b64_cols, dest_b64_rows, avg);
+    n_seg = roi_palette(avg, n_sb, seg_values);
+    ff_qpfile_segment_lut(lut, seg_values, n_seg);
+
+    for (i = 0; i < n_sb; i++)
+        seg_map[i] = lut[avg[i] - QPFILE_DELTA_MIN];
+
+    out_evt->max_seg_id = (int8_t)(n_seg - 1u);
+    for (i = 0; i < n_seg; i++)
+        out_evt->seg_qp[i] = (int16_t)seg_values[i];
+
+    return 0;
+}
+
+/* Build ROI events for all qpfile frames, returning 0 or a negative error. */
+static int build_all_roi_evts(AVCodecContext *avctx, SvtContext *svt_enc)
+{
+    unsigned b64_cols = ((unsigned)avctx->width  + 63u) / 64u;
+    unsigned b64_rows = ((unsigned)avctx->height + 63u) / 64u;
+    unsigned n = svt_enc->qpfile.frame_count;
+    unsigned i;
+    int8_t *avg = NULL;
+    int ret = 0;
+
+    if (!n || !b64_cols || !b64_rows)
+        return AVERROR(EINVAL);
+
+    avg = av_malloc_array((size_t)b64_cols * b64_rows, sizeof(*avg));
+    if (!avg)
+        return AVERROR(ENOMEM);
+
+    svt_enc->roi_evts = av_calloc(n, sizeof(*svt_enc->roi_evts));
+    svt_enc->roi_seg_maps = av_calloc(n, sizeof(*svt_enc->roi_seg_maps));
+    if (!svt_enc->roi_evts || !svt_enc->roi_seg_maps) {
+        ret = AVERROR(ENOMEM);
+        goto end;
+    }
+    svt_enc->roi_evt_count = n;
+    svt_enc->roi_b64_cols  = b64_cols;
+    svt_enc->roi_b64_rows  = b64_rows;
+
+    for (i = 0; i < n; i++) {
+        ret = build_one_roi_evt(&svt_enc->qpfile.frames[i],
+                                b64_cols, b64_rows, avg,
+                                &svt_enc->roi_evts[i],
+                                &svt_enc->roi_seg_maps[i]);
+        if (ret < 0) {
+            av_log(avctx, AV_LOG_ERROR,
+                   "failed to build ROI map for qpfile frame %u (%d)\n",
+                   i, ret);
+            goto end;
+        }
+        av_freep(&svt_enc->qpfile.frames[i].block_offsets);
+    }
+
+end:
+    av_free(avg);
+    return ret;
+}
+
+/* Look up the ROI map event of the record a frame uses, returning it, or
+ * NULL when there is none or SVT-AV1 already holds it. SVT-AV1 keeps the
+ * last event it accepted for all later frames, so an event is sent whenever
+ * the record in force changes: normally on the frame of the record, or on
+ * the next frame that reaches SVT-AV1 when that frame was dropped. */
+static SvtAv1RoiMapEvt *roi_evt_for_index(SvtContext *svt_enc, unsigned frame_index)
+{
+    const FFQpFrame *qf;
+    ptrdiff_t index;
+
+    if (!svt_enc->roi_evt_count)
+        return NULL;
+    qf = ff_qpfile_frame_for_index(&svt_enc->qpfile, frame_index);
+    if (!qf)
+        return NULL;
+    index = qf - svt_enc->qpfile.frames;
+    if ((unsigned)index >= svt_enc->roi_evt_count ||
+        &svt_enc->roi_evts[index] == svt_enc->roi_evt_sent)
+        return NULL;
+    return &svt_enc->roi_evts[index];
+}
+#endif /* SVT_AV1_CHECK_VERSION(1, 6, 0) */
+
+/* Load the QP file and check its grid, returning 0 or a negative error code. */
+static av_cold int load_qpfile(AVCodecContext *avctx)
+{
+    SvtContext *svt_enc = avctx->priv_data;
+    int ret = ff_qpfile_load(avctx, svt_enc->qpfile_path, &svt_enc->qpfile);
+
+    if (ret < 0) {
+        av_log(avctx, AV_LOG_ERROR, "cannot read qpfile %s: %s\n",
+               svt_enc->qpfile_path, av_err2str(ret));
+        return ret;
+    }
+    svt_enc->qpfile_loaded = 1;
+    return ff_qpfile_check_grid(avctx, "libsvtav1", &svt_enc->qpfile,
+                                avctx->width, avctx->height);
+}
+
 static av_cold int eb_enc_init(AVCodecContext *avctx)
 {
     SvtContext   *svt_enc = avctx->priv_data;
@@ -505,11 +751,65 @@ static av_cold int eb_enc_init(AVCodecContext *avctx)
         return ret;
     }

+    if (svt_enc->qpfile_path && *svt_enc->qpfile_path) {
+        ret = load_qpfile(avctx);
+        if (ret < 0)
+            return ret;
+#if SVT_AV1_CHECK_VERSION(1, 6, 0)
+        if (svt_enc->enc_params.rate_control_mode != 0) {
+            av_log(avctx, AV_LOG_ERROR,
+                   "qpfile with libsvtav1 needs CRF or constant-QP rate "
+                   "control (rc 0); SVT-AV1 applies ROI maps only there.\n");
+            return AVERROR(EINVAL);
+        }
+        /* SVT-AV1 reads the ROI map with superblock positions of the
+         * scaled frame but the stride of the full-size map, so internal
+         * scaling would move the offsets to other superblocks. */
+        if (svt_enc->enc_params.superres_mode != SUPERRES_NONE ||
+            svt_enc->enc_params.resize_mode != RESIZE_NONE) {
+            av_log(avctx, AV_LOG_ERROR,
+                   "qpfile with libsvtav1 does not support internal "
+                   "scaling (superres-mode or resize-mode other than 0).\n");
+            return AVERROR(EINVAL);
+        }
+        /* SVT-AV1 can encode the first pass at a reduced size and then
+         * reads the ROI map with the stride of that size, so the first
+         * pass is refused even where it would not be downsampled. */
+        if (svt_enc->enc_params.pass == 1) {
+            av_log(avctx, AV_LOG_ERROR,
+                   "qpfile with libsvtav1 does not support the first pass.\n");
+            return AVERROR(EINVAL);
+        }
+        /* Build all per-frame ROI map events upfront. SVT-AV1 reads
+         * ROI_MAP_EVENT data via shallow-copied pointers on async
+         * pipeline threads, so the events and their b64_seg_maps must
+         * live for the whole encode session. Then flip enable_roi_map
+         * before set_parameter so the encoder allocates segmentation
+         * state.
+         */
+        ret = build_all_roi_evts(avctx, svt_enc);
+        if (ret < 0)
+            return ret;
+        svt_enc->enc_params.enable_roi_map = 1;
+        av_log(avctx, AV_LOG_VERBOSE,
+               "qpfile=%s loaded (frames=%u, %ux%u qpfile blocks "
+               "-> %ux%u SB ROI grid).\n",
+               svt_enc->qpfile_path, svt_enc->qpfile.frame_count,
+               svt_enc->qpfile.block_cols, svt_enc->qpfile.block_rows,
+               svt_enc->roi_b64_cols, svt_enc->roi_b64_rows);
+#else
+        av_log(avctx, AV_LOG_ERROR,
+               "qpfile needs SVT-AV1 1.6.0 or newer.\n");
+        return AVERROR(ENOSYS);
+#endif
+    }
+
     svt_ret = svt_av1_enc_set_parameter(svt_enc->svt_handle, &svt_enc->enc_params);
     if (svt_ret != EB_ErrorNone) {
         return svt_print_error(avctx, svt_ret, "Error setting encoder parameters");
     }

+
     svt_ret = svt_av1_enc_init(svt_enc->svt_handle);
     if (svt_ret != EB_ErrorNone) {
         return svt_print_error(avctx, svt_ret, "Error initializing encoder");
@@ -558,6 +858,9 @@ static int eb_send_frame(AVCodecContext *avctx, const AVFrame *frame)
     AVFrameSideData *sd;
     EbErrorType svt_ret;
     int ret;
+#if SVT_AV1_CHECK_VERSION(1, 6, 0)
+    unsigned roi_frame = 0;
+#endif

     if (!frame) {
         EbBufferHeaderType headerPtrLast;
@@ -574,6 +877,13 @@ static int eb_send_frame(AVCodecContext *avctx, const AVFrame *frame)
         return 0;
     }

+#if SVT_AV1_CHECK_VERSION(1, 6, 0)
+    /* Count every input frame before any step that can fail, so that the
+     * frames after a dropped one keep their own qpfile records. */
+    if (svt_enc->qpfile_loaded)
+        roi_frame = svt_enc->roi_input_frame++;
+#endif
+
     ret = read_in_data(&svt_enc->enc_params, frame, headerPtr);
     if (ret < 0)
         return ret;
@@ -613,8 +923,44 @@ static int eb_send_frame(AVCodecContext *avctx, const AVFrame *frame)
         return AVERROR_INVALIDDATA;
     }

+#if SVT_AV1_CHECK_VERSION(1, 6, 0)
+    /* qpfile -> SVT-AV1 ROI map: attach the (already-built)
+     * per-frame ROI map event as a stack-local priv-data node. The
+     * encoder's resource_coordination_process.c expects
+     *   node->size == sizeof(SvtAv1RoiMapEvt*)
+     * and uses node->data as a pointer that must outlive the async
+     * pipeline -- so the SvtAv1RoiMapEvt + b64_seg_map live in
+     * svt_enc->roi_evts/roi_seg_maps until eb_enc_close(). The
+     * EbPrivDataNode itself is shallow-copied by copy_private_data_list
+     * in enc_handle.c, so a stack-local node is safe.
+     */
+    EbPrivDataNode roi_node;
+    SvtAv1RoiMapEvt *roi_evt_ptr = NULL;
+    if (svt_enc->qpfile_loaded && svt_enc->roi_evt_count > 0)
+        roi_evt_ptr = roi_evt_for_index(svt_enc, roi_frame);
+    if (roi_evt_ptr) {
+        memset(&roi_node, 0, sizeof(roi_node));
+        roi_node.node_type = ROI_MAP_EVENT;
+        roi_node.data      = roi_evt_ptr;
+        roi_node.size      = (uint32_t)sizeof(SvtAv1RoiMapEvt *);
+        roi_node.next      = NULL;
+        headerPtr->p_app_private = &roi_node;
+    }
+#endif

     svt_ret = svt_av1_enc_send_picture(svt_enc->svt_handle, headerPtr);
+
+#if SVT_AV1_CHECK_VERSION(1, 6, 0)
+    /* Restore the slot for the next frame's send-path. The library
+     * already shallow-copied the priv-data list. */
+    if (roi_evt_ptr) {
+        headerPtr->p_app_private = NULL;
+        /* After a failed send the event goes out again with the next frame. */
+        if (svt_ret == EB_ErrorNone)
+            svt_enc->roi_evt_sent = roi_evt_ptr;
+    }
+#endif
+
     if (svt_ret != EB_ErrorNone)
         return svt_print_error(avctx, svt_ret, "Error sending a frame to encoder");

@@ -784,6 +1130,24 @@ static av_cold int eb_enc_close(AVCodecContext *avctx)
     ff_dovi_ctx_unref(&svt_enc->dovi);
     av_freep(&svt_enc->stats_buf);

+    if (svt_enc->qpfile_loaded) {
+#if SVT_AV1_CHECK_VERSION(1, 6, 0)
+        if (svt_enc->roi_seg_maps) {
+            for (unsigned i = 0; i < svt_enc->roi_evt_count; i++)
+                av_freep(&svt_enc->roi_seg_maps[i]);
+            av_freep(&svt_enc->roi_seg_maps);
+        }
+        av_freep(&svt_enc->roi_evts);
+        svt_enc->roi_evt_count = 0;
+        svt_enc->roi_b64_cols  = 0;
+        svt_enc->roi_b64_rows  = 0;
+        svt_enc->roi_input_frame = 0;
+        svt_enc->roi_evt_sent = NULL;
+#endif
+        ff_qpfile_free(&svt_enc->qpfile);
+        svt_enc->qpfile_loaded = 0;
+    }
+
     return 0;
 }

@@ -828,6 +1192,7 @@ static const AVOption options[] = {
     { "qp", "Initial Quantizer level value", OFFSET(qp),
       AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 63, VE },
     { "svtav1-params", "Set the SVT-AV1 configuration using a :-separated list of key=value parameters", OFFSET(svtav1_opts), AV_OPT_TYPE_DICT, { 0 }, 0, 0, VE },
+    { "qpfile",        "Read per-frame QP offsets from a file (needs SVT-AV1 1.6.0 or newer)", OFFSET(qpfile_path), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, VE },

     { "dolbyvision", "Enable Dolby Vision RPU coding", OFFSET(dovi.enable), AV_OPT_TYPE_BOOL, {.i64 = FF_DOVI_AUTOMATIC }, -1, 1, VE, .unit = "dovi" },
     {   "auto", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_DOVI_AUTOMATIC}, .flags = VE, .unit = "dovi" },