FFmpeg
Loading...
Searching...
No Matches
qpfile_parser.c
Go to the documentation of this file.
1/*
2 * Copyright 2026 Lusoris
3 *
4 * This file is part of FFmpeg.
5 *
6 * FFmpeg is free software; you can redistribute it and/or modify it under
7 * the terms of the GNU Lesser General Public License as published by the
8 * Free Software Foundation; either version 2.1 of the License, or (at
9 * your option) any later version.
10 *
11 * FFmpeg is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
14 * License for more details.
15 */
16
17/**
18 * @file
19 * Shared parser for the per-frame QP-offset file format consumed by libx264,
20 * libsvtav1, and libaom-av1 encoder adapters. The format consists of
21 * <frame_idx> <I|P|B> <qp> followed by per-MB-row deltas.
22 *
23 * Format (ASCII, one logical record per frame):
24 *
25 * <frame_idx> <I|P|B> <baseline_qp>
26 * <delta_0_0> <delta_0_1> ... <delta_0_(bw-1)>
27 * ...
28 *
29 * Lines are read with fgetc(), not POSIX getline().
30 */
31
32#include <errno.h>
33#include <limits.h>
34#include <stdio.h>
35#include <stdlib.h>
36#include <string.h>
37
38#include "libavutil/common.h"
39#include "libavutil/avstring.h"
40#include "libavutil/error.h"
41#include "libavutil/file_open.h"
42#include "libavutil/log.h"
43#include "libavutil/macros.h"
44#include "libavutil/mem.h"
45
46#include "qpfile_parser.h"
47
48#define QPFILE_MAX_FRAMES (1u << 20)
49#define QPFILE_MAX_BLOCKS_PER_DIM (1u << 14)
50#define QPFILE_MAX_LINE_BYTES (1u << 20)
51
52/* Parse a base-10 64-bit integer from a string, returning 0 or an error code. */
53static int parse_int64(const char *s, char **end, int64_t *out)
54{
55 int64_t v;
56 errno = 0;
57 v = strtoll(s, end, 10);
58 if (errno == ERANGE)
59 return AVERROR(ERANGE);
60 if (*end == s)
61 return AVERROR(EINVAL);
62 *out = v;
63 return 0;
64}
65
66/* Clamp a QP delta value to the allowed range, returning the clamped value. */
67static int clamp_offset(int64_t v)
68{
70}
71
72/* Skip spaces and tabs, returning the first other character. */
73static const char *skip_blank(const char *p)
74{
75 while (*p == ' ' || *p == '\t')
76 p++;
77 return p;
78}
79
80/* Test whether c is a frame type letter (I, P or B, any case), returning 1 or 0. */
81static int is_frame_type(char c)
82{
83 return c && strchr("IPBipb", c);
84}
85
86/* Test whether a line matches the frame header format, returning 1 or 0. */
87static int looks_like_header(const char *line)
88{
89 const char *p = skip_blank(line);
90
91 if (!av_isdigit(*p))
92 return 0;
93 while (av_isdigit(*p))
94 p++;
95 return is_frame_type(*skip_blank(p));
96}
97
98/* Return 1 if p contains only whitespace (' ', '\t', '\r', '\n') up to '\0', else 0. */
99static int only_space(const char *p)
100{
101 while (*p) {
102 if (*p != ' ' && *p != '\t' && *p != '\r' && *p != '\n')
103 return 0;
104 p++;
105 }
106 return 1;
107}
108
109/* Parse a frame header line into an FFQpFrame, returning 0 or an error code. */
110static int parse_header(const char *line, FFQpFrame *f)
111{
112 char *p = NULL;
113 const char *cur;
114 int64_t idx = 0, qp = 0;
115 int err;
116
117 err = parse_int64(line, &p, &idx);
118 if (err < 0)
119 return err;
120 if (idx < 0 || idx > UINT_MAX)
121 return AVERROR(EINVAL);
122 cur = skip_blank(p);
123 if (!is_frame_type(*cur))
124 return AVERROR(EINVAL);
125 err = parse_int64(skip_blank(cur + 1), &p, &qp);
126 if (err < 0)
127 return err;
128 if (qp < 0 || qp > 63 || !only_space(p))
129 return AVERROR(EINVAL);
130
131 f->frame_index = (unsigned)idx;
132 f->block_offsets = NULL;
133 f->block_cols = 0;
134 f->block_rows = 0;
135 return 0;
136}
137
138/* Count whitespace-separated tokens on a line, returning the token count. */
139static unsigned count_tokens(const char *line)
140{
141 unsigned n = 0;
142 int in_tok = 0;
143 for (const char *p = line; *p; p++) {
144 if (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n') {
145 in_tok = 0;
146 } else if (!in_tok) {
147 in_tok = 1;
148 n++;
150 return n;
151 }
152 }
153 return n;
154}
155
156/* Parse a row of clamped block QP deltas, returning 0 or a negative error. */
157static int parse_row(const char *line, int8_t *row_out, unsigned bw)
158{
159 char *p = NULL;
160 const char *cur = line;
161 int64_t v = 0;
162 for (unsigned i = 0; i < bw; i++) {
163 int err;
164 err = parse_int64(cur, &p, &v);
165 if (err < 0)
166 return err;
167 row_out[i] = (int8_t)clamp_offset(v);
168 cur = p;
169 while (*cur == ' ' || *cur == '\t')
170 cur++;
171 }
172 if (!only_space(cur))
173 return AVERROR(EINVAL);
174 return 0;
175}
176
177/* Allocate the first line buffer, returning 0 or an error code. */
178static int qpfile_line_alloc(char **buf, size_t *cap)
179{
180 if (*cap && *buf)
181 return 0;
182 *cap = 4096;
183 *buf = av_realloc(*buf, *cap);
184 return *buf ? 0 : AVERROR(ENOMEM);
185}
186
187/* Grow the line buffer to fit one more byte and the terminator, returning 0 or an error code. */
188static int qpfile_line_grow(char **buf, size_t *cap, size_t pos)
189{
190 size_t nc;
191 char *nb;
192
193 if (pos + 1 < *cap)
194 return 0;
195 nc = FFMIN((*cap) * 2u, (size_t)QPFILE_MAX_LINE_BYTES + 1);
196 nb = av_realloc(*buf, nc);
197 if (!nb)
198 return AVERROR(ENOMEM);
199 *buf = nb;
200 *cap = nc;
201 return 0;
202}
203
204/* End the line at end of file, setting out_len to -1 when nothing was read. */
205static int qpfile_line_eof(FILE *fp, char *buf, size_t pos, ptrdiff_t *out_len)
206{
207 if (ferror(fp))
208 return AVERROR(EIO);
209 if (!pos) {
210 *out_len = -1;
211 return 0;
212 }
213 buf[pos] = 0;
214 *out_len = (ptrdiff_t)pos;
215 return 0;
216}
217
218/* Portable line reader (no POSIX getline dependency). */
219static int qpfile_getline(char **buf, size_t *cap, FILE *fp, ptrdiff_t *out_len)
220{
221 size_t pos = 0;
222 int ret = qpfile_line_alloc(buf, cap);
223
224 if (ret < 0)
225 return ret;
226 while (1) {
227 int c;
228
229 ret = qpfile_line_grow(buf, cap, pos);
230 if (ret < 0)
231 return ret;
232 c = fgetc(fp);
233 if (c == EOF)
234 return qpfile_line_eof(fp, *buf, pos, out_len);
235 if (!c || pos >= QPFILE_MAX_LINE_BYTES)
236 return AVERROR(EINVAL);
237 (*buf)[pos++] = (char)c;
238 if (c == '\n') {
239 (*buf)[pos] = 0;
240 *out_len = (ptrdiff_t)pos;
241 return 0;
242 }
243 }
244}
245
252
253/* Finalise the current frame's block buffer, returning 0 or an error code. */
255{
256 FFQpFrame *f = st->cur_frame;
257 if (f && st->row_count > 0) {
258 if (!st->bw) {
259 st->bw = f->block_cols;
260 st->bh = st->row_count;
261 } else if (st->row_count != st->bh) {
262 return AVERROR(EINVAL);
263 }
264 f->block_offsets = av_memdup(st->row_buf, (size_t)st->bh * st->bw * sizeof(*st->row_buf));
265 if (!f->block_offsets)
266 return AVERROR(ENOMEM);
267 f->block_rows = st->bh;
268 f->block_cols = st->bw;
269 }
270 return 0;
271}
272
273/* Append a new frame from a header line, returning 0 or a negative error. */
274static int qpfile_add_header(FFQpFile *out, QpLoadState *st, const char *line)
275{
276 int ret = qpfile_finish_frame(st);
277
278 if (ret < 0)
279 return ret;
280 if (out->frame_count == st->cap_frames) {
281 unsigned nc = st->cap_frames * 2u;
282 FFQpFrame *nf;
283 if (nc > QPFILE_MAX_FRAMES)
284 return AVERROR(EINVAL);
285 nf = av_realloc_array(out->frames, nc, sizeof(*nf));
286 if (!nf)
287 return AVERROR(ENOMEM);
288 memset(nf + st->cap_frames, 0, (nc - st->cap_frames) * sizeof(*nf));
289 out->frames = nf;
290 st->cap_frames = nc;
291 }
292 st->cur_frame = &out->frames[out->frame_count];
294 if (ret < 0)
295 return ret;
296 if (out->frame_count > 0) {
297 FFQpFrame *previous;
298 previous = &out->frames[out->frame_count - 1u];
299 if (st->cur_frame->frame_index <= previous->frame_index) {
301 "qpfile: line %u frame index %u is not greater than "
302 "previous index %u\n", st->line_number,
303 st->cur_frame->frame_index, previous->frame_index);
304 return AVERROR(EINVAL);
305 }
306 }
307 out->frame_count++;
308 st->row_count = 0;
309 return 0;
310}
311
312/* Set or check the frame's row width, returning 0 or an error code. */
313static int qpfile_set_row_width(QpLoadState *st, unsigned tokens)
314{
315 FFQpFrame *f = st->cur_frame;
316
317 if (tokens > QPFILE_MAX_BLOCKS_PER_DIM)
318 return AVERROR(EINVAL);
319 if (!f->block_cols) {
320 f->block_cols = tokens;
321 if (st->bw && tokens != st->bw)
322 return AVERROR(EINVAL);
323 } else if (tokens != f->block_cols) {
324 return AVERROR(EINVAL);
325 }
326 return 0;
327}
328
329/* Parse and append a block delta row to the frame, returning 0 or an error. */
330static int qpfile_add_row(QpLoadState *st, const char *line)
331{
332 unsigned tokens, this_bw, needed;
333 int8_t *nrow;
334 int ret;
335 if (!st->cur_frame)
336 return AVERROR(EINVAL);
337 tokens = count_tokens(line);
338 if (!tokens)
339 return 0;
340 ret = qpfile_set_row_width(st, tokens);
341 if (ret < 0)
342 return ret;
343 this_bw = st->cur_frame->block_cols;
344 needed = (st->row_count + 1) * this_bw;
345 nrow = av_realloc_array(st->row_buf, needed, sizeof(*st->row_buf));
346 if (!nrow)
347 return AVERROR(ENOMEM);
348 st->row_buf = nrow;
349 ret = parse_row(line, &st->row_buf[st->row_count * this_bw], this_bw);
350 if (ret < 0)
351 return ret;
352 st->row_count++;
354 return AVERROR(EINVAL);
355 return 0;
356}
357
358/* Log a line-level parser failure and return the error code. */
359static int qpfile_line_error(const QpLoadState *st, const char *fmt_kind,
360 unsigned line, int err)
361{
363 "qpfile: %s line %u: %s\n", fmt_kind, line, av_err2str(err));
364 return err;
365}
366
367/* Parse every frame header and row line in a file, returning 0 or an error. */
369 char **line, size_t *line_cap)
370{
371 ptrdiff_t got = 0;
372 int ret;
373
374 for (;;) {
375 ret = qpfile_getline(line, line_cap, fp, &got);
376 if (ret < 0)
377 return qpfile_line_error(st, "error reading", st->line_number + 1, ret);
378 if (got < 0)
379 break;
380 st->line_number++;
381 if (only_space(*line) || (*line)[0] == '#')
382 continue;
384 ret = qpfile_add_header(out, st, *line);
385 else
386 ret = qpfile_add_row(st, *line);
387 if (ret < 0)
388 return qpfile_line_error(st, "invalid", st->line_number, ret);
389 }
391 if (ret < 0)
392 return qpfile_line_error(st, "invalid last record ending at",
393 st->line_number, ret);
394 return 0;
395}
396
397/* Load and parse a QP-offset file from disk into out. */
398int ff_qpfile_load(void *log_ctx, const char *path, FFQpFile *out)
399{
400 FILE *fp;
401 char *line = NULL;
402 size_t line_cap = 0;
403 QpLoadState st = { 0 };
404 int ret;
405
406 if (!path || !out)
407 return AVERROR(EINVAL);
408 memset(out, 0, sizeof(*out));
409 st.log_ctx = log_ctx;
410 fp = avpriv_fopen_utf8(path, "rb");
411 if (!fp)
412 return AVERROR(errno ? errno : ENOENT);
413 st.cap_frames = 16;
414 out->frames = av_calloc(st.cap_frames, sizeof(*out->frames));
415 if (!out->frames)
416 ret = AVERROR(ENOMEM);
417 else
418 ret = qpfile_read_frames(fp, out, &st, &line, &line_cap);
419 av_freep(&st.row_buf);
420 if (ret >= 0) {
421 out->block_cols = st.bw;
422 out->block_rows = st.bh;
423 if (!out->frame_count) {
424 av_log(log_ctx, AV_LOG_ERROR,
425 "qpfile: %s holds no frame record.\n", path);
426 ret = AVERROR(EINVAL);
427 }
428 }
429 av_free(line);
430 fclose(fp);
431 if (ret < 0)
433 return ret;
434}
435
436/* Verify that the QP file grid matches the video macroblock dimensions. */
437int ff_qpfile_check_grid(void *log_ctx, const char *encoder, const FFQpFile *qf,
438 int width, int height)
439{
440 const unsigned mbx = (width + 15) / 16;
441 const unsigned mby = (height + 15) / 16;
442
443 if (!qf->block_cols && !qf->block_rows)
444 return 0;
445
446 if (qf->block_cols != mbx || qf->block_rows != mby) {
447 av_log(log_ctx, AV_LOG_ERROR,
448 "%s: the qpfile has %ux%u blocks per frame, the %dx%d video has %ux%u "
449 "macroblocks.\n", encoder, qf->block_cols, qf->block_rows,
450 width, height, mbx, mby);
451 return AVERROR(EINVAL);
452 }
453 return 0;
454}
455
456/* Free every frame's offset map and the frame array, and reset the counters. */
458{
459 if (!qpf)
460 return;
461 if (qpf->frames) {
462 for (unsigned i = 0; i < qpf->frame_count; i++)
464 av_freep(&qpf->frames);
465 }
466 qpf->frame_count = 0;
467 qpf->block_cols = 0;
468 qpf->block_rows = 0;
469}
470
472 unsigned frame_index)
473{
474 unsigned low = 0, high;
475
476 if (!qf || !qf->frame_count)
477 return NULL;
478 high = qf->frame_count;
479 while (low < high) {
480 unsigned mid = low + (high - low) / 2;
481
482 if (qf->frames[mid].frame_index <= frame_index)
483 low = mid + 1;
484 else
485 high = mid;
486 }
487 return low ? &qf->frames[low - 1] : NULL;
488}
489
490/* Scan distinct offsets, their minimum, and their maximum into seen. */
491static void qpfile_histogram(const int8_t *vals, size_t n, uint8_t *seen,
492 int *min_off, int *max_off, unsigned *distinct)
493{
494 for (size_t i = 0; i < n; i++)
495 seen[vals[i] - QPFILE_DELTA_MIN] = 1;
496 for (int v = QPFILE_DELTA_MIN; v <= QPFILE_DELTA_MAX; v++) {
497 if (!seen[v - QPFILE_DELTA_MIN])
498 continue;
499 *min_off = FFMIN(*min_off, v);
500 *max_off = v;
501 (*distinct)++;
502 }
503}
504
505/* Select a representative palette of up to max_segments QP offsets. */
506unsigned ff_qpfile_palette(const int8_t *vals, size_t n, int *seg_values,
507 unsigned max_segments)
508{
509 uint8_t seen[QPFILE_LUT_SIZE] = { 0 };
510 int min_off = QPFILE_DELTA_MAX, max_off = QPFILE_DELTA_MIN;
511 unsigned distinct = 0;
512
513 if (!n || max_segments < 2)
514 return 0;
515 qpfile_histogram(vals, n, seen, &min_off, &max_off, &distinct);
516 if (distinct <= max_segments) {
517 unsigned k = 0;
518
519 for (int v = min_off; v <= max_off; v++)
520 if (seen[v - QPFILE_DELTA_MIN])
521 seg_values[k++] = v;
522 return k;
523 }
524 for (unsigned i = 0; i < max_segments; i++)
525 seg_values[i] = min_off +
526 (int)((unsigned)(max_off - min_off) * i / (max_segments - 1u));
527 return max_segments;
528}
529
530/* Fill seg_values with the palette of the frame's block offsets. */
531unsigned ff_qpfile_segment_values(const FFQpFrame *qf, int *seg_values,
532 unsigned max_segments)
533{
534 if (!qf->block_offsets || !qf->block_cols || !qf->block_rows)
535 return 0;
537 (size_t)qf->block_rows * qf->block_cols,
538 seg_values, max_segments);
539}
540
541/* Return the index of the segment value nearest v, the first one on a tie. */
542unsigned ff_qpfile_nearest_segment(int v, const int *seg_values, unsigned n_seg)
543{
544 unsigned best_idx = 0;
545 int best_dist = INT_MAX;
546
547 for (unsigned i = 0; i < n_seg; i++) {
548 int d = FFABS(v - seg_values[i]);
549
550 if (d < best_dist) {
551 best_dist = d;
552 best_idx = i;
553 }
554 }
555 return best_idx;
556}
557
558/* Fill lut with the nearest segment index for each valid offset. */
559void ff_qpfile_segment_lut(uint8_t *lut, const int *seg_values, unsigned n_seg)
560{
561 for (int v = QPFILE_DELTA_MIN; v <= QPFILE_DELTA_MAX; v++)
562 lut[v - QPFILE_DELTA_MIN] =
563 (uint8_t)ff_qpfile_nearest_segment(v, seg_values, n_seg);
564}
static FILE * out
#define i(width, name, range_min, range_max)
Definition cbs_h264.c:63
#define f(width, name)
Definition cbs_vp8.c:236
#define s(width, name)
Definition cbs_vp9.c:198
common internal and external API header
#define av_clip64
Definition common.h:103
#define FFABS(a)
Absolute value, Note, INT_MIN / INT64_MIN result in undefined behavior as they are not representable ...
Definition common.h:74
#define NULL
Definition coverity.c:32
long long int64_t
Definition coverity.c:34
int high
Definition dovi_rpuenc.c:39
error code definitions
char * path
Definition ffplay.c:385
int ret
Definition ffplay.c:391
#define av_err2str(errnum)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition error.h:122
#define AVERROR(e)
Definition error.h:45
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition log.h:210
void * av_realloc_array(void *ptr, size_t nmemb, size_t size)
Definition mem.c:318
void * av_memdup(const void *p, size_t size)
Duplicate a buffer with av_malloc().
Definition mem.c:408
static av_const int av_isdigit(int c)
Locale-independent conversion of ASCII isdigit.
Definition avstring.h:202
FILE * avpriv_fopen_utf8(const char *path, const char *mode)
Open a file using a UTF-8 filename.
Definition file_open.c:160
Utility Preprocessor macros.
#define FFMIN(a, b)
Definition macros.h:49
void * av_calloc(size_t nmemb, size_t size)
Definition mem.c:370
Memory handling functions.
#define av_realloc(p, s)
Definition ops_static.c:54
static const char * skip_blank(const char *p)
static int qpfile_line_alloc(char **buf, size_t *cap)
static int qpfile_line_error(const QpLoadState *st, const char *fmt_kind, unsigned line, int err)
#define QPFILE_MAX_LINE_BYTES
unsigned ff_qpfile_palette(const int8_t *vals, size_t n, int *seg_values, unsigned max_segments)
Fill seg_values, ascending, with each distinct value of the n offsets in vals when there are at most ...
static int parse_header(const char *line, FFQpFrame *f)
static int parse_int64(const char *s, char **end, int64_t *out)
static int qpfile_line_eof(FILE *fp, char *buf, size_t pos, ptrdiff_t *out_len)
static int is_frame_type(char c)
int ff_qpfile_load(void *log_ctx, const char *path, FFQpFile *out)
Load a per-frame QP-offset file into out, logging errors to log_ctx.
static unsigned count_tokens(const char *line)
static int clamp_offset(int64_t v)
const FFQpFrame * ff_qpfile_frame_for_index(const FFQpFile *qf, unsigned frame_index)
Look up the QP frame record matching or preceding the given frame index.
static int qpfile_set_row_width(QpLoadState *st, unsigned tokens)
static int qpfile_line_grow(char **buf, size_t *cap, size_t pos)
unsigned ff_qpfile_segment_values(const FFQpFrame *qf, int *seg_values, unsigned max_segments)
Fill seg_values with the palette (see ff_qpfile_palette) of the frame's block offsets,...
static int qpfile_finish_frame(QpLoadState *st)
static int parse_row(const char *line, int8_t *row_out, unsigned bw)
void ff_qpfile_segment_lut(uint8_t *lut, const int *seg_values, unsigned n_seg)
Fill lut[QPFILE_LUT_SIZE] with the nearest segment index of each offset from QPFILE_DELTA_MIN to QPFI...
#define QPFILE_MAX_BLOCKS_PER_DIM
static int qpfile_add_row(QpLoadState *st, const char *line)
#define QPFILE_MAX_FRAMES
int ff_qpfile_check_grid(void *log_ctx, const char *encoder, const FFQpFile *qf, int width, int height)
Verify that the QP file grid matches the video macroblock dimensions.
static int qpfile_read_frames(FILE *fp, FFQpFile *out, QpLoadState *st, char **line, size_t *line_cap)
static void qpfile_histogram(const int8_t *vals, size_t n, uint8_t *seen, int *min_off, int *max_off, unsigned *distinct)
void ff_qpfile_free(FFQpFile *qpf)
Free all memory allocated inside an FFQpFile structure.
static int qpfile_getline(char **buf, size_t *cap, FILE *fp, ptrdiff_t *out_len)
static int only_space(const char *p)
static int looks_like_header(const char *line)
unsigned ff_qpfile_nearest_segment(int v, const int *seg_values, unsigned n_seg)
Return the index of the segment value nearest v, the first one on a tie.
static int qpfile_add_header(FFQpFile *out, QpLoadState *st, const char *line)
Shared parser for the per-frame QP-offset file format.
#define QPFILE_DELTA_MIN
#define QPFILE_DELTA_MAX
#define QPFILE_LUT_SIZE
unsigned int pos
Definition spdifenc.c:431
unsigned int frame_count
unsigned int block_cols
unsigned int block_rows
FFQpFrame * frames
unsigned int block_cols
int8_t * block_offsets
unsigned int frame_index
unsigned int block_rows
unsigned line_number
int8_t * row_buf
FFQpFrame * cur_frame
unsigned cap_frames
unsigned row_count
#define av_free(p)
#define av_freep(p)
#define av_log(a,...)
#define height
Definition dsp.h:99
#define width
Definition dsp.h:99
FILE * fp
Definition swscale.c:145
static double c[64]