Commit 90b56f64ce for ffmpeg
commit 90b56f64cee389d5741c143ee501277731e3f500
Author: lusoris <lusoris@proton.me>
Date: Sun Nov 8 17:01:18 2026 +0100
avcodec/libaomenc: add a qpfile option
Add a qpfile option that reads per-frame QP offsets from a text file
and passes them to libaom as a region-of-interest map through
AOME_SET_ROI_MAP, so an external analysis step can steer the quality
per 16x16 block.
The file format and its parser live in qpfile_parser.c, a configure
component that the SVT-AV1 and x264 wrappers select too. Each record
names a 0-based input frame, strictly increasing and at most
4294967295, a frame type and a QP, which are checked but not used,
followed by one line of offsets per row of 16x16 blocks. A frame uses
the last record whose number is not greater than its own. The reader
takes at most 1048576 records and refuses a read error, a NUL byte, a
line longer than 1 MiB and text after the last value of a line; lines
holding only spaces or tabs, lines starting with '#', trailing spaces
and tabs and CRLF line ends are accepted. Errors name the line, also
for a record that ends at the end of the file. Offsets are clipped to
-12..12 and stored as int8_t. The fate-qpfile-parser test covers the
format and its limits, including records that clear the map and the
records that follow them.
The frame number counts every input frame, also one that the encoder
refuses, so the frames after a refused frame keep their own records.
The whole file is read when the encoder opens and kept for the whole
encode, one byte per 16x16 block and record: 32,400 bytes per record
at 3840x2160, so a record on every frame of a two-hour 4K encode at
30 fps takes about 7.0 GB. Reading the file through a bounded window
of records is left for a follow-up.
libaom applies ROI maps only in one-pass encoding with usage realtime,
an effective cpu-used of at least 7, also when set through aom-params,
and no lookahead (lag-in-frames 0, the realtime default), so other
settings are refused instead of being ignored. libaom takes at most 8
segments per frame; more distinct offsets are quantized to 8 evenly
spaced values. The offsets are deltas on libaom's 0..63 quantizer
scale, which libaom converts to quantizer index deltas, so an offset
of 12 becomes 48.
From libaom 3.13.0 on, at least up to 3.15.3, libaom checks each
segment's quantizer index delta against the index of the previous
segment instead of the frame's base index, so near the ends of the
index range a delta can come out changed or dropped: with base index
28 and offsets -12 and -8, the second segment gets no delta instead
of -27. The documentation names this limitation.
The effective speed requirement, the line number for a record that
ends at the end of the file and the tests for clearing records come
from patches in a Forgejo Fairy review of this option.
Counting the refused frames follows a later Forgejo Fairy review.
Signed-off-by: lusoris <lusoris@proton.me>
diff --git a/configure b/configure
index 5f1bcebf5b..cb39b436a1 100755
--- a/configure
+++ b/configure
@@ -2639,6 +2639,7 @@ TYPES_LIST="
SecPkgContext_KeyingMaterialInfo
socklen_t
struct_addrinfo
+ struct_aom_roi_map_ref_frame
struct_group_source_req
struct_ip_mreq_source
struct_ipv6_mreq
@@ -2785,6 +2786,7 @@ CONFIG_EXTRA="
mss34dsp
pixblockdsp
qpeldsp
+ qpfile
qsv
qsvdec
qsvenc
@@ -3808,7 +3810,7 @@ prores_videotoolbox_encoder_select="videotoolbox_encoder"
libaom_av1_decoder_deps="libaom"
libaom_av1_decoder_select="itut_t35"
libaom_av1_encoder_deps="libaom"
-libaom_av1_encoder_select="extract_extradata_bsf dovi_rpuenc"
+libaom_av1_encoder_select="extract_extradata_bsf dovi_rpuenc qpfile"
libaribb24_decoder_deps="libaribb24"
libaribcaption_decoder_deps="libaribcaption"
libastcenc_encoder_deps="libastcenc"
@@ -7277,6 +7279,7 @@ enabled jni && { [ $target_os = "android" ] && check_headers jni.h
enabled ladspa && require_headers "ladspa.h dlfcn.h"
enabled lcms2 && require_pkg_config lcms2 "lcms2 >= 2.13" lcms2.h cmsCreateContext
enabled libaom && require_pkg_config libaom "aom >= 2.0.0" aom/aom_codec.h aom_codec_version
+enabled libaom && check_struct aom/aomcx.h "struct aom_roi_map" ref_frame
enabled liboapv && require_pkg_config liboapv "oapv >= 0.2.0.0" "oapv/oapv.h" oapve_encode
enabled libaribb24 && { check_pkg_config libaribb24 "aribb24 > 1.0.3" "aribb24/aribb24.h" arib_instance_new ||
{ enabled gpl && require_pkg_config libaribb24 aribb24 "aribb24/aribb24.h" arib_instance_new; } ||
diff --git a/doc/encoders.texi b/doc/encoders.texi
index cf3861d679..7b9c29ffa1 100644
--- a/doc/encoders.texi
+++ b/doc/encoders.texi
@@ -1974,6 +1974,38 @@ Enable interintra compound. Default is true.
@item enable-smooth-interintra (@emph{boolean}) (Requires libaom >= v2.0.0)
Enable smooth interintra mode. Default is true.
+@item qpfile @var{filename}
+Read per-frame QP offsets from @var{filename} and pass them to libaom as
+a region-of-interest map. libaom applies the map only in one-pass encoding
+with @option{usage} @samp{realtime}, an effective @option{cpu-used} of at
+least 7, and @option{lag-in-frames} 0, the default for realtime usage;
+other settings are refused. Speeds above 8 can be selected through
+@option{aom-params} when supported by the linked libaom.
+
+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; a record without offset lines,
+or no record yet, clears the map. libaom takes at most 8 distinct offsets per
+frame; when a frame holds more, they are quantized to 8 evenly spaced values.
+The offsets are deltas on libaom's 0 to 63 quantizer scale; libaom converts each
+to a quantizer index delta, so an offset of 12 becomes 48. While a map is
+enabled, libaom does not run its cyclic-refresh adaptive quantization
+(@option{aq-mode} 3). Up to at least version 3.15.3, libaom checks each
+distinct offset of a frame against the quantizer index of the previous one
+instead of the frame's base index, so near the ends of the quantizer index
+range an offset can be changed or dropped.
+
+Requires at least libaom 3.13.0.
+
@item aom-params
Set libaom options using a list of @var{key}=@var{value} pairs separated
by ":". For a list of supported options, see @command{aomenc --help} under the
diff --git a/libavcodec/Makefile b/libavcodec/Makefile
index f12ad9c8e8..c3da8412c6 100644
--- a/libavcodec/Makefile
+++ b/libavcodec/Makefile
@@ -166,6 +166,7 @@ OBJS-$(CONFIG_MSMPEG4ENC) += msmpeg4enc.o msmpeg4.o msmpeg4data.o \
OBJS-$(CONFIG_MSS34DSP) += mss34dsp.o jpegquanttables.o
OBJS-$(CONFIG_PIXBLOCKDSP) += pixblockdsp.o
OBJS-$(CONFIG_QPELDSP) += qpeldsp.o
+OBJS-$(CONFIG_QPFILE) += qpfile_parser.o
OBJS-$(CONFIG_QSV) += qsv.o
OBJS-$(CONFIG_QSVDEC) += qsvdec.o
OBJS-$(CONFIG_QSVENC) += qsvenc.o
@@ -1406,6 +1407,7 @@ TESTPROGS-$(CONFIG_DXV_ENCODER) += hashtable
TESTPROGS-$(CONFIG_MJPEG_ENCODER) += mjpegenc_huffman
TESTPROGS-$(CONFIG_MPEGAUDIOHEADER) += mpegaudiodecheader
TESTPROGS-$(CONFIG_MPEGVIDEO) += mpeg12framerate
+TESTPROGS-$(CONFIG_QPFILE) += qpfile_parser
TESTPROGS-$(CONFIG_H264_METADATA_BSF) += h264_levels
TESTPROGS-$(CONFIG_HEVC_METADATA_BSF) += h265_levels
TESTPROGS-$(CONFIG_RANGECODER) += rangecoder
diff --git a/libavcodec/libaomenc.c b/libavcodec/libaomenc.c
index fe68f1f953..ae83f3076d 100644
--- a/libavcodec/libaomenc.c
+++ b/libavcodec/libaomenc.c
@@ -24,6 +24,7 @@
*/
#include <limits.h>
+#include <stdlib.h>
#define AOM_DISABLE_CTRL_TYPECHECKS 1
#include <aom/aom_encoder.h>
@@ -32,6 +33,7 @@
#include "libavutil/avassert.h"
#include "libavutil/base64.h"
#include "libavutil/cpu.h"
+#include "libavutil/dict.h"
#include "libavutil/hdr_dynamic_metadata.h"
#include "libavutil/imgutils.h"
#include "libavutil/mathematics.h"
@@ -50,6 +52,7 @@
#include "itut35.h"
#include "libaom.h"
#include "profiles.h"
+#include "qpfile_parser.h"
/*
* Portion of struct aom_codec_cx_pkt from aom_encoder.h.
@@ -69,6 +72,12 @@ struct FrameListData {
struct FrameListData *next;
};
+/* libaom 3.15.3 applies ROI maps only in realtime usage at cpu-used >= 7
+ * without lookahead (measured: lower speeds, good usage and a nonzero
+ * lag-in-frames ignore the map content). */
+#define QPFILE_AOM_USAGE_REALTIME 1 /* AOM_USAGE_REALTIME */
+#define QPFILE_AOM_MIN_CPU_USED 7
+
typedef struct AOMEncoderContext {
AVClass *class;
AVBSFContext *bsf;
@@ -110,6 +119,35 @@ typedef struct AOMEncoderContext {
int enable_global_motion;
int enable_intrabc;
int enable_restoration;
+ char *qpfile_path;
+
+ /* qpfile -> libaom AOME_SET_ROI_MAP ROI map.
+ * Populated by ff_qpfile_load() in aom_init() when qpfile_path is set,
+ * consumed per-frame in aom_encode(), released in aom_free().
+ *
+ * libaom requires the segment-id map to match its mode-info grid
+ * exactly: rows == mi_rows, cols == mi_cols (4x4-luma cells; see
+ * av1/encoder/encoder.c::av1_set_roi_map). The qpfile rows are at
+ * 16x16-MB granularity, so each MB cell expands into a 4x4 block of
+ * mi cells. delta_q[8] holds up to AOM_MAX_SEGMENTS distinct QP
+ * deltas; per-frame qp_offsets are quantised into <=8 segment ids
+ * (uniform binning when more distinct values than segments exist).
+ *
+ * roi_seg_map is allocated once at the encoder grid size; libaom
+ * deep-copies it on every aom_codec_control() call, so the buffer
+ * can be reused across frames.
+ */
+ FFQpFile qpfile;
+ int qpfile_loaded;
+ uint8_t *roi_seg_map;
+ unsigned int roi_mi_rows;
+ unsigned int roi_mi_cols;
+ unsigned int roi_input_frame; /* input frames seen: the qpfile's frame index */
+ const FFQpFrame *roi_qf; /* record the cached map was built from */
+ int roi_cached; /* roi_qf, roi_seg_q and roi_n_seg are valid */
+ int roi_seg_q[AOM_MAX_SEGMENTS];
+ unsigned int roi_n_seg;
+
int usage;
int tune;
int still_picture;
@@ -506,6 +544,17 @@ static av_cold int aom_free(AVCodecContext *avctx)
aom_codec_destroy(&ctx->encoder);
aom_img_remove_metadata(&ctx->rawimg);
+ if (ctx->qpfile_loaded) {
+ ff_qpfile_free(&ctx->qpfile);
+ ctx->qpfile_loaded = 0;
+ }
+ av_freep(&ctx->roi_seg_map);
+ ctx->roi_mi_rows = 0;
+ ctx->roi_mi_cols = 0;
+ ctx->roi_input_frame = 0;
+ ctx->roi_qf = NULL;
+ ctx->roi_cached = 0;
+ ctx->roi_n_seg = 0;
av_freep(&ctx->twopass_stats.buf);
av_freep(&avctx->stats_out);
free_frame_list(ctx->coded_frame_list);
@@ -797,6 +846,38 @@ static const struct {
{ AV1E_SET_ENABLE_SMOOTH_INTERINTRA, OFFSET(enable_smooth_interintra) },
};
+/* Return the cpu-used value libaom runs with: an aom-params entry wins over -cpu-used. */
+static int qpfile_aom_cpu_used(const AOMContext *ctx)
+{
+ const AVDictionaryEntry *en = av_dict_get(ctx->aom_params, "cpu-used",
+ NULL, AV_DICT_MATCH_CASE);
+ char *end;
+ long v;
+
+ if (!en)
+ return ctx->cpu_used;
+ v = strtol(en->value, &end, 10);
+ return end == en->value ? ctx->cpu_used : (int)av_clip64(v, INT_MIN, INT_MAX);
+}
+
+#if HAVE_STRUCT_AOM_ROI_MAP_REF_FRAME
+/* Load the QP file and check its grid, returning 0 or a negative error code. */
+static av_cold int load_qpfile(AVCodecContext *avctx)
+{
+ AOMContext *ctx = avctx->priv_data;
+ int ret = ff_qpfile_load(avctx, ctx->qpfile_path, &ctx->qpfile);
+
+ if (ret < 0) {
+ av_log(avctx, AV_LOG_ERROR, "cannot read qpfile %s: %s\n",
+ ctx->qpfile_path, av_err2str(ret));
+ return ret;
+ }
+ ctx->qpfile_loaded = 1;
+ return ff_qpfile_check_grid(avctx, "libaom", &ctx->qpfile,
+ avctx->width, avctx->height);
+}
+#endif
+
static av_cold int aom_config(AVCodecContext *avctx,
const struct aom_codec_iface *iface)
{
@@ -1072,6 +1153,56 @@ static av_cold int aom_init(AVCodecContext *avctx,
if (res < 0)
return res;
+ if (ctx->qpfile_path && *ctx->qpfile_path) {
+#if HAVE_STRUCT_AOM_ROI_MAP_REF_FRAME
+ if (avctx->flags & (AV_CODEC_FLAG_PASS1 | AV_CODEC_FLAG_PASS2)) {
+ av_log(avctx, AV_LOG_ERROR,
+ "qpfile needs one-pass encoding: libaom applies "
+ "ROI maps only without recode.\n");
+ return AVERROR(EINVAL);
+ }
+ if (ctx->usage != QPFILE_AOM_USAGE_REALTIME ||
+ qpfile_aom_cpu_used(ctx) < QPFILE_AOM_MIN_CPU_USED) {
+ av_log(avctx, AV_LOG_ERROR,
+ "qpfile with libaom-av1 requires -usage realtime and cpu-used >= 7, "
+ "also when set through aom-params; libaom applies ROI maps only in "
+ "realtime usage at speed 7 or more.\n");
+ return AVERROR(EINVAL);
+ }
+ if (ctx->enccfg.g_lag_in_frames) {
+ av_log(avctx, AV_LOG_ERROR,
+ "qpfile with libaom-av1 needs -lag-in-frames 0; "
+ "libaom ignores ROI maps with lookahead.\n");
+ return AVERROR(EINVAL);
+ }
+ res = load_qpfile(avctx);
+ if (res < 0)
+ return res;
+ /* libaom's segmentation map is sized at the mode-info grid:
+ * size_in_mi(x) == ALIGN_POWER_OF_TWO(x, 3) >> MI_SIZE_LOG2,
+ * i.e. each dim aligned up to a multiple of 8 px and divided
+ * by 4. Mirror that here so av1_set_roi_map's (rows, cols)
+ * equality check passes. */
+ ctx->roi_mi_cols = ((unsigned)((avctx->width + 7) & ~7)) >> 2;
+ ctx->roi_mi_rows = ((unsigned)((avctx->height + 7) & ~7)) >> 2;
+ ctx->roi_seg_map = av_calloc((size_t)ctx->roi_mi_rows *
+ ctx->roi_mi_cols,
+ sizeof(*ctx->roi_seg_map));
+ if (!ctx->roi_seg_map)
+ return AVERROR(ENOMEM);
+ av_log(avctx, AV_LOG_VERBOSE,
+ "qpfile=%s loaded (frames=%u, %ux%u qpfile blocks "
+ "-> %ux%u mi grid).\n",
+ ctx->qpfile_path, ctx->qpfile.frame_count,
+ ctx->qpfile.block_cols, ctx->qpfile.block_rows,
+ ctx->roi_mi_cols, ctx->roi_mi_rows);
+#else
+ av_log(avctx, AV_LOG_ERROR,
+ "qpfile needs libaom 3.13.0 or newer.\n");
+ return AVERROR(ENOSYS);
+#endif
+ }
+
ctx->dovi.logctx = avctx;
if ((res = ff_dovi_configure(&ctx->dovi, avctx)) < 0)
return res;
@@ -1324,6 +1455,118 @@ static enum AVPixelFormat aomfmt_to_pixfmt(struct aom_image *img)
return AV_PIX_FMT_NONE;
}
+#if HAVE_STRUCT_AOM_ROI_MAP_REF_FRAME
+/* libaom-av1 ROI map helpers. Convert one FFQpFrame into a
+ * libaom aom_roi_map_t whose (rows, cols, roi_map, delta_q) match the
+ * encoder's mode-info grid (4x4-luma cells).
+ *
+ * Quantisation: per-MB qp_offsets are clipped to [-12, +12] by the
+ * shared parser. Per frame, we discover the actual value range and
+ * emit one segment per distinct value when there are at most
+ * AOM_MAX_SEGMENTS of them, or do uniform linear binning across the span
+ * (lossy: each MB rounds to its nearest segment QP). Each frame's map is
+ * built through a 25-entry offset lookup table and reused while the same
+ * record applies. */
+
+#define QPFILE_AOM_MAX_SEGMENTS AOM_MAX_SEGMENTS /* 8, see aomcx.h */
+#define QPFILE_AOM_MI_PER_MB 4 /* 16 px MB / 4 px mi */
+
+/* Give each mode-info cell the segment nearest its macroblock's QP offset. */
+static void qpfile_aom_paint_seg_map(const FFQpFrame *qf,
+ uint8_t *seg_map,
+ unsigned mi_rows, unsigned mi_cols,
+ const int *seg_q, unsigned n_seg)
+{
+ uint8_t lut[QPFILE_LUT_SIZE];
+ unsigned mi_y, mi_x;
+ unsigned mb_rows = qf->block_rows;
+ unsigned mb_cols = qf->block_cols;
+
+ ff_qpfile_segment_lut(lut, seg_q, n_seg);
+ /* For each mi cell, pick the qpfile MB it overlaps, then snap that
+ * MB's QP-offset to the nearest segment id. mi index / 4 = mb idx. */
+ for (mi_y = 0; mi_y < mi_rows; mi_y++) {
+ unsigned mb_y = mi_y / QPFILE_AOM_MI_PER_MB;
+ mb_y = FFMIN(mb_y, mb_rows - 1u);
+ for (mi_x = 0; mi_x < mi_cols; mi_x++) {
+ unsigned mb_x = mi_x / QPFILE_AOM_MI_PER_MB;
+ int v;
+ mb_x = FFMIN(mb_x, mb_cols - 1u);
+ v = qf->block_offsets[mb_y * mb_cols + mb_x];
+ seg_map[mi_y * mi_cols + mi_x] = lut[v - QPFILE_DELTA_MIN];
+ }
+ }
+}
+
+/* Send an ROI map to libaom via AOME_SET_ROI_MAP, returning 0 or an error. */
+static int qpfile_aom_send_roi(AVCodecContext *avctx, aom_roi_map_t *roi,
+ unsigned frame_index)
+{
+ AOMContext *ctx = avctx->priv_data;
+ int res = aom_codec_control(&ctx->encoder, AOME_SET_ROI_MAP, roi);
+
+ if (res != AOM_CODEC_OK) {
+ av_log(avctx, AV_LOG_ERROR,
+ "AOME_SET_ROI_MAP failed for frame %u (res=%d).\n",
+ frame_index, res);
+ return AVERROR_EXTERNAL;
+ }
+ return 0;
+}
+
+/* Clear an ROI map to rows x cols mode-info cells with no reference frame. */
+static void qpfile_aom_init_roi(aom_roi_map_t *roi, unsigned rows, unsigned cols)
+{
+ memset(roi, 0, sizeof(*roi));
+ roi->rows = rows;
+ roi->cols = cols;
+ for (unsigned i = 0; i < QPFILE_AOM_MAX_SEGMENTS; i++)
+ roi->ref_frame[i] = -1;
+}
+
+/* Refresh the cached ROI segment map and QP deltas when the active record changes. */
+static void qpfile_aom_update_map(AOMContext *ctx, const FFQpFrame *qf)
+{
+ ctx->roi_n_seg = 0;
+ if (qf)
+ ctx->roi_n_seg = ff_qpfile_segment_values(qf, ctx->roi_seg_q,
+ QPFILE_AOM_MAX_SEGMENTS);
+ if (ctx->roi_n_seg)
+ qpfile_aom_paint_seg_map(qf, ctx->roi_seg_map,
+ ctx->roi_mi_rows, ctx->roi_mi_cols,
+ ctx->roi_seg_q, ctx->roi_n_seg);
+ ctx->roi_qf = qf;
+ ctx->roi_cached = 1;
+}
+
+/* Build and apply the ROI map for a frame, returning 0 or a negative error. */
+static int qpfile_aom_apply_roi(AVCodecContext *avctx, unsigned frame_index)
+{
+ AOMContext *ctx = avctx->priv_data;
+ aom_roi_map_t roi;
+ const FFQpFrame *qf;
+
+ if (!ctx->qpfile_loaded || !ctx->roi_seg_map ||
+ !ctx->roi_mi_rows || !ctx->roi_mi_cols)
+ return 0;
+
+ qf = ff_qpfile_frame_for_index(&ctx->qpfile, frame_index);
+ if (!ctx->roi_cached || qf != ctx->roi_qf)
+ qpfile_aom_update_map(ctx, qf);
+
+ qpfile_aom_init_roi(&roi, ctx->roi_mi_rows, ctx->roi_mi_cols);
+ if (ctx->roi_n_seg) {
+ roi.enabled = 1;
+ roi.roi_map = ctx->roi_seg_map;
+ roi.delta_qp_enabled = 1;
+ for (unsigned i = 0; i < ctx->roi_n_seg; i++)
+ roi.delta_q[i] = ctx->roi_seg_q[i];
+ }
+
+ return qpfile_aom_send_roi(avctx, &roi, frame_index);
+}
+#endif
+
static int aom_encode(AVCodecContext *avctx, AVPacket *pkt,
const AVFrame *frame, int *got_packet)
{
@@ -1334,8 +1577,17 @@ static int aom_encode(AVCodecContext *avctx, AVPacket *pkt,
int res, coded_size;
aom_enc_frame_flags_t flags = 0;
AVFrameSideData *sd;
+#if HAVE_STRUCT_AOM_ROI_MAP_REF_FRAME
+ unsigned roi_frame = 0;
+#endif
if (frame) {
+#if HAVE_STRUCT_AOM_ROI_MAP_REF_FRAME
+ /* Count every input frame before any step that can fail, so that
+ * the frames after a dropped one keep their own qpfile records. */
+ if (ctx->qpfile_loaded)
+ roi_frame = ctx->roi_input_frame++;
+#endif
rawimg = &ctx->rawimg;
aom_img_remove_metadata(rawimg);
rawimg->planes[AOM_PLANE_Y] = frame->data[0];
@@ -1397,6 +1649,14 @@ static int aom_encode(AVCodecContext *avctx, AVPacket *pkt,
return res;
}
+#if HAVE_STRUCT_AOM_ROI_MAP_REF_FRAME
+ if (ctx->qpfile_loaded && frame) {
+ int qret = qpfile_aom_apply_roi(avctx, roi_frame);
+ if (qret < 0)
+ return qret;
+ }
+#endif
+
res = aom_codec_encode(&ctx->encoder, rawimg, timestamp, duration, flags);
if (res != AOM_CODEC_OK) {
log_encoder_error(avctx, "Error encoding frame");
@@ -1559,6 +1819,13 @@ static av_cold int av1_reconf(AVCodecContext *avctx, AVDictionary **dict)
if (res < 0)
return res;
+ if (ctx->qpfile_loaded && qpfile_aom_cpu_used(ctx) < QPFILE_AOM_MIN_CPU_USED) {
+ av_log(avctx, AV_LOG_ERROR,
+ "qpfile with libaom-av1 requires cpu-used >= 7, also when set through "
+ "aom-params; libaom applies ROI maps only at speed 7 or more.\n");
+ return AVERROR(EINVAL);
+ }
+
res = aom_config(avctx, ctx->encoder.iface);
if (res < 0)
return res;
@@ -1621,6 +1888,7 @@ static const AVOption options[] = {
{ "tune", "The metric that the encoder tunes for. Automatically chosen by the encoder by default", OFFSET(tune), AV_OPT_TYPE_INT, {.i64 = -1}, -1, AOM_TUNE_SSIM, VE, .unit = "tune"},
{ "psnr", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = AOM_TUNE_PSNR}, 0, 0, VE, .unit = "tune"},
{ "ssim", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = AOM_TUNE_SSIM}, 0, 0, VE, .unit = "tune"},
+ { "qpfile", "Read per-frame QP offsets from a file as a region-of-interest map (needs libaom 3.13.0 or newer)", OFFSET(qpfile_path), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, VE },
FF_AV1_PROFILE_OPTS
{ "still-picture", "Encode in single frame mode (typically used for still AVIF images).", OFFSET(still_picture), AV_OPT_TYPE_BOOL, {.i64 = 0}, -1, 1, VE },
{ "dolbyvision", "Enable Dolby Vision RPU coding", OFFSET(dovi.enable), AV_OPT_TYPE_BOOL, {.i64 = FF_DOVI_AUTOMATIC }, -1, 1, VE, .unit = "dovi" },
diff --git a/libavcodec/qpfile_parser.c b/libavcodec/qpfile_parser.c
new file mode 100644
index 0000000000..a061c78c7e
--- /dev/null
+++ b/libavcodec/qpfile_parser.c
@@ -0,0 +1,564 @@
+/*
+ * Copyright 2026 Lusoris
+ *
+ * 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.
+ */
+
+/**
+ * @file
+ * Shared parser for the per-frame QP-offset file format consumed by libx264,
+ * libsvtav1, and libaom-av1 encoder adapters. The format consists of
+ * <frame_idx> <I|P|B> <qp> followed by per-MB-row deltas.
+ *
+ * Format (ASCII, one logical record per frame):
+ *
+ * <frame_idx> <I|P|B> <baseline_qp>
+ * <delta_0_0> <delta_0_1> ... <delta_0_(bw-1)>
+ * ...
+ *
+ * Lines are read with fgetc(), not POSIX getline().
+ */
+
+#include <errno.h>
+#include <limits.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "libavutil/common.h"
+#include "libavutil/avstring.h"
+#include "libavutil/error.h"
+#include "libavutil/file_open.h"
+#include "libavutil/log.h"
+#include "libavutil/macros.h"
+#include "libavutil/mem.h"
+
+#include "qpfile_parser.h"
+
+#define QPFILE_MAX_FRAMES (1u << 20)
+#define QPFILE_MAX_BLOCKS_PER_DIM (1u << 14)
+#define QPFILE_MAX_LINE_BYTES (1u << 20)
+
+/* Parse a base-10 64-bit integer from a string, returning 0 or an error code. */
+static int parse_int64(const char *s, char **end, int64_t *out)
+{
+ int64_t v;
+ errno = 0;
+ v = strtoll(s, end, 10);
+ if (errno == ERANGE)
+ return AVERROR(ERANGE);
+ if (*end == s)
+ return AVERROR(EINVAL);
+ *out = v;
+ return 0;
+}
+
+/* Clamp a QP delta value to the allowed range, returning the clamped value. */
+static int clamp_offset(int64_t v)
+{
+ return av_clip64(v, QPFILE_DELTA_MIN, QPFILE_DELTA_MAX);
+}
+
+/* Skip spaces and tabs, returning the first other character. */
+static const char *skip_blank(const char *p)
+{
+ while (*p == ' ' || *p == '\t')
+ p++;
+ return p;
+}
+
+/* Test whether c is a frame type letter (I, P or B, any case), returning 1 or 0. */
+static int is_frame_type(char c)
+{
+ return c && strchr("IPBipb", c);
+}
+
+/* Test whether a line matches the frame header format, returning 1 or 0. */
+static int looks_like_header(const char *line)
+{
+ const char *p = skip_blank(line);
+
+ if (!av_isdigit(*p))
+ return 0;
+ while (av_isdigit(*p))
+ p++;
+ return is_frame_type(*skip_blank(p));
+}
+
+/* Return 1 if p contains only whitespace (' ', '\t', '\r', '\n') up to '\0', else 0. */
+static int only_space(const char *p)
+{
+ while (*p) {
+ if (*p != ' ' && *p != '\t' && *p != '\r' && *p != '\n')
+ return 0;
+ p++;
+ }
+ return 1;
+}
+
+/* Parse a frame header line into an FFQpFrame, returning 0 or an error code. */
+static int parse_header(const char *line, FFQpFrame *f)
+{
+ char *p = NULL;
+ const char *cur;
+ int64_t idx = 0, qp = 0;
+ int err;
+
+ err = parse_int64(line, &p, &idx);
+ if (err < 0)
+ return err;
+ if (idx < 0 || idx > UINT_MAX)
+ return AVERROR(EINVAL);
+ cur = skip_blank(p);
+ if (!is_frame_type(*cur))
+ return AVERROR(EINVAL);
+ err = parse_int64(skip_blank(cur + 1), &p, &qp);
+ if (err < 0)
+ return err;
+ if (qp < 0 || qp > 63 || !only_space(p))
+ return AVERROR(EINVAL);
+
+ f->frame_index = (unsigned)idx;
+ f->block_offsets = NULL;
+ f->block_cols = 0;
+ f->block_rows = 0;
+ return 0;
+}
+
+/* Count whitespace-separated tokens on a line, returning the token count. */
+static unsigned count_tokens(const char *line)
+{
+ unsigned n = 0;
+ int in_tok = 0;
+ for (const char *p = line; *p; p++) {
+ if (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n') {
+ in_tok = 0;
+ } else if (!in_tok) {
+ in_tok = 1;
+ n++;
+ if (n > QPFILE_MAX_BLOCKS_PER_DIM)
+ return n;
+ }
+ }
+ return n;
+}
+
+/* Parse a row of clamped block QP deltas, returning 0 or a negative error. */
+static int parse_row(const char *line, int8_t *row_out, unsigned bw)
+{
+ char *p = NULL;
+ const char *cur = line;
+ int64_t v = 0;
+ for (unsigned i = 0; i < bw; i++) {
+ int err;
+ err = parse_int64(cur, &p, &v);
+ if (err < 0)
+ return err;
+ row_out[i] = (int8_t)clamp_offset(v);
+ cur = p;
+ while (*cur == ' ' || *cur == '\t')
+ cur++;
+ }
+ if (!only_space(cur))
+ return AVERROR(EINVAL);
+ return 0;
+}
+
+/* Allocate the first line buffer, returning 0 or an error code. */
+static int qpfile_line_alloc(char **buf, size_t *cap)
+{
+ if (*cap && *buf)
+ return 0;
+ *cap = 4096;
+ *buf = av_realloc(*buf, *cap);
+ return *buf ? 0 : AVERROR(ENOMEM);
+}
+
+/* Grow the line buffer to fit one more byte and the terminator, returning 0 or an error code. */
+static int qpfile_line_grow(char **buf, size_t *cap, size_t pos)
+{
+ size_t nc;
+ char *nb;
+
+ if (pos + 1 < *cap)
+ return 0;
+ nc = FFMIN((*cap) * 2u, (size_t)QPFILE_MAX_LINE_BYTES + 1);
+ nb = av_realloc(*buf, nc);
+ if (!nb)
+ return AVERROR(ENOMEM);
+ *buf = nb;
+ *cap = nc;
+ return 0;
+}
+
+/* End the line at end of file, setting out_len to -1 when nothing was read. */
+static int qpfile_line_eof(FILE *fp, char *buf, size_t pos, ptrdiff_t *out_len)
+{
+ if (ferror(fp))
+ return AVERROR(EIO);
+ if (!pos) {
+ *out_len = -1;
+ return 0;
+ }
+ buf[pos] = 0;
+ *out_len = (ptrdiff_t)pos;
+ return 0;
+}
+
+/* Portable line reader (no POSIX getline dependency). */
+static int qpfile_getline(char **buf, size_t *cap, FILE *fp, ptrdiff_t *out_len)
+{
+ size_t pos = 0;
+ int ret = qpfile_line_alloc(buf, cap);
+
+ if (ret < 0)
+ return ret;
+ while (1) {
+ int c;
+
+ ret = qpfile_line_grow(buf, cap, pos);
+ if (ret < 0)
+ return ret;
+ c = fgetc(fp);
+ if (c == EOF)
+ return qpfile_line_eof(fp, *buf, pos, out_len);
+ if (!c || pos >= QPFILE_MAX_LINE_BYTES)
+ return AVERROR(EINVAL);
+ (*buf)[pos++] = (char)c;
+ if (c == '\n') {
+ (*buf)[pos] = 0;
+ *out_len = (ptrdiff_t)pos;
+ return 0;
+ }
+ }
+}
+
+typedef struct QpLoadState {
+ void *log_ctx;
+ unsigned bw, bh, cap_frames, row_count, line_number;
+ int8_t *row_buf;
+ FFQpFrame *cur_frame;
+} QpLoadState;
+
+/* Finalise the current frame's block buffer, returning 0 or an error code. */
+static int qpfile_finish_frame(QpLoadState *st)
+{
+ FFQpFrame *f = st->cur_frame;
+ if (f && st->row_count > 0) {
+ if (!st->bw) {
+ st->bw = f->block_cols;
+ st->bh = st->row_count;
+ } else if (st->row_count != st->bh) {
+ return AVERROR(EINVAL);
+ }
+ f->block_offsets = av_memdup(st->row_buf, (size_t)st->bh * st->bw * sizeof(*st->row_buf));
+ if (!f->block_offsets)
+ return AVERROR(ENOMEM);
+ f->block_rows = st->bh;
+ f->block_cols = st->bw;
+ }
+ return 0;
+}
+
+/* Append a new frame from a header line, returning 0 or a negative error. */
+static int qpfile_add_header(FFQpFile *out, QpLoadState *st, const char *line)
+{
+ int ret = qpfile_finish_frame(st);
+
+ if (ret < 0)
+ return ret;
+ if (out->frame_count == st->cap_frames) {
+ unsigned nc = st->cap_frames * 2u;
+ FFQpFrame *nf;
+ if (nc > QPFILE_MAX_FRAMES)
+ return AVERROR(EINVAL);
+ nf = av_realloc_array(out->frames, nc, sizeof(*nf));
+ if (!nf)
+ return AVERROR(ENOMEM);
+ memset(nf + st->cap_frames, 0, (nc - st->cap_frames) * sizeof(*nf));
+ out->frames = nf;
+ st->cap_frames = nc;
+ }
+ st->cur_frame = &out->frames[out->frame_count];
+ ret = parse_header(line, st->cur_frame);
+ if (ret < 0)
+ return ret;
+ if (out->frame_count > 0) {
+ FFQpFrame *previous;
+ previous = &out->frames[out->frame_count - 1u];
+ if (st->cur_frame->frame_index <= previous->frame_index) {
+ av_log(st->log_ctx, AV_LOG_ERROR,
+ "qpfile: line %u frame index %u is not greater than "
+ "previous index %u\n", st->line_number,
+ st->cur_frame->frame_index, previous->frame_index);
+ return AVERROR(EINVAL);
+ }
+ }
+ out->frame_count++;
+ st->row_count = 0;
+ return 0;
+}
+
+/* Set or check the frame's row width, returning 0 or an error code. */
+static int qpfile_set_row_width(QpLoadState *st, unsigned tokens)
+{
+ FFQpFrame *f = st->cur_frame;
+
+ if (tokens > QPFILE_MAX_BLOCKS_PER_DIM)
+ return AVERROR(EINVAL);
+ if (!f->block_cols) {
+ f->block_cols = tokens;
+ if (st->bw && tokens != st->bw)
+ return AVERROR(EINVAL);
+ } else if (tokens != f->block_cols) {
+ return AVERROR(EINVAL);
+ }
+ return 0;
+}
+
+/* Parse and append a block delta row to the frame, returning 0 or an error. */
+static int qpfile_add_row(QpLoadState *st, const char *line)
+{
+ unsigned tokens, this_bw, needed;
+ int8_t *nrow;
+ int ret;
+ if (!st->cur_frame)
+ return AVERROR(EINVAL);
+ tokens = count_tokens(line);
+ if (!tokens)
+ return 0;
+ ret = qpfile_set_row_width(st, tokens);
+ if (ret < 0)
+ return ret;
+ this_bw = st->cur_frame->block_cols;
+ needed = (st->row_count + 1) * this_bw;
+ nrow = av_realloc_array(st->row_buf, needed, sizeof(*st->row_buf));
+ if (!nrow)
+ return AVERROR(ENOMEM);
+ st->row_buf = nrow;
+ ret = parse_row(line, &st->row_buf[st->row_count * this_bw], this_bw);
+ if (ret < 0)
+ return ret;
+ st->row_count++;
+ if (st->row_count > QPFILE_MAX_BLOCKS_PER_DIM)
+ return AVERROR(EINVAL);
+ return 0;
+}
+
+/* Log a line-level parser failure and return the error code. */
+static int qpfile_line_error(const QpLoadState *st, const char *fmt_kind,
+ unsigned line, int err)
+{
+ av_log(st->log_ctx, AV_LOG_ERROR,
+ "qpfile: %s line %u: %s\n", fmt_kind, line, av_err2str(err));
+ return err;
+}
+
+/* Parse every frame header and row line in a file, returning 0 or an error. */
+static int qpfile_read_frames(FILE *fp, FFQpFile *out, QpLoadState *st,
+ char **line, size_t *line_cap)
+{
+ ptrdiff_t got = 0;
+ int ret;
+
+ for (;;) {
+ ret = qpfile_getline(line, line_cap, fp, &got);
+ if (ret < 0)
+ return qpfile_line_error(st, "error reading", st->line_number + 1, ret);
+ if (got < 0)
+ break;
+ st->line_number++;
+ if (only_space(*line) || (*line)[0] == '#')
+ continue;
+ if (looks_like_header(*line))
+ ret = qpfile_add_header(out, st, *line);
+ else
+ ret = qpfile_add_row(st, *line);
+ if (ret < 0)
+ return qpfile_line_error(st, "invalid", st->line_number, ret);
+ }
+ ret = qpfile_finish_frame(st);
+ if (ret < 0)
+ return qpfile_line_error(st, "invalid last record ending at",
+ st->line_number, ret);
+ return 0;
+}
+
+/* Load and parse a QP-offset file from disk into out. */
+int ff_qpfile_load(void *log_ctx, const char *path, FFQpFile *out)
+{
+ FILE *fp;
+ char *line = NULL;
+ size_t line_cap = 0;
+ QpLoadState st = { 0 };
+ int ret;
+
+ if (!path || !out)
+ return AVERROR(EINVAL);
+ memset(out, 0, sizeof(*out));
+ st.log_ctx = log_ctx;
+ fp = avpriv_fopen_utf8(path, "rb");
+ if (!fp)
+ return AVERROR(errno ? errno : ENOENT);
+ st.cap_frames = 16;
+ out->frames = av_calloc(st.cap_frames, sizeof(*out->frames));
+ if (!out->frames)
+ ret = AVERROR(ENOMEM);
+ else
+ ret = qpfile_read_frames(fp, out, &st, &line, &line_cap);
+ av_freep(&st.row_buf);
+ if (ret >= 0) {
+ out->block_cols = st.bw;
+ out->block_rows = st.bh;
+ if (!out->frame_count) {
+ av_log(log_ctx, AV_LOG_ERROR,
+ "qpfile: %s holds no frame record.\n", path);
+ ret = AVERROR(EINVAL);
+ }
+ }
+ av_free(line);
+ fclose(fp);
+ if (ret < 0)
+ ff_qpfile_free(out);
+ return ret;
+}
+
+/* Verify that the QP file grid matches the video macroblock dimensions. */
+int ff_qpfile_check_grid(void *log_ctx, const char *encoder, const FFQpFile *qf,
+ int width, int height)
+{
+ const unsigned mbx = (width + 15) / 16;
+ const unsigned mby = (height + 15) / 16;
+
+ if (!qf->block_cols && !qf->block_rows)
+ return 0;
+
+ if (qf->block_cols != mbx || qf->block_rows != mby) {
+ av_log(log_ctx, AV_LOG_ERROR,
+ "%s: the qpfile has %ux%u blocks per frame, the %dx%d video has %ux%u "
+ "macroblocks.\n", encoder, qf->block_cols, qf->block_rows,
+ width, height, mbx, mby);
+ return AVERROR(EINVAL);
+ }
+ return 0;
+}
+
+/* Free every frame's offset map and the frame array, and reset the counters. */
+void ff_qpfile_free(FFQpFile *qpf)
+{
+ if (!qpf)
+ return;
+ if (qpf->frames) {
+ for (unsigned i = 0; i < qpf->frame_count; i++)
+ av_freep(&qpf->frames[i].block_offsets);
+ av_freep(&qpf->frames);
+ }
+ qpf->frame_count = 0;
+ qpf->block_cols = 0;
+ qpf->block_rows = 0;
+}
+
+const FFQpFrame *ff_qpfile_frame_for_index(const FFQpFile *qf,
+ unsigned frame_index)
+{
+ unsigned low = 0, high;
+
+ if (!qf || !qf->frame_count)
+ return NULL;
+ high = qf->frame_count;
+ while (low < high) {
+ unsigned mid = low + (high - low) / 2;
+
+ if (qf->frames[mid].frame_index <= frame_index)
+ low = mid + 1;
+ else
+ high = mid;
+ }
+ return low ? &qf->frames[low - 1] : NULL;
+}
+
+/* Scan distinct offsets, their minimum, and their maximum into seen. */
+static void qpfile_histogram(const int8_t *vals, size_t n, uint8_t *seen,
+ int *min_off, int *max_off, unsigned *distinct)
+{
+ for (size_t i = 0; i < n; i++)
+ seen[vals[i] - QPFILE_DELTA_MIN] = 1;
+ for (int v = QPFILE_DELTA_MIN; v <= QPFILE_DELTA_MAX; v++) {
+ if (!seen[v - QPFILE_DELTA_MIN])
+ continue;
+ *min_off = FFMIN(*min_off, v);
+ *max_off = v;
+ (*distinct)++;
+ }
+}
+
+/* Select a representative palette of up to max_segments QP offsets. */
+unsigned ff_qpfile_palette(const int8_t *vals, size_t n, int *seg_values,
+ unsigned max_segments)
+{
+ uint8_t seen[QPFILE_LUT_SIZE] = { 0 };
+ int min_off = QPFILE_DELTA_MAX, max_off = QPFILE_DELTA_MIN;
+ unsigned distinct = 0;
+
+ if (!n || max_segments < 2)
+ return 0;
+ qpfile_histogram(vals, n, seen, &min_off, &max_off, &distinct);
+ if (distinct <= max_segments) {
+ unsigned k = 0;
+
+ for (int v = min_off; v <= max_off; v++)
+ if (seen[v - QPFILE_DELTA_MIN])
+ seg_values[k++] = v;
+ return k;
+ }
+ for (unsigned i = 0; i < max_segments; i++)
+ seg_values[i] = min_off +
+ (int)((unsigned)(max_off - min_off) * i / (max_segments - 1u));
+ return max_segments;
+}
+
+/* Fill seg_values with the palette of the frame's block offsets. */
+unsigned ff_qpfile_segment_values(const FFQpFrame *qf, int *seg_values,
+ unsigned max_segments)
+{
+ if (!qf->block_offsets || !qf->block_cols || !qf->block_rows)
+ return 0;
+ return ff_qpfile_palette(qf->block_offsets,
+ (size_t)qf->block_rows * qf->block_cols,
+ seg_values, max_segments);
+}
+
+/* Return the index of the segment value nearest v, the first one on a tie. */
+unsigned ff_qpfile_nearest_segment(int v, const int *seg_values, unsigned n_seg)
+{
+ unsigned best_idx = 0;
+ int best_dist = INT_MAX;
+
+ for (unsigned i = 0; i < n_seg; i++) {
+ int d = FFABS(v - seg_values[i]);
+
+ if (d < best_dist) {
+ best_dist = d;
+ best_idx = i;
+ }
+ }
+ return best_idx;
+}
+
+/* Fill lut with the nearest segment index for each valid offset. */
+void ff_qpfile_segment_lut(uint8_t *lut, const int *seg_values, unsigned n_seg)
+{
+ for (int v = QPFILE_DELTA_MIN; v <= QPFILE_DELTA_MAX; v++)
+ lut[v - QPFILE_DELTA_MIN] =
+ (uint8_t)ff_qpfile_nearest_segment(v, seg_values, n_seg);
+}
diff --git a/libavcodec/qpfile_parser.h b/libavcodec/qpfile_parser.h
new file mode 100644
index 0000000000..c8e3bb41d4
--- /dev/null
+++ b/libavcodec/qpfile_parser.h
@@ -0,0 +1,83 @@
+/*
+ * Copyright 2026 Lusoris
+ *
+ * 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.
+ */
+
+/**
+ * @file
+ * Shared parser for the per-frame QP-offset file format. Consumed by libx264,
+ * libsvtav1, and libaom-av1 encoder adapters via the new -qpfile
+ * AVOption.
+ *
+ * Keep the parser shared across encoder adapters so future
+ * encoder additions inherit the same format handling and
+ * validation rules.
+ *
+ * The parsed block offsets are QP deltas for libx264, deltas on libaom's
+ * 0..63 quantizer scale for libaom-av1 (libaom converts each to a
+ * quantizer index delta, 12 becoming 48) and AV1 quantizer index deltas
+ * for libsvtav1.
+ */
+
+#ifndef AVCODEC_QPFILE_PARSER_H
+#define AVCODEC_QPFILE_PARSER_H
+
+#include <stddef.h>
+#include <stdint.h>
+
+#define QPFILE_DELTA_MIN (-12)
+#define QPFILE_DELTA_MAX (12)
+#define QPFILE_LUT_SIZE (QPFILE_DELTA_MAX - QPFILE_DELTA_MIN + 1)
+
+typedef struct FFQpFrame {
+ unsigned int frame_index;
+ int8_t *block_offsets;
+ unsigned int block_cols;
+ unsigned int block_rows;
+} FFQpFrame;
+
+typedef struct FFQpFile {
+ FFQpFrame *frames;
+ unsigned int frame_count;
+ unsigned int block_cols;
+ unsigned int block_rows;
+} FFQpFile;
+
+/** Load a per-frame QP-offset file into out, logging errors to log_ctx. */
+int ff_qpfile_load(void *log_ctx, const char *path, FFQpFile *out);
+/** Verify that the QP file grid matches the video macroblock dimensions. */
+int ff_qpfile_check_grid(void *log_ctx, const char *encoder, const FFQpFile *qf,
+ int width, int height);
+/** Free all memory allocated inside an FFQpFile structure. */
+void ff_qpfile_free(FFQpFile *qpf);
+/** Look up the QP frame record matching or preceding the given frame index. */
+const FFQpFrame *ff_qpfile_frame_for_index(const FFQpFile *qf,
+ unsigned frame_index);
+/** Fill seg_values with the palette (see ff_qpfile_palette) of the frame's
+ * block offsets, returning its size, or 0 without offsets. */
+unsigned ff_qpfile_segment_values(const FFQpFrame *qf, int *seg_values,
+ unsigned max_segments);
+/** Return the index of the segment value nearest v, the first one on a tie. */
+unsigned ff_qpfile_nearest_segment(int v, const int *seg_values, unsigned n_seg);
+/** Fill seg_values, ascending, with each distinct value of the n offsets in
+ * vals when there are at most max_segments (at least 2) of them, else with
+ * max_segments evenly spaced values over their range; return the count,
+ * 0 when n is 0. Every value must lie in QPFILE_DELTA_MIN..QPFILE_DELTA_MAX. */
+unsigned ff_qpfile_palette(const int8_t *vals, size_t n, int *seg_values,
+ unsigned max_segments);
+/** Fill lut[QPFILE_LUT_SIZE] with the nearest segment index of each offset
+ * from QPFILE_DELTA_MIN to QPFILE_DELTA_MAX. */
+void ff_qpfile_segment_lut(uint8_t *lut, const int *seg_values, unsigned n_seg);
+
+#endif /* AVCODEC_QPFILE_PARSER_H */
diff --git a/libavcodec/tests/.gitignore b/libavcodec/tests/.gitignore
index 436476bc78..f78e17f588 100644
--- a/libavcodec/tests/.gitignore
+++ b/libavcodec/tests/.gitignore
@@ -21,5 +21,6 @@
/mpeg12framerate
/mpegaudiodecheader
/packet_side_data_handle
+/qpfile_parser
/rangecoder
/snowenc
diff --git a/libavcodec/tests/qpfile_parser.c b/libavcodec/tests/qpfile_parser.c
new file mode 100644
index 0000000000..6784fc3862
--- /dev/null
+++ b/libavcodec/tests/qpfile_parser.c
@@ -0,0 +1,253 @@
+/*
+ * Copyright 2026 Lusoris
+ *
+ * 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.
+ */
+
+#include <stdio.h>
+#include <string.h>
+
+#include "libavutil/error.h"
+#include "libavutil/macros.h"
+#include "libavutil/random_seed.h"
+#include "libavcodec/qpfile_parser.h"
+
+typedef struct FixtureCase {
+ const char *name;
+ const char *bytes;
+ size_t len;
+ void (*check)(const FFQpFile *qf);
+} FixtureCase;
+
+/* Return the short symbolic name of an error code. */
+static const char *err_name(int err)
+{
+ if (!err)
+ return "ok";
+ if (err == AVERROR(EINVAL))
+ return "EINVAL";
+ if (err == AVERROR(ERANGE))
+ return "ERANGE";
+ if (err == AVERROR(ENOMEM))
+ return "ENOMEM";
+ return "error";
+}
+
+/* Print the frame index and block offsets for one frame. */
+static void print_frame(const char *name, unsigned idx, const FFQpFrame *f)
+{
+ unsigned total = f->block_rows * f->block_cols;
+ printf("%s frame %u: index %u offsets", name, idx, f->frame_index);
+ for (unsigned i = 0; i < total; i++)
+ printf(" %d", (int)f->block_offsets[i]);
+ printf("\n");
+}
+
+/* Run additional validation assertions on the valid fixture. */
+static void check_valid(const FFQpFile *qf)
+{
+ static const unsigned probe_indices[] = { 1, 2, 4, 5, 100 };
+ int vals[8];
+ unsigned n_vals;
+ int err;
+
+ print_frame("valid", 0, &qf->frames[0]);
+ print_frame("valid", 1, &qf->frames[1]);
+
+ err = ff_qpfile_check_grid(NULL, "test", qf, 32, 16);
+ printf("valid check_grid 32x16: %s\n", err_name(err));
+ err = ff_qpfile_check_grid(NULL, "test", qf, 48, 16);
+ printf("valid check_grid 48x16: %s\n", err_name(err));
+
+ for (unsigned i = 0; i < 5; i++) {
+ const FFQpFrame *f = ff_qpfile_frame_for_index(qf, probe_indices[i]);
+ if (f)
+ printf("valid frame_for_index %u: %u\n", probe_indices[i], f->frame_index);
+ else
+ printf("valid frame_for_index %u: none\n", probe_indices[i]);
+ }
+
+ n_vals = ff_qpfile_segment_values(&qf->frames[1], vals, 8);
+ printf("valid segment_values 1:");
+ for (unsigned i = 0; i < n_vals; i++)
+ printf(" %d", vals[i]);
+ printf("\n");
+}
+
+/* Run additional validation assertions on the clip fixture. */
+static void check_clip(const FFQpFile *qf)
+{
+ print_frame("clip", 0, &qf->frames[0]);
+}
+
+/* Run additional validation assertions on the header-only fixture. */
+static void check_header_only(const FFQpFile *qf)
+{
+ int err = ff_qpfile_check_grid(NULL, "test", qf, 32, 16);
+ printf("header-only check_grid 32x16: %s\n", err_name(err));
+}
+
+/* Print lookup results across populated, clearing, and resumed records. */
+static void check_clearing(const FFQpFile *qf)
+{
+ static const unsigned probes[] = { 1, 2, 4, 5, 7, 8, 100 };
+
+ for (unsigned i = 0; i < FF_ARRAY_ELEMS(probes); i++) {
+ const FFQpFrame *f = ff_qpfile_frame_for_index(qf, probes[i]);
+
+ if (!f)
+ printf("clearing lookup %u: none\n", probes[i]);
+ else if (!f->block_offsets)
+ printf("clearing lookup %u: index %u clear\n",
+ probes[i], f->frame_index);
+ else
+ print_frame("clearing lookup", probes[i], f);
+ }
+}
+
+/* Run additional validation assertions on the index-max fixture. */
+static void check_index_max(const FFQpFile *qf)
+{
+ print_frame("index-max", 0, &qf->frames[0]);
+}
+
+/* Write bytes to a file path, returning 0 on success or -1 on error. */
+static int write_fixture(const char *path, const char *bytes, size_t len)
+{
+ FILE *fp = fopen(path, "wb");
+ if (!fp)
+ return -1;
+ if (fwrite(bytes, 1, len, fp) != len) {
+ fclose(fp);
+ return -1;
+ }
+ if (fclose(fp) != 0)
+ return -1;
+ return 0;
+}
+
+/* Run one fixture test case against the temporary file path. */
+static int run_fixture_test(const char *path, const FixtureCase *tc)
+{
+ FFQpFile qf = { 0 };
+ int err, ret = 0;
+
+ if (write_fixture(path, tc->bytes, tc->len) < 0) {
+ printf("%s: cannot write fixture\n", tc->name);
+ remove(path);
+ return 1;
+ }
+ err = ff_qpfile_load(NULL, path, &qf);
+ if (!err) {
+ printf("%s: ok frames %u grid %ux%u\n", tc->name,
+ qf.frame_count, qf.block_cols, qf.block_rows);
+ if (tc->check)
+ tc->check(&qf);
+ } else {
+ printf("%s: %s\n", tc->name, err_name(err));
+ }
+ ff_qpfile_free(&qf);
+ if (remove(path) != 0) {
+ printf("%s: cannot remove fixture\n", tc->name);
+ ret = 1;
+ }
+ return ret;
+}
+
+/* Test and print one palette calculation result. */
+static void test_palette(const char *label, const int8_t *vals, size_t n, unsigned budget)
+{
+ int out[32];
+ unsigned count = ff_qpfile_palette(vals, n, out, budget);
+ printf("%s:", label);
+ if (!count) {
+ printf(" (none)\n");
+ return;
+ }
+ for (unsigned i = 0; i < count; i++)
+ printf(" %d", out[i]);
+ printf("\n");
+}
+
+/* Run the suite of palette calculation checks. */
+static void test_palettes(void)
+{
+ static const int8_t p1[3] = { -12, 0, 12 };
+ int8_t p_all[25];
+
+ for (int i = 0; i < FF_ARRAY_ELEMS(p_all); i++)
+ p_all[i] = (int8_t)(-12 + i);
+
+ test_palette("palette -12 0 12 budget 8", p1, 3, 8);
+ test_palette("palette -12 0 12 budget 2", p1, 3, 2);
+ test_palette("palette -12..12 budget 8", p_all, 25, 8);
+ test_palette("palette empty budget 8", NULL, 0, 8);
+ test_palette("palette -12 0 12 budget 1", p1, 3, 1);
+}
+
+/* Test and print segment lookup-table indices for all offsets. */
+static void test_lut(void)
+{
+ static const int seg[3] = { -12, 0, 12 };
+ uint8_t lut[QPFILE_LUT_SIZE];
+ ff_qpfile_segment_lut(lut, seg, 3);
+ printf("lut -12 0 12:");
+ for (unsigned i = 0; i < QPFILE_LUT_SIZE; i++)
+ printf(" %u", (unsigned)lut[i]);
+ printf("\n");
+}
+
+/* Main entry point for the QP file parser regression test. */
+int main(void)
+{
+ static const FixtureCase cases[] = {
+ { "valid", " \t\n# comment\n2 I 26\n-12 12\n \t\n5 P 30\n3 -3\n",
+ sizeof(" \t\n# comment\n2 I 26\n-12 12\n \t\n5 P 30\n3 -3\n") - 1, check_valid },
+ { "crlf", "2 I 26\r\n-12 12\r\n5 P 30\r\n3 -3\r\n",
+ sizeof("2 I 26\r\n-12 12\r\n5 P 30\r\n3 -3\r\n") - 1, NULL },
+ { "clip", "0 I 26\n-20 20\n",
+ sizeof("0 I 26\n-20 20\n") - 1, check_clip },
+ { "header-only", "0 I 26\n3 P 26\n",
+ sizeof("0 I 26\n3 P 26\n") - 1, check_header_only },
+ { "clearing", "2 I 26\n1 2\n5 P 26\n8 B 26\n-3 3\n",
+ sizeof("2 I 26\n1 2\n5 P 26\n8 B 26\n-3 3\n") - 1, check_clearing },
+ { "index-max", "4294967295 I 26\n-1 1\n",
+ sizeof("4294967295 I 26\n-1 1\n") - 1, check_index_max },
+ { "index-over", "4294967296 I 26\n",
+ sizeof("4294967296 I 26\n") - 1, NULL },
+ { "not-increasing", "5 I 26\n5 P 26\n",
+ sizeof("5 I 26\n5 P 26\n") - 1, NULL },
+ { "no-record", "# only a comment\n\n",
+ sizeof("# only a comment\n\n") - 1, NULL },
+ { "nul", "0 I 26\n-12 12\0junk\n",
+ sizeof("0 I 26\n-12 12\0junk\n") - 1, NULL },
+ { "row-width", "0 I 26\n1 2\n3\n",
+ sizeof("0 I 26\n1 2\n3\n") - 1, NULL },
+ { "frame-width", "0 I 26\n1 2\n1 P 26\n3\n",
+ sizeof("0 I 26\n1 2\n1 P 26\n3\n") - 1, NULL },
+ { "frame-rows", "0 I 26\n1 2\n1 P 26\n3 4\n5 6\n",
+ sizeof("0 I 26\n1 2\n1 P 26\n3 4\n5 6\n") - 1, NULL },
+ };
+ char path[64];
+ unsigned seed = av_get_random_seed();
+ int ret = 0;
+
+ snprintf(path, sizeof(path), "ff-qpfile-test-%08x.txt", seed);
+ for (size_t i = 0; i < FF_ARRAY_ELEMS(cases); i++) {
+ if (run_fixture_test(path, &cases[i]) != 0)
+ ret = 1;
+ }
+ test_palettes();
+ test_lut();
+ return ret;
+}
diff --git a/tests/fate/libavcodec.mak b/tests/fate/libavcodec.mak
index 2e2dabcd14..11b02ae77c 100644
--- a/tests/fate/libavcodec.mak
+++ b/tests/fate/libavcodec.mak
@@ -143,5 +143,9 @@ $(FATE_SAMPLES_ENC_RECON-yes): CMP = null
FATE_EXTERN-yes += $(FATE_SAMPLES_ENC_RECON-yes)
fate-enc-recon: $(FATE_SAMPLES_ENC_RECON-yes)
+FATE_LIBAVCODEC-$(CONFIG_QPFILE) += fate-qpfile-parser
+fate-qpfile-parser: libavcodec/tests/qpfile_parser$(EXESUF)
+fate-qpfile-parser: CMD = run libavcodec/tests/qpfile_parser$(EXESUF)
+
FATE-$(CONFIG_AVCODEC) += $(FATE_LIBAVCODEC-yes)
fate-libavcodec: $(FATE_LIBAVCODEC-yes)
diff --git a/tests/ref/fate/qpfile-parser b/tests/ref/fate/qpfile-parser
new file mode 100644
index 0000000000..1a224eae2a
--- /dev/null
+++ b/tests/ref/fate/qpfile-parser
@@ -0,0 +1,39 @@
+valid: ok frames 2 grid 2x1
+valid frame 0: index 2 offsets -12 12
+valid frame 1: index 5 offsets 3 -3
+valid check_grid 32x16: ok
+valid check_grid 48x16: EINVAL
+valid frame_for_index 1: none
+valid frame_for_index 2: 2
+valid frame_for_index 4: 2
+valid frame_for_index 5: 5
+valid frame_for_index 100: 5
+valid segment_values 1: -3 3
+crlf: ok frames 2 grid 2x1
+clip: ok frames 1 grid 2x1
+clip frame 0: index 0 offsets -12 12
+header-only: ok frames 2 grid 0x0
+header-only check_grid 32x16: ok
+clearing: ok frames 3 grid 2x1
+clearing lookup 1: none
+clearing lookup frame 2: index 2 offsets 1 2
+clearing lookup frame 4: index 2 offsets 1 2
+clearing lookup 5: index 5 clear
+clearing lookup 7: index 5 clear
+clearing lookup frame 8: index 8 offsets -3 3
+clearing lookup frame 100: index 8 offsets -3 3
+index-max: ok frames 1 grid 2x1
+index-max frame 0: index 4294967295 offsets -1 1
+index-over: EINVAL
+not-increasing: EINVAL
+no-record: EINVAL
+nul: EINVAL
+row-width: EINVAL
+frame-width: EINVAL
+frame-rows: EINVAL
+palette -12 0 12 budget 8: -12 0 12
+palette -12 0 12 budget 2: -12 12
+palette -12..12 budget 8: -12 -9 -6 -2 1 5 8 12
+palette empty budget 8: (none)
+palette -12 0 12 budget 1: (none)
+lut -12 0 12: 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2