PR #25957 opened by luoye-cpu
URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/25957
Patch URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/25957.patch
Depends on #25872 (avfilter: add film_grain_adjust filter). This PR is stacked
on top of it: the first commit in the series is the content of #25872, included
so the tree applies cleanly — please review only the film_grain_apply commit
here. Once #25872 merges, the diff of this PR will automatically reduce to the
film_grain_apply commit.
FFmpeg can produce AV1 film grain synthesis parameters as
AV_FRAME_DATA_FILM_GRAIN_PARAMS frame side data (native av1, libdav1d and
qsvdec, gated by AV_CODEC_EXPORT_DATA_FILM_GRAIN), film_grain_adjust can
rewrite those parameters in flight, and libplacebo synthesises them for
display. What it cannot do is execute the synthesis inside the pipeline
itself: turning the parameters into pixels is left to the decoder
(libdav1d with apply_grain=1) or to the downstream consumer, and a
decoder that keeps its own synthesis on cannot be combined with
parameters that have just been adjusted in the filter chain.
The two filters are complementary by construction and do not overlap:
film_grain_adjust is the parameter author (it rewrites the film grain
side data and never touches the picture data), film_grain_apply is the
parameter executor (it reads the parameters attached to each frame and
synthesises the grain they describe into the picture data). Together
they complete the decode, adjust, apply, encode route: an encoder
downstream of this filter receives pictures with the grain already
synthesised from the adjusted parameters.
Add the film_grain_apply video filter to close that gap. The filter
layer is the natural place for this: film grain synthesis is a
per-frame operation driven by per-frame side data, the filter chain is
the generic place where per-frame side data can be consumed between
arbitrary sources and sinks, and the pixels it writes feed the next
stage directly without a re-encode.
The filter picks the parameter set to synthesise with
av_film_grain_params_select(), i.e. one synthesis per frame with the
set that the selection ranks highest; the remaining sets on the frame
become obsolete once the grain of the selected set is baked into the
pixels, so every AV_FRAME_DATA_FILM_GRAIN_PARAMS entry is removed from
the output frame ("applied" semantics, the same libplacebo follows by
deleting the entry after synthesis). H.274-type parameters are
synthesised inside the decoder, so frames whose selection resolves to
them (or to no usable set at all) pass through unchanged, keeping their
side data.
Because the synthesiser writes real pixels the filter clones the frame
and makes the picture buffers writable before synthesising
(copy-on-write, so frames sharing the buffer are never affected), and
it is not usable on hardware frames: query_formats restricts it to the
19 software pixel formats the synthesiser dispatches on
(gray8/9/10/12 and yuv 4:2:0/4:2:2/4:4:4 in 8..12 bit, the
limited-range yuvj variants included), so hardware formats fail at
graph configuration time rather than at synthesis time. The synthesiser
is the AV1 one the decoders already use, exposed from libavcodec with
the avpriv_ prefix: ff_aom_apply_film_grain is renamed to
avpriv_aom_apply_film_grain in four one-line places (the declaration in
libavcodec/aom_film_grain.h, the definition in
libavcodec/aom_film_grain.c and the two decoder call sites in
libavcodec/hevc/hevcdec.c and libavcodec/vvc/dec.c), behaviour
unchanged.
A single boolean option 'verbose' logs the parameters of the selected
set for the first synthesised frame and the per-role frame counts at
uninit.
## Testing
fate-api-film-grain-apply (new API test, enabled whenever the filter is
built) constructs frames with AV1 and H.274 parameter sets in-process
and asserts:
- deterministic synthesis: two passes over the same parameters produce
bit-exact pixels, the output frame carries zero film grain entries
afterwards, and the side data of the input frame is unchanged (the
copy-on-write isolation);
- frames without film grain side data pass through with identical pixel
CRCs;
- H.274-only frames pass through unchanged with their side data intact;
- a frame carrying several sets (two AV1 + one H.274) synthesises the
set av_film_grain_params_select() ranks highest and ends with zero
film grain entries;
- an unparseable option value is rejected with the documented EINVAL,
asserted via errno symbol comparison rather than a hardcoded -22;
- the test helpers mirror the construction pattern of the
api-film-grain-adjust test.
The FATE suite passes with the filter added: fate-api-film-grain-apply
passes three consecutive rounds, and the two film_grain_adjust
regression entries (fate-api-film-grain-adjust,
fate-filter-film-grain-adjust) pass unchanged after the avpriv rename.
patcheck exits clean (only the known false-positive classes also
present in the adjust series) and make fate-source passes.
## Examples
Halve the grain amplitude of a source carrying film grain parameters
and synthesise the adjusted parameters into the pixels
(decode -> adjust -> apply -> encode):
ffmpeg -c:v libdav1d -export_side_data +film_grain -i master.mkv \
-vf film_grain_adjust=scale=0.5,film_grain_apply -c:v libx264 out.mkv
Synthesise the film grain parameters exported by the decoder into the
pixels (stand-alone use):
ffmpeg -c:v libdav1d -export_side_data +film_grain -i master.mkv \
-vf film_grain_apply -c:v libx264 out.mkv
## Limitations
This filter synthesises AV1 film grain parameters only (v1 is
AV1-only); H.274 film grain synthesis is the decoder's responsibility,
so a frame whose selection resolves to an H.274 parameter set (or to no
usable set at all) is passed through unchanged, with its side data
intact.
A decoder that synthesises film grain into the decoded picture must
keep that synthesis disabled when its parameters are exported as side
data for this filter: the picture would already contain the grain, and
synthesising the exported parameters on top of it would add a second
layer of grain. The libdav1d decoder disables its film grain synthesis
by default when film grain side data is exported; keep the deprecated
filmgrain option of libdav1d at its default when using this filter.
From d3b820336ac68c14633f4239833b06c7309c2664 Mon Sep 17 00:00:00 2001
From: luoye-cpu <[email protected]>
Date: Sun, 8 Nov 2026 23:32:37 +0800
Subject: [PATCH 1/2] avfilter: add film_grain_adjust filter
FFmpeg can produce AV1 film grain synthesis parameters as
AV_FRAME_DATA_FILM_GRAIN_PARAMS frame side data (native av1, libdav1d and
qsvdec, gated by AV_CODEC_EXPORT_DATA_FILM_GRAIN), it can consume them
(libplacebo synthesises them for display), and the sidedata filter can
delete such an entry wholesale. What it cannot do is modify the
parameters in flight: nothing between a decoder and the next stage of a
pipeline can rescale the grain amplitude or override individual fields.
The natural workflow "decode a grain-carrying master, dial the grain
down or up, feed the modified parameters to an encoder that consumes
film grain side data" is therefore not expressible today; re-encoding
through an analysis-based encoder re-estimates grain from scratch and
loses the authoring intent of the source.
Add the film_grain_adjust video filter to close that gap. The filter
layer (rather than a decoder option or a bitstream filter) is the
natural place for this: film grain parameters are a per-frame side data
property, the filter chain is the generic place where per-frame
properties can be rewritten between arbitrary sources and sinks, and a
bitstream filter operates on encoded bitstream units, not on frame side
data.
The filter is a pixel pass-through: it never touches picture data, it
only adjusts the film grain side data of each frame and forwards the
frame unchanged. Side data buffers are refcounted and shared between
frames referencing each other: av_frame_ref() and
av_frame_side_data_clone() only take an additional reference to the same
underlying AVBufferRef, and av_frame_make_writable() only covers the
picture buffers, not side data. A frame may carry several film grain
parameter sets as multiple AV_FRAME_DATA_FILM_GRAIN_PARAMS entries; every
AV1 set on the frame is adjusted. The filter therefore makes each
adjusted side data entry's buffer writable with av_buffer_make_writable()
before adjusting the parameters -- a no-op when the frame holds the only
reference, a copy-on-write otherwise -- so other frames sharing the
buffer are never affected. Because it does not read pixels it works the
same on hardware frames (e.g. cuda, qsv), which is the typical path for
this workflow.
The filter declares AVFILTER_FLAG_METADATA_ONLY (it never touches
picture data) and FF_FILTER_FLAG_DYNAMIC_FRAME_PARAMS: it carries no
frame parameter state and never accesses pixel data based on the size or
format of its input link, so frames changing size or format after the
graph was configured pass through unharmed (same class of filters as
marked in 58892c922e).
15 options are exposed: overall and chroma-only amplitude scales
('scale', 'chroma_scale') plus overrides for chroma_scaling_from_luma,
overlap_flag, limit_output_range, scaling_shift, ar_coeff_shift,
grain_scale_shift and the cb/cr scaling-function coefficients (cb_mult,
cr_mult, cb_luma_mult, cr_luma_mult, cb_offset, cr_offset). Overrides
use sentinels one below each field's valid range (-1, -129, -257) to
mean "keep the source value", so the help output shows a tight range per
option. The chroma scaling-function coefficients are only applied when
chroma_scaling_from_luma is zero and the corresponding plane has chroma
scaling points, mirroring the AV1 bitstream syntax where they are only
transmitted in that case. All options are runtime
parameters and can be changed through process_command while the filter
is running. Out-of-bitstream-range values of scaling_shift and
ar_coeff_shift are rejected explicitly with EINVAL in init() and
process_command() instead of being silently clipped, and the
end-of-stream summary is only logged when verbose is set.
The point scaling values (point_y_scaling / point_uv_scaling) are 8-bit
amplitude multipliers in the AV1 bitstream (u(8)); the effective grain
amplitude is this value times the generated grain, right-shifted by
scaling_shift (see add_noise_to_block() in libaom's grain_synthesis.c).
libaom, dav1d and the hardware APIs use the value verbatim, so the only
hard limit is the field width: amplitude scaling clamps to 0..255, the
scale/chroma_scale option range is capped at 255.0 (a factor of 255
saturates every non-zero source point) and scale=1.0 is a bit-exact
identity.
This is independent of, and complementary to, work on the production
side (e.g. exporting film grain side data from nvdec_av1): the filter
operates on whatever AV_FRAME_DATA_FILM_GRAIN_PARAMS entry a decoder
exports and passes it to whatever consumes it downstream. The chroma
subsampling av1dec exports for CUDA frames has been corrected in
3c1aad218f8b ("avcodec/av1dec: use sw_pix_fmt for film grain
subsampling"), so the side data this filter reads is consistent on that
path as well.
Review rework after the first Forgejo_Fairy review round: runtime
commands now accept the full AVOption expression syntax (scale=1/2,
scaling_shift=8+1) and a NULL argument returns EINVAL instead of
crashing (the private context is saved, ff_filter_process_command()
runs, init() re-validates and a rejected command restores the saved
copy); the seven clipping calls use av_clip_uintp2()/av_clip_intp2()
(fixes the fate-source CI failure); the FATE filter test selects
without the lavfi input device; the manual and the filter introduction
point at libplacebo=apply_filmgrain=1 for grain synthesis before
encoding since no encoder consumes film grain side data yet;
chroma_scale is documented as ineffective on luma-derived chroma
(chroma_scaling_from_luma=1); the API test prints the observed
parameters, preservation/isolation results and command outcomes
against a new FATE reference file instead of hard-coded checks and now
also covers luma-derived chroma, multi-set resolution ranking and
payload-level copy-on-write; the scaling_shift documentation names the
encoded field correctly (grain_scaling_minus_8 + 8, ar_coeff_shift =
ar_coeff_shift_minus_6 + 6) and the filter has a Changelog entry.
Signed-off-by: luoye-cpu <[email protected]>
---
Changelog | 1 +
doc/filters.texi | 176 ++++++++
libavfilter/Makefile | 1 +
libavfilter/allfilters.c | 1 +
libavfilter/version.h | 2 +-
libavfilter/vf_film_grain_adjust.c | 366 ++++++++++++++++
tests/api/Makefile | 1 +
tests/api/api-film-grain-adjust-test.c | 547 ++++++++++++++++++++++++
tests/fate/api.mak | 5 +
tests/fate/filter-video.mak | 3 +
tests/ref/fate/api-film-grain-adjust | 35 ++
tests/ref/fate/filter-film-grain-adjust | 30 ++
12 files changed, 1167 insertions(+), 1 deletion(-)
create mode 100644 libavfilter/vf_film_grain_adjust.c
create mode 100644 tests/api/api-film-grain-adjust-test.c
create mode 100644 tests/ref/fate/api-film-grain-adjust
create mode 100644 tests/ref/fate/filter-film-grain-adjust
diff --git a/Changelog b/Changelog
index bce79b181f7..c627a42f1cf 100644
--- a/Changelog
+++ b/Changelog
@@ -6,6 +6,7 @@ version <next>:
- LCEVC raw demuxer and muxer
- AVS+ (AVS1-P16, Broadcasting profile) support in the Chinese AVS decoder
- PCM PAMF decoder
+- film_grain_adjust filter
version 9.1:
- ASTC image encoding and decoding via libastcenc, with .astc and KTX 1.0
muxers and demuxers
diff --git a/doc/filters.texi b/doc/filters.texi
index ec23628067a..223af69257a 100644
--- a/doc/filters.texi
+++ b/doc/filters.texi
@@ -14640,6 +14640,182 @@ The command accepts the same syntax of the
corresponding option.
If the specified expression is not valid, it is kept at its current
value.
+@section film_grain_adjust
+
+Rewrite the AV1 film grain synthesis parameters carried on each frame as
+@code{AV_FRAME_DATA_FILM_GRAIN_PARAMS} side data, without touching the
+picture data.
+
+The filter is a pixel pass-through: it never reads or modifies the picture,
+it only adjusts the film grain side data of each frame and forwards the
+frame unchanged, making the buffer of each adjusted side data entry
+writable before adjusting it so that other frames sharing the buffer are
+unaffected. It therefore also works on hardware frames (e.g. @code{cuda},
+@code{qsv}).
+
+A frame may carry several film grain parameter sets as multiple
+@code{AV_FRAME_DATA_FILM_GRAIN_PARAMS} side data entries (alternative
+parameter sets for different video signal characteristics). All AV1 film
+grain parameter sets on the frame are adjusted independently, and each
+set's buffer is made writable individually; parameter sets of other types
+(e.g. H.274) and all other side data are passed through unchanged.
+
+This enables the "decode, adjust, encode" route: a decoder that exports film
+grain side data (e.g. via @code{-export_side_data +film_grain}) provides the
+source parameters, this filter rescales or overrides individual fields, and
+a downstream consumer can use the modified parameters. The
+@ref{libplacebo} filter can synthesise them into picture data before
+encoding; direct encoder consumption requires separate encoder support.
+
+The chroma scaling-function coefficients (@option{cb_mult}, @option{cr_mult},
+@option{cb_luma_mult}, @option{cr_luma_mult}, @option{cb_offset},
+@option{cr_offset}) are only applied when @code{chroma_scaling_from_luma} is
+zero and the corresponding plane actually has chroma scaling points
+(@code{num_uv_points} greater than zero), mirroring the AV1 bitstream syntax
+where they are only transmitted in that case. When a plane has no scaling
+points its coefficients were not transmitted, and the overrides are not
+applied to that plane instead of being presented as valid results.
+
+Note that overriding @option{chroma_scaling_from_luma} from one to zero has
+limited effect when the chroma scaling function was derived from luma:
+source parameters with @code{chroma_scaling_from_luma} set do not contain
+independent chroma scaling points, overriding the flag to zero does not
+create those points, and clearing the flag only means the chroma scaling
+functions are no longer derived from luma. This filter provides no
+capability to create or rebuild chroma scaling points.
+
+This filter only modifies frame side data and never touches picture data;
+it can therefore be inserted anywhere in a filter graph without affecting
+the pixel output.
+
+This filter accepts the following options:
+
+@table @option
+@item scale
+Scales the luma point amplitudes: every luma point scaling value is
+multiplied by this factor. Independent chroma point amplitudes use
+@option{chroma_scale} instead, which follows @option{scale} when negative;
+luma-derived chroma follows the luma curve. 1.0 keeps the source values
+unchanged, @code{0.0} zeroes the luma amplitudes, values greater than 1
+amplify up to the 8-bit field limit. The point scaling values are 8-bit, so
+a factor of 255.0 saturates every non-zero source point and larger factors
+have no additional effect. Default is @var{1.0}.
+
+@item chroma_scale
+Chroma-only amplitude scale, multiplied onto every chroma point scaling
+value. A negative value follows @option{scale}. Default is @var{-1}.
+
+This option only affects parameter sets with independent chroma scaling
+points: decoder-exported sets with @code{chroma_scaling_from_luma} enabled
+carry no independent chroma scaling points, the chroma curve follows the
+(already scaled) luma curve and @option{chroma_scale} is silently
+ineffective for them. Disabling chroma grain for such sets requires
+@option{chroma_scale=0} combined with @option{chroma_scaling_from_luma=0}.
+
+@item chroma_scaling_from_luma
+Override the chroma_scaling_from_luma flag. -1 keeps the source value.
+Default is @var{-1}.
+
+Enabling this flag retains independent chroma point counts and positions.
+Their amplitudes are still adjusted by @option{chroma_scale}, or by
+@option{scale} when @option{chroma_scale} is negative. These stored points
+do not affect synthesis while the flag is set; synthesis uses the scaled
+luma curve. If the flag is subsequently cleared on these parameters, the
+adjusted independent points become active. Runtime commands affect
+subsequent frames only; adjusting one output frame does not change the
+independent points carried by later source frames.
+
+@item overlap_flag
+Override the grain block overlap flag. -1 keeps the source value.
+Default is @var{-1}.
+
+@item limit_output_range
+Override the clip_to_restricted_range flag. -1 keeps the source value.
+Default is @var{-1}.
+
+@item scaling_shift
+Override scaling_shift (grain_scaling_minus_8 + 8), valid range 8..11.
+-1 keeps the source value. Values inside the option range but outside the
+valid range are rejected. Default is @var{-1}.
+
+@item ar_coeff_shift
+Override ar_coeff_shift (ar_coeff_shift_minus_6 + 6), valid range 6..9.
+-1 keeps the source value. Values inside the option range but outside the
+valid range are rejected. Default is @var{-1}.
+
+@item grain_scale_shift
+Override grain_scale_shift, valid range 0..3. -1 keeps the source value.
+Default is @var{-1}.
+
+@item cb_mult
+Override cb_mult, valid range -128..127. -129 keeps the source value.
+Only applied when chroma_scaling_from_luma is zero and Cb has scaling
+points. Default is @var{-129}.
+
+@item cr_mult
+Override cr_mult, valid range -128..127. -129 keeps the source value.
+Only applied when chroma_scaling_from_luma is zero and Cr has scaling
+points. Default is @var{-129}.
+
+@item cb_luma_mult
+Override cb_luma_mult, valid range -128..127. -129 keeps the source value.
+Only applied when chroma_scaling_from_luma is zero and Cb has scaling
+points. Default is @var{-129}.
+
+@item cr_luma_mult
+Override cr_luma_mult, valid range -128..127. -129 keeps the source value.
+Only applied when chroma_scaling_from_luma is zero and Cr has scaling
+points. Default is @var{-129}.
+
+@item cb_offset
+Override cb_offset, valid range -256..255. -257 keeps the source value.
+Only applied when chroma_scaling_from_luma is zero and Cb has scaling
+points. Default is @var{-257}.
+
+@item cr_offset
+Override cr_offset, valid range -256..255. -257 keeps the source value.
+Only applied when chroma_scaling_from_luma is zero and Cr has scaling
+points. Default is @var{-257}.
+
+@item verbose
+Log the parameters of the first adjusted frame and a per-stream summary
+when the filter is closed. When several film grain parameter sets are
+present on that frame, the parameters of the set selected by
+@code{av_film_grain_params_select()}, i.e. the set a film grain synthesiser
+would consume, are logged. If selection returns no AV1 set, the parameters
+of the first adjusted AV1 set are logged instead. Default is disabled.
+@end table
+
+@subsection Commands
+This filter supports the same @ref{commands} as options.
+The command accepts the same syntax of the corresponding option.
+
+Note that currently no FFmpeg encoder consumes film grain side data; the
+@ref{libplacebo} filter can consume the adjusted side data and synthesise the
+grain into the pixels. Once an encoder that consumes film grain side data
+exists, this filter can be placed directly in front of it instead.
+
+@subsection Examples
+
+@itemize
+@item
+Halve the grain amplitude of a source carrying film grain parameters and
+synthesise the adjusted grain into the pixels:
+@example
+ffmpeg -c:v libdav1d -export_side_data +film_grain -i master.mkv \
+ -vf film_grain_adjust=scale=0.5,libplacebo=apply_filmgrain=1 -c:v
libx264 out.mkv
+@end example
+
+@item
+Disable chroma grain and grain block overlap:
+@example
+ffmpeg -c:v libdav1d -export_side_data +film_grain -i master.mkv \
+ -vf
film_grain_adjust=chroma_scale=0:chroma_scaling_from_luma=0:overlap_flag=0,libplacebo=apply_filmgrain=1
\
+ -c:v libx264 out.mkv
+@end example
+
+@end itemize
+
@section find_rect
Find a rectangular object in the input video.
diff --git a/libavfilter/Makefile b/libavfilter/Makefile
index dc5c083f013..a196cc1bb5d 100644
--- a/libavfilter/Makefile
+++ b/libavfilter/Makefile
@@ -321,6 +321,7 @@ OBJS-$(CONFIG_FIELDHINT_FILTER) +=
vf_fieldhint.o
OBJS-$(CONFIG_FIELDMATCH_FILTER) += vf_fieldmatch.o
OBJS-$(CONFIG_FIELDORDER_FILTER) += vf_fieldorder.o
OBJS-$(CONFIG_FILLBORDERS_FILTER) += vf_fillborders.o
+OBJS-$(CONFIG_FILM_GRAIN_ADJUST_FILTER) += vf_film_grain_adjust.o
OBJS-$(CONFIG_FIND_RECT_FILTER) += vf_find_rect.o lavfutils.o
OBJS-$(CONFIG_FLIP_VULKAN_FILTER) += vf_flip_vulkan.o vulkan.o
vulkan_filter.o
OBJS-$(CONFIG_FLOODFILL_FILTER) += vf_floodfill.o
diff --git a/libavfilter/allfilters.c b/libavfilter/allfilters.c
index 9f07bf83dce..4a44ca9c90f 100644
--- a/libavfilter/allfilters.c
+++ b/libavfilter/allfilters.c
@@ -293,6 +293,7 @@ extern const FFFilter ff_vf_fieldhint;
extern const FFFilter ff_vf_fieldmatch;
extern const FFFilter ff_vf_fieldorder;
extern const FFFilter ff_vf_fillborders;
+extern const FFFilter ff_vf_film_grain_adjust;
extern const FFFilter ff_vf_find_rect;
extern const FFFilter ff_vf_flip_vulkan;
extern const FFFilter ff_vf_floodfill;
diff --git a/libavfilter/version.h b/libavfilter/version.h
index 64cd692ab67..537df129cd3 100644
--- a/libavfilter/version.h
+++ b/libavfilter/version.h
@@ -31,7 +31,7 @@
#include "version_major.h"
-#define LIBAVFILTER_VERSION_MINOR 12
+#define LIBAVFILTER_VERSION_MINOR 13
#define LIBAVFILTER_VERSION_MICRO 100
diff --git a/libavfilter/vf_film_grain_adjust.c
b/libavfilter/vf_film_grain_adjust.c
new file mode 100644
index 00000000000..2613924e53f
--- /dev/null
+++ b/libavfilter/vf_film_grain_adjust.c
@@ -0,0 +1,366 @@
+/*
+ * Film grain synthesis parameter adjustment filter (AV1)
+ *
+ * Adjusts the AV1 film grain synthesis parameters carried on each frame as
+ * AV_FRAME_DATA_FILM_GRAIN_PARAMS side data. A frame may carry several film
+ * grain parameter sets as multiple side data entries of that type (see
+ * libavutil/frame.h); every AV1 parameter set on the frame is adjusted,
+ * parameter sets of other types pass through untouched. This enables the
+ * "decode -> modify grain params -> encode" route: a decoder (libdav1d /
+ * native av1 / NVDEC / QSV) exports the source grain parameters, this filter
+ * rewrites them, and a downstream consumer such as libplacebo synthesises
+ * grain from the modified parameters.
+ *
+ * The filter is a pixel pass-through: it does not touch picture data, it only
+ * edits the grain parameters in the side data of each frame and forwards the
+ * frame unchanged.
+ *
+ * Copyright (c) 2026
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include <math.h>
+
+#include "libavutil/common.h"
+#include "libavutil/film_grain_params.h"
+#include "libavutil/opt.h"
+
+#include "avfilter.h"
+#include "filters.h"
+#include "video.h"
+
+/* "keep source value" sentinels. Each is one below the field's valid range so
+ * that -h film_grain_adjust shows a tight, meaningful range per option. */
+#define KEEP_MUL (-129) /* uv_mult / uv_mult_luma: valid [-128, 127] */
+#define KEEP_OFFSET (-257) /* uv_offset: valid [-256, 255] */
+
+typedef struct FilmGrainAdjustContext {
+ const AVClass *class;
+
+ /* amplitude */
+ double scale;
+ double chroma_scale;
+
+ /* overrides, negative / sentinel = keep source value */
+ int chroma_scaling_from_luma;
+ int overlap_flag;
+ int limit_output_range;
+ int scaling_shift;
+ int ar_coeff_shift;
+ int grain_scale_shift;
+ int cb_mult;
+ int cr_mult;
+ int cb_luma_mult;
+ int cr_luma_mult;
+ int cb_offset;
+ int cr_offset;
+
+ int verbose;
+ int logged;
+ int64_t frames;
+ int64_t frames_adjusted;
+ int64_t frames_nograin;
+ int64_t frames_other;
+} FilmGrainAdjustContext;
+
+static uint8_t scale_point(uint8_t v, double f)
+{
+ /* point scaling is an 8-bit amplitude multiplier (AV1 spec: u(8)); the
+ * effective grain amplitude is this value times the generated grain,
+ * right-shifted by scaling_shift (libaom: add_noise_to_block()). It is
+ * used verbatim by libaom, dav1d and the hardware APIs, so the only
+ * hard limit is the field width. */
+ return av_clip((int)lrint(v * f), 0, UINT8_MAX);
+}
+
+static void adjust_aom(AVFilmGrainAOMParams *a, const FilmGrainAdjustContext
*s)
+{
+ const double cs = (s->chroma_scale >= 0.0) ? s->chroma_scale : s->scale;
+ int c, i;
+
+ a->num_y_points = av_clip(a->num_y_points, 0, FF_ARRAY_ELEMS(a->y_points));
+ for (i = 0; i < a->num_y_points; i++)
+ a->y_points[i][1] = scale_point(a->y_points[i][1], s->scale);
+
+ /* chroma_scale scales the stored chroma points regardless of
+ * chroma_scaling_from_luma: with the flag set the stored points stay
+ * inactive (the synthesiser derives the chroma curve from the (already
+ * scaled) luma curve) and the adjusted points take effect again if the
+ * flag is cleared. Decoder-exported sets with the flag set carry no
+ * independent chroma points, so disabling chroma grain for those
+ * requires chroma_scale=0 combined with chroma_scaling_from_luma=0 */
+ for (c = 0; c < 2; c++) {
+ a->num_uv_points[c] = av_clip(a->num_uv_points[c], 0,
FF_ARRAY_ELEMS(a->uv_points[c]));
+ for (i = 0; i < a->num_uv_points[c]; i++)
+ a->uv_points[c][i][1] = scale_point(a->uv_points[c][i][1], cs);
+ }
+
+ if (s->chroma_scaling_from_luma >= 0)
+ a->chroma_scaling_from_luma = s->chroma_scaling_from_luma & 1;
+ if (s->overlap_flag >= 0)
+ a->overlap_flag = s->overlap_flag & 1;
+ if (s->limit_output_range >= 0)
+ a->limit_output_range = s->limit_output_range & 1;
+ /* the shift values have been validated in init() / process_command(),
+ * the clips below are a defensive no-op for valid input */
+ if (s->scaling_shift >= 0)
+ a->scaling_shift = av_clip(s->scaling_shift, 8, 11);
+ if (s->ar_coeff_shift >= 0)
+ a->ar_coeff_shift = av_clip(s->ar_coeff_shift, 6, 9);
+ if (s->grain_scale_shift >= 0)
+ a->grain_scale_shift = av_clip_uintp2(s->grain_scale_shift, 2);
+
+ /* chroma scaling-function coefficients are only present when the chroma
+ * scaling function is not derived from luma AND the corresponding plane
+ * actually has chroma scaling points: when num_uv_points[c] is zero the
+ * coefficients were not transmitted in the bitstream for that plane, so
+ * the overrides must not be presented as valid results for it */
+ if (!a->chroma_scaling_from_luma) {
+ if (a->num_uv_points[0]) {
+ if (s->cb_mult != KEEP_MUL) a->uv_mult[0] =
av_clip_intp2(s->cb_mult, 7);
+ if (s->cb_luma_mult != KEEP_MUL) a->uv_mult_luma[0] =
av_clip_intp2(s->cb_luma_mult, 7);
+ if (s->cb_offset != KEEP_OFFSET) a->uv_offset[0] =
av_clip_intp2(s->cb_offset, 8);
+ }
+ if (a->num_uv_points[1]) {
+ if (s->cr_mult != KEEP_MUL) a->uv_mult[1] =
av_clip_intp2(s->cr_mult, 7);
+ if (s->cr_luma_mult != KEEP_MUL) a->uv_mult_luma[1] =
av_clip_intp2(s->cr_luma_mult, 7);
+ if (s->cr_offset != KEEP_OFFSET) a->uv_offset[1] =
av_clip_intp2(s->cr_offset, 8);
+ }
+ }
+}
+
+/* the AVOption ranges of the shift options are deliberately wider than the
+ * values valid in the AV1 bitstream (they include the "keep source value"
+ * sentinel); values inside the AVOption range but outside the bitstream
+ * range are rejected instead of being silently clipped to the valid range */
+static int check_shift_opt(void *logctx, const char *name, long v,
+ int valid_min, int valid_max)
+{
+ if (v == -1 || (v >= valid_min && v <= valid_max))
+ return 0;
+ av_log(logctx, AV_LOG_ERROR,
+ "Invalid %s value %ld: must be -1 (keep source value) or %d..%d\n",
+ name, v, valid_min, valid_max);
+ return AVERROR(EINVAL);
+}
+
+static av_cold int init(AVFilterContext *ctx)
+{
+ FilmGrainAdjustContext *s = ctx->priv;
+ int ret;
+
+ /* non-finite factors must never reach lrint() in scale_point() */
+ if (!isfinite(s->scale) || !isfinite(s->chroma_scale)) {
+ av_log(ctx, AV_LOG_ERROR,
+ "scale and chroma_scale must be finite numbers\n");
+ return AVERROR(EINVAL);
+ }
+
+ ret = check_shift_opt(ctx, "scaling_shift", s->scaling_shift, 8, 11);
+ if (ret < 0)
+ return ret;
+ ret = check_shift_opt(ctx, "ar_coeff_shift", s->ar_coeff_shift, 6, 9);
+ if (ret < 0)
+ return ret;
+
+ return 0;
+}
+
+static int process_command(AVFilterContext *ctx, const char *cmd, const char
*arg,
+ char *res, int res_len, int flags)
+{
+ FilmGrainAdjustContext *s = ctx->priv;
+ const FilmGrainAdjustContext saved = *s;
+ int ret = ff_filter_process_command(ctx, cmd, arg, res, res_len, flags);
+
+ /* Re-validate the updated options with the init() checks. The context
+ * owns no allocations, so restoring the saved copy fully reverts a
+ * rejected command. This also accepts the full AVOption expression
+ * syntax (e.g. "scale=1/2", "scaling_shift=8+1") and turns a NULL
+ * argument into an EINVAL rejection via the option setter. */
+ if (ret >= 0)
+ ret = init(ctx);
+ if (ret < 0)
+ *s = saved;
+ return ret;
+}
+
+static int filter_frame(AVFilterLink *inlink, AVFrame *in)
+{
+ AVFilterContext *ctx = inlink->dst;
+ AVFilterLink *outlink = ctx->outputs[0];
+ FilmGrainAdjustContext *s = ctx->priv;
+ AVFilmGrainParams *first_adjusted = NULL;
+ int n_valid = 0; /* well-formed film grain side data entries */
+ int n_adjusted = 0; /* AV1 entries adjusted */
+ int ret;
+
+ s->frames++;
+
+ /* AV_FRAME_DATA_FILM_GRAIN_PARAMS may be present multiple times on a
+ * single frame, carrying alternative parameter sets (see
+ * libavutil/frame.h). Every AV1 parameter set is adjusted; sets of other
+ * types (e.g. H.274) pass through untouched. Only the buffer of an
+ * existing entry is ever replaced below, the side data array itself is
+ * not resized or reordered, so iterating over in->side_data[] is safe
+ * while entries are adjusted. */
+ for (int i = 0; i < in->nb_side_data; i++) {
+ AVFrameSideData *sd = in->side_data[i];
+ AVFilmGrainParams *fgp;
+
+ if (sd->type != AV_FRAME_DATA_FILM_GRAIN_PARAMS)
+ continue;
+ if (sd->size < sizeof(AVFilmGrainParams))
+ continue; /* malformed entry, treat like missing side data */
+
+ n_valid++;
+ fgp = (AVFilmGrainParams *)sd->data;
+ if (fgp->type != AV_FILM_GRAIN_PARAMS_AV1)
+ continue;
+
+ /* Side data buffers are refcounted and shared between frames that
+ * reference each other: av_frame_ref() and
+ * av_frame_side_data_clone() only take an additional reference to
+ * the same underlying AVBufferRef. Modifying the parameters in
+ * place would therefore leak into every other frame sharing that
+ * buffer, and av_frame_make_writable() only covers the picture
+ * buffers, not side data. Copy-on-write the side data buffer of
+ * each entry independently (a no-op when this frame holds the only
+ * reference). */
+ if (!av_buffer_is_writable(sd->buf)) {
+ ret = av_buffer_make_writable(&sd->buf);
+ if (ret < 0) {
+ av_frame_free(&in);
+ return ret;
+ }
+ /* the buffer may have been replaced, re-point the payload */
+ sd->data = sd->buf->data;
+ fgp = (AVFilmGrainParams *)sd->data;
+ }
+
+ adjust_aom(&fgp->codec.aom, s);
+ if (!first_adjusted)
+ first_adjusted = fgp;
+ n_adjusted++;
+ }
+
+ /* frame-level accounting: each frame is counted exactly once, no matter
+ * how many parameter sets it carries */
+ if (!n_valid) {
+ s->frames_nograin++;
+ } else if (n_adjusted) {
+ s->frames_adjusted++;
+ } else {
+ s->frames_other++;
+ }
+
+ if (s->verbose && !s->logged && n_adjusted) {
+ /* when several sets are present, report the one that
+ * av_film_grain_params_select() picks, i.e. the set a film grain
+ * synthesiser would actually consume; fall back to the first
+ * adjusted set if select() prefers a non-AV1 entry */
+ const AVFilmGrainParams *logp = av_film_grain_params_select(in);
+
+ if (!logp || logp->type != AV_FILM_GRAIN_PARAMS_AV1)
+ logp = first_adjusted;
+ av_log(ctx, AV_LOG_INFO,
+ "film_grain_adjust: first adjusted frame: "
+ "num_y_points=%d num_uv_points=%d/%d ar_coeff_lag=%d "
+ "scaling_shift=%d scale=%.3f chroma_scale=%.3f\n",
+ logp->codec.aom.num_y_points,
+ logp->codec.aom.num_uv_points[0],
logp->codec.aom.num_uv_points[1],
+ logp->codec.aom.ar_coeff_lag, logp->codec.aom.scaling_shift,
+ s->scale, s->chroma_scale);
+ s->logged = 1;
+ }
+
+ return ff_filter_frame(outlink, in);
+}
+
+static av_cold void uninit(AVFilterContext *ctx)
+{
+ FilmGrainAdjustContext *s = ctx->priv;
+
+ if (s->verbose)
+ av_log(ctx, AV_LOG_INFO,
+ "film_grain_adjust: frames=%"PRId64" adjusted=%"PRId64
+ " no_grain=%"PRId64" other_type=%"PRId64"\n",
+ s->frames, s->frames_adjusted, s->frames_nograin,
s->frames_other);
+}
+
+#define OFFSET(x) offsetof(FilmGrainAdjustContext, x)
+#define VF AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_FILTERING_PARAM |
AV_OPT_FLAG_RUNTIME_PARAM
+
+static const AVOption film_grain_adjust_options[] = {
+ { "scale", "luma amplitude scale: multiplies the luma point amplitudes,
independent chroma points use chroma_scale (1.0 = unchanged, 0.0 = zero luma
amplitude, >1 amplifies up to the 8-bit field limit)",
+ OFFSET(scale), AV_OPT_TYPE_DOUBLE, {.dbl=1.0}, 0.0, 255.0, VF },
+ { "chroma_scale", "chroma-only amplitude scale; negative = follow 'scale';
stored chroma amplitudes stay adjustable even when chroma_scaling_from_luma=1,
but such sets synthesize chroma from the luma curve",
+ OFFSET(chroma_scale), AV_OPT_TYPE_DOUBLE, {.dbl=-1.0}, -1.0, 255.0, VF },
+ { "chroma_scaling_from_luma", "override chroma_scaling_from_luma (-1 =
keep)",
+ OFFSET(chroma_scaling_from_luma), AV_OPT_TYPE_INT, {.i64=-1}, -1, 1, VF
},
+ { "overlap_flag", "override overlap_flag (-1 = keep)",
+ OFFSET(overlap_flag), AV_OPT_TYPE_INT, {.i64=-1}, -1, 1, VF },
+ { "limit_output_range", "override clip_to_restricted_range (-1 = keep)",
+ OFFSET(limit_output_range), AV_OPT_TYPE_INT, {.i64=-1}, -1, 1, VF },
+ { "scaling_shift", "override scaling_shift (grain_scaling_minus_8 + 8),
valid 8..11 (-1 = keep, other values rejected)",
+ OFFSET(scaling_shift), AV_OPT_TYPE_INT, {.i64=-1}, -1, 11, VF },
+ { "ar_coeff_shift", "override ar_coeff_shift (ar_coeff_shift_minus_6 + 6),
valid 6..9 (-1 = keep, other values rejected)",
+ OFFSET(ar_coeff_shift), AV_OPT_TYPE_INT, {.i64=-1}, -1, 9, VF },
+ { "grain_scale_shift", "override grain_scale_shift, valid 0..3 (-1 =
keep)",
+ OFFSET(grain_scale_shift), AV_OPT_TYPE_INT, {.i64=-1}, -1, 3, VF },
+ { "cb_mult", "override cb_mult, valid -128..127 (-129 = keep; only when
chroma_scaling_from_luma==0 and Cb has scaling points)",
+ OFFSET(cb_mult), AV_OPT_TYPE_INT, {.i64=KEEP_MUL}, KEEP_MUL, 127, VF },
+ { "cr_mult", "override cr_mult, valid -128..127 (-129 = keep; only when
chroma_scaling_from_luma==0 and Cr has scaling points)",
+ OFFSET(cr_mult), AV_OPT_TYPE_INT, {.i64=KEEP_MUL}, KEEP_MUL, 127, VF },
+ { "cb_luma_mult", "override cb_luma_mult, valid -128..127 (-129 = keep;
only when chroma_scaling_from_luma==0 and Cb has scaling points)",
+ OFFSET(cb_luma_mult), AV_OPT_TYPE_INT, {.i64=KEEP_MUL}, KEEP_MUL, 127,
VF },
+ { "cr_luma_mult", "override cr_luma_mult, valid -128..127 (-129 = keep;
only when chroma_scaling_from_luma==0 and Cr has scaling points)",
+ OFFSET(cr_luma_mult), AV_OPT_TYPE_INT, {.i64=KEEP_MUL}, KEEP_MUL, 127,
VF },
+ { "cb_offset", "override cb_offset, valid -256..255 (-257 = keep; only
when chroma_scaling_from_luma==0 and Cb has scaling points)",
+ OFFSET(cb_offset), AV_OPT_TYPE_INT, {.i64=KEEP_OFFSET}, KEEP_OFFSET,
255, VF },
+ { "cr_offset", "override cr_offset, valid -256..255 (-257 = keep; only
when chroma_scaling_from_luma==0 and Cr has scaling points)",
+ OFFSET(cr_offset), AV_OPT_TYPE_INT, {.i64=KEEP_OFFSET}, KEEP_OFFSET,
255, VF },
+ { "verbose", "log the first adjusted frame's parameters (the set
av_film_grain_params_select() picks when several are present, or the first
adjusted set if selection returns no AV1 set) and a summary at exit",
+ OFFSET(verbose), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, VF },
+ { NULL }
+};
+
+static const AVFilterPad inputs[] = {
+ {
+ .name = "default",
+ .type = AVMEDIA_TYPE_VIDEO,
+ .filter_frame = filter_frame,
+ },
+};
+
+AVFILTER_DEFINE_CLASS(film_grain_adjust);
+
+const FFFilter ff_vf_film_grain_adjust = {
+ .p.name = "film_grain_adjust",
+ .p.description = NULL_IF_CONFIG_SMALL("Adjust AV1 film grain synthesis
parameters carried as frame side data."),
+ .p.priv_class = &film_grain_adjust_class,
+ .p.flags = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC |
+ AVFILTER_FLAG_METADATA_ONLY,
+ .priv_size = sizeof(FilmGrainAdjustContext),
+ .init = init,
+ .uninit = uninit,
+ FILTER_OUTPUTS(ff_video_default_filterpad),
+ FILTER_INPUTS(inputs),
+ .process_command = process_command,
+ .flags_internal = FF_FILTER_FLAG_DYNAMIC_FRAME_PARAMS,
+};
diff --git a/tests/api/Makefile b/tests/api/Makefile
index c411e82e5f1..87d899fc852 100644
--- a/tests/api/Makefile
+++ b/tests/api/Makefile
@@ -9,6 +9,7 @@ APITESTPROGS-$(call ALLYES, HEVC_MP4TOANNEXB_BSF HEVC_DECODER)
+= api-hevc-mp4to
APITESTPROGS-yes += api-seek api-dump-stream-meta
APITESTPROGS-$(call DEMDEC, H263, H263) += api-band
APITESTPROGS-$(HAVE_THREADS) += api-threadmessage
+APITESTPROGS-$(CONFIG_FILM_GRAIN_ADJUST_FILTER) += api-film-grain-adjust
APITESTPROGS-$(CONFIG_AVCODEC) += api-enc-info
APITESTPROGS-$(CONFIG_PCM_S16LE_DECODER) += api-skip-samples
APITESTPROGS-$(call ALLYES, H261_ENCODER H261_PARSER) += api-enc-parser
diff --git a/tests/api/api-film-grain-adjust-test.c
b/tests/api/api-film-grain-adjust-test.c
new file mode 100644
index 00000000000..685ecd495e0
--- /dev/null
+++ b/tests/api/api-film-grain-adjust-test.c
@@ -0,0 +1,547 @@
+/*
+ * Copyright (c) 2026
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/*
+ * film_grain_adjust filter API test: prints the observed film grain
+ * parameters, the preservation/isolation results and the runtime command
+ * outcomes; the FATE reference file captures the output. Operational
+ * failures are reported on stderr and exit non-zero.
+ */
+
+#include <inttypes.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "libavfilter/avfilter.h"
+#include "libavfilter/buffersink.h"
+#include "libavfilter/buffersrc.h"
+
+#include "libavutil/dict.h"
+#include "libavutil/film_grain_params.h"
+#include "libavutil/pixfmt.h"
+
+#define WIDTH 64
+#define HEIGHT 64
+
+#define SRC_ARGS "video_size=" AV_STRINGIFY(WIDTH) "x" AV_STRINGIFY(HEIGHT) \
+ ":pix_fmt=yuv420p:time_base=1/25:pixel_aspect=1/1"
+
+static AVFrame *alloc_test_frame(void)
+{
+ AVFrame *f = av_frame_alloc();
+
+ if (!f)
+ return NULL;
+ f->format = AV_PIX_FMT_YUV420P;
+ f->width = WIDTH;
+ f->height = HEIGHT;
+ if (av_frame_get_buffer(f, 0) < 0)
+ av_frame_free(&f);
+ return f;
+}
+
+/* shared graph setup: "buffer -> film_grain_adjust=<args> -> buffersink" */
+static int make_graph(AVFilterGraph **graph, AVFilterContext **src,
+ AVFilterContext **sink, const char *args)
+{
+ AVFilterContext *fga = NULL;
+ int ret;
+
+ if (!avfilter_get_by_name("buffer") ||
+ !avfilter_get_by_name("buffersink") ||
+ !avfilter_get_by_name("film_grain_adjust"))
+ return AVERROR(ENOSYS);
+
+ *graph = avfilter_graph_alloc();
+ if (!*graph)
+ return AVERROR(ENOMEM);
+
+ ret = avfilter_graph_create_filter(src, avfilter_get_by_name("buffer"),
+ "src", SRC_ARGS, NULL, *graph);
+ if (!ret)
+ ret = avfilter_graph_create_filter(&fga,
+
avfilter_get_by_name("film_grain_adjust"),
+ "fga", args, NULL, *graph);
+ if (!ret)
+ ret = avfilter_graph_create_filter(sink,
+ avfilter_get_by_name("buffersink"),
+ "sink", NULL, NULL, *graph);
+ if (!ret)
+ ret = avfilter_link(*src, 0, fga, 0);
+ if (!ret)
+ ret = avfilter_link(fga, 0, *sink, 0);
+ if (!ret)
+ ret = avfilter_graph_config(*graph, NULL);
+
+ if (ret < 0) {
+ avfilter_graph_free(graph);
+ *src = *sink = NULL;
+ }
+ return ret;
+}
+
+/* push one frame through the shared graph setup and return the output */
+static int run_filter(AVFrame *in, AVFrame *out, const char *args)
+{
+ AVFilterGraph *graph = NULL;
+ AVFilterContext *src = NULL, *sink = NULL;
+ int ret = make_graph(&graph, &src, &sink, args);
+
+ if (ret < 0)
+ return ret;
+
+ /* KEEP_REF: the frame handed to the filter chain shares its side data
+ * buffers with the caller's frame, which is the situation the
+ * copy-on-write handling must cope with */
+ ret = av_buffersrc_add_frame_flags(src, in, AV_BUFFERSRC_FLAG_KEEP_REF);
+ if (ret >= 0)
+ ret = av_buffersink_get_frame(sink, out);
+
+ avfilter_graph_free(&graph);
+ return ret;
+}
+
+static int push_frame(AVFilterContext *src, AVFilterContext *sink,
+ AVFrame *in, AVFrame *out)
+{
+ int ret = av_buffersrc_add_frame_flags(src, in,
AV_BUFFERSRC_FLAG_KEEP_REF);
+
+ if (ret >= 0)
+ ret = av_buffersink_get_frame(sink, out);
+ return ret;
+}
+
+static void fill_aom(AVFilmGrainAOMParams *a)
+{
+ *a = (AVFilmGrainAOMParams) {
+ .num_y_points = 3,
+ .y_points = { { 10, 100 }, { 20, 150 }, { 30, 64 } },
+ .chroma_scaling_from_luma = 0,
+ .num_uv_points = { 2, 1 },
+ .uv_points = { { { 40, 40 }, { 60, 80 } }, { { 50, 200 } } },
+ .scaling_shift = 9, .ar_coeff_lag = 2, .ar_coeff_shift = 7,
+ .grain_scale_shift = 1, .uv_mult = { 5, 3 }, .uv_mult_luma = { 2, 4 },
+ .uv_offset = { 15, 25 }, .overlap_flag = 1, .limit_output_range = 0,
+ };
+}
+
+/* attach one AV1 film grain set with the default test values */
+static AVFilmGrainParams *add_aom_entry(AVFrame *f, uint32_t seed)
+{
+ AVFilmGrainParams *p = av_film_grain_params_create_side_data(f);
+
+ if (p) {
+ p->type = AV_FILM_GRAIN_PARAMS_AV1;
+ p->seed = seed;
+ fill_aom(&p->codec.aom);
+ }
+ return p;
+}
+
+/* attach one H.274 film grain set */
+static AVFilmGrainParams *add_h274_entry(AVFrame *f, uint32_t seed)
+{
+ AVFilmGrainParams *p = av_film_grain_params_create_side_data(f);
+
+ if (p) {
+ p->type = AV_FILM_GRAIN_PARAMS_H274;
+ p->seed = seed;
+ p->codec.h274.model_id = 1;
+ p->codec.h274.log2_scale_factor = 2;
+ p->codec.h274.num_model_values[0] = 3;
+ p->codec.h274.comp_model_value[0][0][0] = -100;
+ p->codec.h274.comp_model_value[0][0][1] = 0;
+ p->codec.h274.comp_model_value[0][0][2] = 100;
+ }
+ return p;
+}
+
+/* the frame's film grain side data matches the reference bytes */
+static int entry_matches(const AVFrame *f, const unsigned char *ref)
+{
+ AVFrameSideData *sd = av_frame_get_side_data(f,
AV_FRAME_DATA_FILM_GRAIN_PARAMS);
+
+ return sd && sd->size == sizeof(AVFilmGrainParams) &&
+ !memcmp(sd->data, ref, sizeof(AVFilmGrainParams));
+}
+
+/* payload address of the idx-th film grain side data entry: unlike the
+ * AVBufferRef pointers, equal payload addresses prove shared buffers */
+static const void *fg_payload(const AVFrame *f, int idx)
+{
+ int n = 0;
+
+ for (int i = 0; i < f->nb_side_data; i++)
+ if (f->side_data[i]->type == AV_FRAME_DATA_FILM_GRAIN_PARAMS &&
+ n++ == idx)
+ return f->side_data[i]->data;
+ return NULL;
+}
+
+static void dump_aom(const AVFilmGrainAOMParams *a)
+{
+ printf(" yp:");
+ for (int i = 0; i < a->num_y_points; i++)
+ printf(" %d/%d", a->y_points[i][0], a->y_points[i][1]);
+ printf(" csfl=%d ovl=%d lim=%d ss=%d acs=%d gss=%d lag=%d",
+ a->chroma_scaling_from_luma, a->overlap_flag, a->limit_output_range,
+ a->scaling_shift, a->ar_coeff_shift, a->grain_scale_shift,
+ a->ar_coeff_lag);
+ printf(" cb=%d/%d/%d cr=%d/%d/%d\n", a->uv_mult[0], a->uv_mult_luma[0],
+ a->uv_offset[0], a->uv_mult[1], a->uv_mult_luma[1],
a->uv_offset[1]);
+ printf(" uvp:");
+ for (int c = 0; c < 2; c++)
+ for (int i = 0; i < a->num_uv_points[c]; i++)
+ printf(" c%d %d/%d", c, a->uv_points[c][i][0],
a->uv_points[c][i][1]);
+ printf("\n");
+}
+
+static void dump_entry(const AVFrameSideData *sd)
+{
+ const AVFilmGrainParams *p;
+
+ if (!sd || sd->size != sizeof(AVFilmGrainParams)) {
+ printf(" missing film grain side data\n");
+ return;
+ }
+ p = (const AVFilmGrainParams *)sd->data;
+ printf(" seed=0x%08"PRIX64" type=%s\n", p->seed,
+ p->type == AV_FILM_GRAIN_PARAMS_AV1 ? "AV1" : "other");
+ if (p->type == AV_FILM_GRAIN_PARAMS_AV1)
+ dump_aom(&p->codec.aom);
+}
+
+/* scale + field overrides; frames sharing the side data buffer keep the
+ * original parameters (copy-on-write) */
+static int test_scale_isolation(void)
+{
+ AVFrame *in = NULL, *clone = NULL, *out = NULL;
+ unsigned char ref[sizeof(AVFilmGrainParams)];
+ int ret;
+
+ in = alloc_test_frame();
+ out = av_frame_alloc();
+ if (!in || !out || !add_aom_entry(in, 0x12345678)) {
+ ret = AVERROR(ENOMEM);
+ goto fail;
+ }
+ clone = av_frame_clone(in);
+ if (!clone) {
+ ret = AVERROR(ENOMEM);
+ goto fail;
+ }
+ memcpy(ref, av_frame_get_side_data(in,
AV_FRAME_DATA_FILM_GRAIN_PARAMS)->data,
+ sizeof(AVFilmGrainParams));
+
+ ret = run_filter(in, out,
+ "scale=2.0:chroma_scale=3.0:overlap_flag=0"
+ ":limit_output_range=1:scaling_shift=10"
+ ":ar_coeff_shift=8:cb_mult=10:cb_offset=20");
+ if (ret < 0)
+ goto fail;
+ printf("scale=2.0 chroma_scale=3.0 with overrides:\n");
+ dump_entry(av_frame_get_side_data(out, AV_FRAME_DATA_FILM_GRAIN_PARAMS));
+ printf(" in unchanged=%d clone unchanged=%d\n",
+ entry_matches(in, ref), entry_matches(clone, ref));
+ ret = 0;
+fail:
+ av_frame_free(&out);
+ av_frame_free(&clone);
+ av_frame_free(&in);
+ return ret;
+}
+
+/* chroma_scaling_from_luma=1: the parameters carry no independent chroma
+ * points, so chroma_scale=0 is ineffective (documented limitation) while
+ * scale=0 clears the luma curve the chroma curve is derived from */
+static int test_derived_chroma(void)
+{
+ AVFrame *in = NULL, *out = NULL;
+ AVFilmGrainParams *p;
+ unsigned char ref[sizeof(AVFilmGrainParams)];
+ int ret;
+
+ in = alloc_test_frame();
+ out = av_frame_alloc();
+ p = (in && out) ? add_aom_entry(in, 0x00DEFACE) : NULL;
+ if (!p) {
+ ret = AVERROR(ENOMEM);
+ goto fail;
+ }
+ p->codec.aom.chroma_scaling_from_luma = 1;
+ p->codec.aom.num_uv_points[0] = 0;
+ p->codec.aom.num_uv_points[1] = 0;
+ memcpy(ref, av_frame_get_side_data(in,
AV_FRAME_DATA_FILM_GRAIN_PARAMS)->data,
+ sizeof(AVFilmGrainParams));
+
+ ret = run_filter(in, out, "chroma_scale=0");
+ if (ret < 0)
+ goto fail;
+ printf("csfl=1 chroma_scale=0: unchanged=%d\n", entry_matches(out, ref));
+ av_frame_unref(out);
+
+ ret = run_filter(in, out, "scale=0");
+ if (ret < 0)
+ goto fail;
+ printf("csfl=1 scale=0 (chroma curve follows luma):\n");
+ dump_entry(av_frame_get_side_data(out, AV_FRAME_DATA_FILM_GRAIN_PARAMS));
+ ret = 0;
+fail:
+ av_frame_free(&out);
+ av_frame_free(&in);
+ return ret;
+}
+
+/* frames without grain side data stay without side data */
+static int test_no_side_data(void)
+{
+ AVFrame *in = alloc_test_frame(), *out = av_frame_alloc();
+ int ret;
+
+ if (!in || !out) {
+ ret = AVERROR(ENOMEM);
+ goto fail;
+ }
+
+ ret = run_filter(in, out, "scale=2.0");
+ if (ret < 0)
+ goto fail;
+ printf("no grain side data in: output entry=%d\n",
+ !!av_frame_get_side_data(out, AV_FRAME_DATA_FILM_GRAIN_PARAMS));
+ ret = 0;
+fail:
+ av_frame_free(&out);
+ av_frame_free(&in);
+ return ret;
+}
+
+/* three parameter sets on one frame (two AV1 + one H.274): independent
+ * scaling, bit-exact H.274 pass-through, preserved order/count/metadata,
+ * select() prefers the largest valid AV1 set (set B uses 8-bit depths so
+ * the resolution ranking is exercised, and the two AV1 entries are
+ * swapped before filtering so a keep-first selector would pick the
+ * half-size set instead), and each AV1 entry is copy-on-written into its
+ * own buffer (payload addresses compared) */
+static int test_multiple_sets(void)
+{
+ AVFrame *in = NULL, *clone = NULL, *out = NULL;
+ AVFilmGrainParams *p;
+ unsigned char ref[3][sizeof(AVFilmGrainParams)];
+ const AVFilmGrainParams *sel;
+ AVDictionaryEntry *e;
+ int i, ret;
+
+ in = alloc_test_frame();
+ out = av_frame_alloc();
+ p = (in && out) ? add_aom_entry(in, 0xAAAA0001) : NULL;
+ if (!p) {
+ ret = AVERROR(ENOMEM);
+ goto fail;
+ }
+ /* set A: full declared size */
+ p->width = WIDTH;
+ p->height = HEIGHT;
+ p->subsampling_x = p->subsampling_y = 1;
+ p->codec.aom.num_y_points = 2;
+ p->codec.aom.num_uv_points[1] = 0;
+
+ /* set B: half declared size, 8-bit depths matching the yuv420p frame */
+ p = add_aom_entry(in, 0xBBBB0002);
+ if (!p) {
+ ret = AVERROR(ENOMEM);
+ goto fail;
+ }
+ p->width = WIDTH / 2;
+ p->height = HEIGHT / 2;
+ p->subsampling_x = p->subsampling_y = 1;
+ p->bit_depth_luma = 8;
+ p->bit_depth_chroma = 8;
+ p->color_primaries = AVCOL_PRI_BT709;
+ p->color_trc = AVCOL_TRC_BT709;
+ p->color_space = AVCOL_SPC_BT709;
+ p->color_range = AVCOL_RANGE_MPEG;
+ for (i = 0; i < 3; i++) {
+ p->codec.aom.y_points[i][0] = 30 + 10 * i;
+ p->codec.aom.y_points[i][1] = 50 + 10 * i;
+ }
+ p->codec.aom.uv_points[0][0][0] = 70;
+ p->codec.aom.uv_points[0][0][1] = 70;
+ p->codec.aom.num_uv_points[0] = 1;
+ p->codec.aom.num_uv_points[1] = 0;
+
+ if (!add_h274_entry(in, 0xCCCC0003)) {
+ ret = AVERROR(ENOMEM);
+ goto fail;
+ }
+ av_dict_set(&in->side_data[2]->metadata, "film_grain_adjust_test", "h274",
0);
+ /* swap the two AV1 entries: the full-size set A is no longer first, so
+ * a selector that always keeps the first eligible set would pick the
+ * half-size set B instead and fail the reference */
+ AVFrameSideData *tmp = in->side_data[0];
+ in->side_data[0] = in->side_data[1];
+ in->side_data[1] = tmp;
+ clone = av_frame_clone(in);
+ if (!clone) {
+ ret = AVERROR(ENOMEM);
+ goto fail;
+ }
+ for (i = 0; i < 3; i++)
+ memcpy(ref[i], in->side_data[i]->data, sizeof(AVFilmGrainParams));
+
+ ret = run_filter(in, out, "scale=2.0:chroma_scale=3.0");
+ if (ret < 0)
+ goto fail;
+
+ printf("three-set frame scale=2.0 chroma_scale=3.0: entries=%d\n",
+ out->nb_side_data);
+ for (i = 0; i < out->nb_side_data; i++) {
+ const AVFrameSideData *sd = out->side_data[i];
+ const AVFilmGrainParams *q = (const AVFilmGrainParams *)sd->data;
+
+ dump_entry(sd);
+ if (q->type != AV_FILM_GRAIN_PARAMS_AV1) {
+ e = av_dict_get(sd->metadata, "film_grain_adjust_test", NULL, 0);
+ printf(" bitexact=%d metadata=%s\n",
+ !memcmp(sd->data, ref[i], sizeof(AVFilmGrainParams)),
+ e ? e->value : "(none)");
+ }
+ }
+ sel = av_film_grain_params_select(out);
+ printf(" select: seed=0x%08"PRIX64" y0=%d\n", sel ? sel->seed : 0,
+ sel && sel->type == AV_FILM_GRAIN_PARAMS_AV1 ?
+ sel->codec.aom.y_points[0][1] : -1);
+ printf(" cow payload out0==in0=%d out1==in1=%d out0==out1=%d\n",
+ fg_payload(out, 0) == fg_payload(in, 0),
+ fg_payload(out, 1) == fg_payload(in, 1),
+ fg_payload(out, 0) == fg_payload(out, 1));
+ for (i = 0; i < 3; i++)
+ printf(" set %d in unchanged=%d clone unchanged=%d\n", i,
+ !memcmp(in->side_data[i]->data, ref[i],
sizeof(AVFilmGrainParams)),
+ !memcmp(clone->side_data[i]->data, ref[i],
sizeof(AVFilmGrainParams)));
+ ret = 0;
+fail:
+ av_frame_free(&out);
+ av_frame_free(&clone);
+ av_frame_free(&in);
+ return ret;
+}
+
+/* runtime commands: the full AVOption expression syntax is accepted,
+ * rejected commands leave the previous settings in place and a NULL
+ * argument is rejected by the option setter */
+static int test_runtime_commands(void)
+{
+ AVFilterGraph *graph = NULL;
+ AVFilterContext *src = NULL, *sink = NULL;
+ AVFrame *frames[3] = { NULL, NULL, NULL }, *out = NULL;
+ const AVFilmGrainParams *fgp;
+ AVFrameSideData *sd;
+ int ret, i;
+
+ ret = make_graph(&graph, &src, &sink, "");
+ if (ret < 0)
+ return ret;
+ out = av_frame_alloc();
+ for (i = 0; i < 3; i++) {
+ frames[i] = alloc_test_frame();
+ if (!out || !frames[i] || !add_aom_entry(frames[i], 0x11000000 + i)) {
+ ret = AVERROR(ENOMEM);
+ goto fail;
+ }
+ }
+
+ /* frame 0: default options leave the parameters unchanged */
+ ret = push_frame(src, sink, frames[0], out);
+ if (ret < 0)
+ goto fail;
+ sd = av_frame_get_side_data(out, AV_FRAME_DATA_FILM_GRAIN_PARAMS);
+ fgp = sd ? (const AVFilmGrainParams *)sd->data : NULL;
+ printf("frame 0 (defaults): y0=%d ss=%d\n",
+ fgp ? fgp->codec.aom.y_points[0][1] : -1,
+ fgp ? fgp->codec.aom.scaling_shift : -1);
+ av_frame_unref(out);
+
+ /* expressions are accepted, as with the equivalent init options */
+ ret = avfilter_graph_send_command(graph, "fga", "scale", "1/2", NULL, 0,
0);
+ printf(" cmd scale=1/2: ret=%d\n", ret);
+ ret = avfilter_graph_send_command(graph, "fga", "scaling_shift", "8+1",
NULL, 0, 0);
+ printf(" cmd scaling_shift=8+1: ret=%d\n", ret);
+ ret = avfilter_graph_send_command(graph, "fga", "scaling_shift", "9.0",
NULL, 0, 0);
+ printf(" cmd scaling_shift=9.0: ret=%d\n", ret);
+
+ ret = push_frame(src, sink, frames[1], out);
+ if (ret < 0)
+ goto fail;
+ sd = av_frame_get_side_data(out, AV_FRAME_DATA_FILM_GRAIN_PARAMS);
+ fgp = sd ? (const AVFilmGrainParams *)sd->data : NULL;
+ printf("frame 1 after commands: y0=%d ss=%d\n",
+ fgp ? fgp->codec.aom.y_points[0][1] : -1,
+ fgp ? fgp->codec.aom.scaling_shift : -1);
+ av_frame_unref(out);
+
+ /* rejected commands keep the previous settings */
+ ret = avfilter_graph_send_command(graph, "fga", "scaling_shift", "7",
NULL, 0, 0);
+ printf(" cmd scaling_shift=7: EINVAL=%d\n", ret == AVERROR(EINVAL));
+ ret = avfilter_graph_send_command(graph, "fga", "scale", "nan", NULL, 0,
0);
+ printf(" cmd scale=nan: EINVAL=%d\n", ret == AVERROR(EINVAL));
+ ret = avfilter_graph_send_command(graph, "fga", "scale", NULL, NULL, 0, 0);
+ printf(" cmd scale (NULL arg): EINVAL=%d\n", ret == AVERROR(EINVAL));
+
+ ret = push_frame(src, sink, frames[2], out);
+ if (ret < 0)
+ goto fail;
+ sd = av_frame_get_side_data(out, AV_FRAME_DATA_FILM_GRAIN_PARAMS);
+ fgp = sd ? (const AVFilmGrainParams *)sd->data : NULL;
+ printf("frame 2 after rejections: y0=%d ss=%d\n",
+ fgp ? fgp->codec.aom.y_points[0][1] : -1,
+ fgp ? fgp->codec.aom.scaling_shift : -1);
+ ret = 0;
+fail:
+ av_frame_free(&out);
+ for (i = 0; i < 3; i++)
+ av_frame_free(&frames[i]);
+ avfilter_graph_free(&graph);
+ return ret;
+}
+
+int main(void)
+{
+ static const struct {
+ const char *name;
+ int (*fn)(void);
+ } tests[] = {
+ { "scale_isolation", test_scale_isolation },
+ { "derived_chroma", test_derived_chroma },
+ { "no_side_data", test_no_side_data },
+ { "multiple_sets", test_multiple_sets },
+ { "runtime_commands", test_runtime_commands },
+ };
+
+ for (unsigned i = 0; i < sizeof(tests) / sizeof(tests[0]); i++) {
+ int ret = tests[i].fn();
+
+ if (ret < 0) {
+ fprintf(stderr, "%s failed: %d\n", tests[i].name, ret);
+ return 1;
+ }
+ }
+ printf("all tests done\n");
+ return 0;
+}
diff --git a/tests/fate/api.mak b/tests/fate/api.mak
index 1659c7979c0..b449257509a 100644
--- a/tests/fate/api.mak
+++ b/tests/fate/api.mak
@@ -59,6 +59,11 @@ fate-api-threadmessage:
$(APITESTSDIR)/api-threadmessage-test$(EXESUF)
fate-api-threadmessage: CMD = run
$(APITESTSDIR)/api-threadmessage-test$(EXESUF) 3 10 30 50 2 20 40
fate-api-threadmessage: CMP = null
+FATE_API-$(CONFIG_FILM_GRAIN_ADJUST_FILTER) += fate-api-film-grain-adjust
+fate-api-film-grain-adjust: $(APITESTSDIR)/api-film-grain-adjust-test$(EXESUF)
+fate-api-film-grain-adjust: CMD = run
$(APITESTSDIR)/api-film-grain-adjust-test$(EXESUF)
+
+
FATE_API_SAMPLES-$(CONFIG_AVFORMAT) += $(FATE_API_SAMPLES_LIBAVFORMAT-yes)
ifdef SAMPLES
diff --git a/tests/fate/filter-video.mak b/tests/fate/filter-video.mak
index 82ab48dc68d..63447fcc999 100644
--- a/tests/fate/filter-video.mak
+++ b/tests/fate/filter-video.mak
@@ -1020,6 +1020,9 @@ fate-filter-xfade-slideup16: CMD = framecrc
-filter_complex "color=c=red:s=8x8:r
FATE_FILTER-$(call FILTERFRAMECRC, COLOR XFADE FORMAT) +=
fate-filter-xfade-duration0
fate-filter-xfade-duration0: CMD = framecrc -filter_complex
"color=c=red:s=8x8:r=8:d=4,format=yuv444p[a];color=c=0x0000ff:s=8x8:r=8:d=4,format=yuv444p[b];[a][b]xfade=transition=squeezeh:offset=1:duration=0"
+FATE_FILTER-$(call FILTERFRAMECRC, TESTSRC2 FILM_GRAIN_ADJUST) +=
fate-filter-film-grain-adjust
+fate-filter-film-grain-adjust: CMD = framecrc -flags bitexact -filter_complex
"testsrc2=cif:d=1,film_grain_adjust=scale=0.5:chroma_scale=0:overlap_flag=0:limit_output_range=1:ar_coeff_shift=6:scaling_shift=11"
-frames:v 25
+
FATE_SAMPLES_FFPROBE += $(FATE_METADATA_FILTER-yes)
FATE_SAMPLES_FFMPEG += $(FATE_FILTER_SAMPLES-yes)
FATE_FFPROBE += $(FATE_FILTER_FFPROBE-yes)
diff --git a/tests/ref/fate/api-film-grain-adjust
b/tests/ref/fate/api-film-grain-adjust
new file mode 100644
index 00000000000..7604ad737e9
--- /dev/null
+++ b/tests/ref/fate/api-film-grain-adjust
@@ -0,0 +1,35 @@
+scale=2.0 chroma_scale=3.0 with overrides:
+ seed=0x12345678 type=AV1
+ yp: 10/200 20/255 30/128 csfl=0 ovl=0 lim=1 ss=10 acs=8 gss=1 lag=2
cb=10/2/20 cr=3/4/25
+ uvp: c0 40/120 c0 60/240 c1 50/255
+ in unchanged=1 clone unchanged=1
+csfl=1 chroma_scale=0: unchanged=1
+csfl=1 scale=0 (chroma curve follows luma):
+ seed=0x00DEFACE type=AV1
+ yp: 10/0 20/0 30/0 csfl=1 ovl=1 lim=0 ss=9 acs=7 gss=1 lag=2 cb=5/2/15
cr=3/4/25
+ uvp:
+no grain side data in: output entry=0
+three-set frame scale=2.0 chroma_scale=3.0: entries=3
+ seed=0xBBBB0002 type=AV1
+ yp: 30/100 40/120 50/140 csfl=0 ovl=1 lim=0 ss=9 acs=7 gss=1 lag=2 cb=5/2/15
cr=3/4/25
+ uvp: c0 70/210
+ seed=0xAAAA0001 type=AV1
+ yp: 10/200 20/255 csfl=0 ovl=1 lim=0 ss=9 acs=7 gss=1 lag=2 cb=5/2/15
cr=3/4/25
+ uvp: c0 40/120 c0 60/240
+ seed=0xCCCC0003 type=other
+ bitexact=1 metadata=h274
+ select: seed=0xAAAA0001 y0=200
+ cow payload out0==in0=0 out1==in1=0 out0==out1=0
+ set 0 in unchanged=1 clone unchanged=1
+ set 1 in unchanged=1 clone unchanged=1
+ set 2 in unchanged=1 clone unchanged=1
+frame 0 (defaults): y0=100 ss=9
+ cmd scale=1/2: ret=0
+ cmd scaling_shift=8+1: ret=0
+ cmd scaling_shift=9.0: ret=0
+frame 1 after commands: y0=50 ss=9
+ cmd scaling_shift=7: EINVAL=1
+ cmd scale=nan: EINVAL=1
+ cmd scale (NULL arg): EINVAL=1
+frame 2 after rejections: y0=50 ss=9
+all tests done
diff --git a/tests/ref/fate/filter-film-grain-adjust
b/tests/ref/fate/filter-film-grain-adjust
new file mode 100644
index 00000000000..d3ae3333420
--- /dev/null
+++ b/tests/ref/fate/filter-film-grain-adjust
@@ -0,0 +1,30 @@
+#tb 0: 1/25
+#media_type 0: video
+#codec_id 0: rawvideo
+#dimensions 0: 352x288
+#sar 0: 1/1
+0, 0, 0, 1, 152064, 0x53022f4b
+0, 1, 1, 1, 152064, 0xfc4a6ac2
+0, 2, 2, 1, 152064, 0x26c7c206
+0, 3, 3, 1, 152064, 0xe2aef2d1
+0, 4, 4, 1, 152064, 0x906c21cd
+0, 5, 5, 1, 152064, 0x70303034
+0, 6, 6, 1, 152064, 0xe1bb274d
+0, 7, 7, 1, 152064, 0xdb03155b
+0, 8, 8, 1, 152064, 0x655808dc
+0, 9, 9, 1, 152064, 0xa6ac0127
+0, 10, 10, 1, 152064, 0x4e4f150c
+0, 11, 11, 1, 152064, 0x601ef77d
+0, 12, 12, 1, 152064, 0xdbc3f47f
+0, 13, 13, 1, 152064, 0x293ef835
+0, 14, 14, 1, 152064, 0xbc7f01af
+0, 15, 15, 1, 152064, 0xbb78091e
+0, 16, 16, 1, 152064, 0xabb711e7
+0, 17, 17, 1, 152064, 0x31562358
+0, 18, 18, 1, 152064, 0x607334e4
+0, 19, 19, 1, 152064, 0x97e432ce
+0, 20, 20, 1, 152064, 0x4bd742da
+0, 21, 21, 1, 152064, 0x2a1d1cab
+0, 22, 22, 1, 152064, 0x0cd2131c
+0, 23, 23, 1, 152064, 0x0ff1043a
+0, 24, 24, 1, 152064, 0x0698efe6
--
2.54.0
From 12b9ee1bffc5700b2d5e5a37b67900cda79ac89a Mon Sep 17 00:00:00 2001
From: luoye-cpu <[email protected]>
Date: Thu, 12 Nov 2026 03:46:18 +0800
Subject: [PATCH 2/2] avfilter: add film_grain_apply filter
FFmpeg can produce AV1 film grain synthesis parameters as
AV_FRAME_DATA_FILM_GRAIN_PARAMS frame side data (native av1, libdav1d and
qsvdec, gated by AV_CODEC_EXPORT_DATA_FILM_GRAIN), film_grain_adjust can
rewrite those parameters in flight, and libplacebo synthesises them for
display. What it cannot do is execute the synthesis inside the pipeline
itself: turning the parameters into pixels is left to the decoder
(libdav1d with apply_grain=1) or to the downstream consumer, and a
decoder that keeps its own synthesis on cannot be combined with
parameters that have just been adjusted in the filter chain.
Add the film_grain_apply video filter to close that gap. The filter
layer is the natural place for this: film grain synthesis is a
per-frame operation driven by per-frame side data, the filter chain is
the generic place where per-frame side data can be consumed between
arbitrary sources and sinks, and the pixels it writes feed the next
stage directly without a re-encode.
The filter clones the frame, makes the picture buffers writable
(copy-on-write, so frames sharing the buffer are never affected) and
calls the AV1 synthesiser avpriv_aom_apply_film_grain() that the AV1 and
HEVC/VVC decoders already use, exposed from libavcodec with the
avpriv_ prefix (ff_aom_apply_film_grain renamed, the two decoder call
sites updated, behaviour unchanged). The parameters are picked with
av_film_grain_params_select(), i.e. one synthesis per frame with the
set that the selection ranks highest; the remaining sets on the frame
become obsolete once the grain of the selected set is baked into the
pixels, so every AV_FRAME_DATA_FILM_GRAIN_PARAMS entry is removed from
the output frame ("applied" semantics, the same libplacebo follows by
deleting the entry after synthesis). H.274-type parameters are
synthesised inside the decoder, so frames whose selection resolves to
them (or to no usable set at all) pass through unchanged, keeping their
side data.
Because the synthesiser writes real pixels the filter is not usable on
hardware frames: query_formats restricts it to the 19 software pixel
formats the synthesiser dispatches on (gray8/9/10/12 and yuv
4:2:0/4:2:2/4:4:4 in 8..12 bit, the limited-range yuvj variants
included), so hardware formats fail at graph configuration time rather
than at synthesis time.
A single boolean option 'verbose' logs the parameters of the selected
set for the first synthesised frame and the per-role frame counts at
uninit.
The FATE api test constructs frames with AV1 and H.274 parameter sets
in-process and covers the deterministic synthesis (two passes over the
same parameters produce bit-exact pixels), the no-side-data and
H.274-only pass-throughs, multi-set selection with full side data
removal, the input-frame isolation and the documented EINVAL for an
unparseable option value.
This is independent of, and complementary to, work on the production
side (e.g. exporting film grain side data from nvdec_av1): the filter
operates on whatever AV_FRAME_DATA_FILM_GRAIN_PARAMS entry a decoder
exports and passes the synthesised result to whatever consumes it
downstream.
Signed-off-by: luoye-cpu <[email protected]>
---
Changelog | 1 +
doc/filters.texi | 92 ++++++
libavcodec/aom_film_grain.c | 4 +-
libavcodec/aom_film_grain.h | 4 +-
libavcodec/hevc/hevcdec.c | 2 +-
libavcodec/vvc/dec.c | 2 +-
libavfilter/Makefile | 1 +
libavfilter/allfilters.c | 1 +
libavfilter/version.h | 2 +-
libavfilter/vf_film_grain_apply.c | 222 +++++++++++++
tests/api/Makefile | 1 +
tests/api/api-film-grain-apply-test.c | 436 ++++++++++++++++++++++++++
tests/fate/api.mak | 3 +
tests/ref/fate/api-film-grain-apply | 12 +
14 files changed, 776 insertions(+), 7 deletions(-)
create mode 100644 libavfilter/vf_film_grain_apply.c
create mode 100644 tests/api/api-film-grain-apply-test.c
create mode 100644 tests/ref/fate/api-film-grain-apply
diff --git a/Changelog b/Changelog
index c627a42f1cf..5ed90546d95 100644
--- a/Changelog
+++ b/Changelog
@@ -7,6 +7,7 @@ version <next>:
- AVS+ (AVS1-P16, Broadcasting profile) support in the Chinese AVS decoder
- PCM PAMF decoder
- film_grain_adjust filter
+- film_grain_apply filter
version 9.1:
- ASTC image encoding and decoding via libastcenc, with .astc and KTX 1.0
muxers and demuxers
diff --git a/doc/filters.texi b/doc/filters.texi
index 223af69257a..46cd56b17bc 100644
--- a/doc/filters.texi
+++ b/doc/filters.texi
@@ -14816,6 +14816,98 @@ ffmpeg -c:v libdav1d -export_side_data +film_grain -i
master.mkv \
@end itemize
+@section film_grain_apply
+
+Apply AV1 film grain synthesis parameters carried as frame side data to
+the pixels: the filter reads the parameters attached to each frame and
+synthesises the grain they describe into the picture data.
+
+The @code{film_grain_adjust} filter rewrites film grain parameters without
+touching the picture data; this filter is the corresponding consumer of
+those parameters. Together they complete the decode, adjust, apply, encode
+route: an encoder downstream of this filter receives pictures with the
+grain already synthesised from the adjusted parameters.
+
+A frame that does not carry @code{AV_FRAME_DATA_FILM_GRAIN_PARAMS} side
+data is passed through unchanged. A frame carrying film grain parameters
+is not modified in place: the filter clones the frame and makes the
+picture buffer of the clone writable before synthesising, so the input
+frame and other frames sharing its picture buffer are unaffected.
+
+A frame may carry several film grain parameter sets as multiple
+@code{AV_FRAME_DATA_FILM_GRAIN_PARAMS} side data entries (alternative
+parameter sets for different video signal characteristics). The filter
+synthesises the set selected by @code{av_film_grain_params_select()}, i.e.
+the set a film grain synthesiser would consume: a candidate set has to
+match the bit depth, the color characteristics and the chroma resolution
+of the frame, and among the matching sets the one with the largest
+coverage of the frame dimensions wins. Once the grain has been synthesised,
+all @code{AV_FRAME_DATA_FILM_GRAIN_PARAMS} side data entries are removed
+from the output frame, including parameter sets of other types: synthesis
+is destructive to the metadata, and parameters left on a synthesised frame
+would make a downstream consumer add a second layer of grain on top of the
+one already in the picture.
+
+This filter synthesises AV1 film grain parameters only; H.274 film grain
+synthesis is the decoder's responsibility. A frame whose film grain side
+data does not yield an AV1 parameter set in the selection, e.g. a frame
+carrying an H.274 parameter set, a malformed entry, or side data whose
+dimensions do not match the frame, is passed through unchanged, with its
+side data intact.
+
+The filter requires software pixel formats: synthesis reads and writes the
+picture data, so hardware frames (e.g. @code{cuda}, @code{qsv}) cannot be
+processed, and a hardware pixel format is rejected at filter graph
+configuration time. The supported pixel formats mirror the formats the
+synthesiser supports: @code{gray8}, @code{yuv420p}, @code{yuv422p},
+@code{yuv444p}, @code{yuvj420p}, @code{yuvj422p}, @code{yuvj444p},
+@code{gray9}, @code{yuv420p9}, @code{yuv422p9}, @code{yuv444p9},
+@code{gray10}, @code{yuv420p10}, @code{yuv422p10}, @code{yuv444p10},
+@code{gray12}, @code{yuv420p12}, @code{yuv422p12} and @code{yuv444p12}.
+
+This filter accepts the following option:
+
+@table @option
+
+@item verbose
+Log the parameters of the film grain set selected for the first frame the
+filter synthesises grain for, and a summary of the frame counts when the
+filter is closed: the number of frames processed, the number of frames
+with grain synthesised, the number of frames passed through without film
+grain side data, and the number of frames passed through with film grain
+parameters that were not synthesised. Default is disabled.
+@end table
+
+A decoder that synthesises film grain into the decoded picture must keep
+that synthesis disabled when its parameters are exported as side data for
+this filter: the picture would already contain the grain, and synthesising
+the exported parameters on top of it would add a second layer of grain.
+The @code{libdav1d} decoder disables its film grain synthesis by default
+when film grain side data is exported; keep the deprecated
+@option{filmgrain} option of @code{libdav1d} at its default when using
+this filter.
+
+@subsection Examples
+
+@itemize
+@item
+Halve the grain amplitude of a source carrying film grain parameters and
+synthesise the adjusted parameters into the pixels:
+@example
+ffmpeg -c:v libdav1d -export_side_data +film_grain -i master.mkv \
+ -vf film_grain_adjust=scale=0.5,film_grain_apply -c:v libx264 out.mkv
+@end example
+
+@item
+Synthesise the film grain parameters exported by the decoder into the
+pixels:
+@example
+ffmpeg -c:v libdav1d -export_side_data +film_grain -i master.mkv \
+ -vf film_grain_apply -c:v libx264 out.mkv
+@end example
+
+@end itemize
+
@section find_rect
Find a rectangular object in the input video.
diff --git a/libavcodec/aom_film_grain.c b/libavcodec/aom_film_grain.c
index 205e93604f8..604a49da29e 100644
--- a/libavcodec/aom_film_grain.c
+++ b/libavcodec/aom_film_grain.c
@@ -65,8 +65,8 @@ static const int16_t gaussian_sequence[2048];
#undef BIT_DEPTH
-int ff_aom_apply_film_grain(AVFrame *out, const AVFrame *in,
- const AVFilmGrainParams *params)
+int avpriv_aom_apply_film_grain(AVFrame *out, const AVFrame *in,
+ const AVFilmGrainParams *params)
{
const AVFilmGrainAOMParams *const data = ¶ms->codec.aom;
const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(out->format);
diff --git a/libavcodec/aom_film_grain.h b/libavcodec/aom_film_grain.h
index 97c33deb471..2343d433e2c 100644
--- a/libavcodec/aom_film_grain.h
+++ b/libavcodec/aom_film_grain.h
@@ -38,8 +38,8 @@ typedef struct AVFilmGrainAFGS1Params {
// Synthesizes film grain on top of `in` and stores the result to `out`. `out`
// must already have been allocated and set to the same size and format as
`in`.
-int ff_aom_apply_film_grain(AVFrame *out, const AVFrame *in,
- const AVFilmGrainParams *params);
+int avpriv_aom_apply_film_grain(AVFrame *out, const AVFrame *in,
+ const AVFilmGrainParams *params);
// Parse AFGS1 parameter sets from an ITU-T T.35 payload. Returns 0 on success,
// or a negative error code.
diff --git a/libavcodec/hevc/hevcdec.c b/libavcodec/hevc/hevcdec.c
index 0934f640966..fd5f959c380 100644
--- a/libavcodec/hevc/hevcdec.c
+++ b/libavcodec/hevc/hevcdec.c
@@ -4333,7 +4333,7 @@ static int hevc_frame_end(HEVCContext *s,
HEVCLayerContext *l)
ret = ff_h274_apply_film_grain(out->frame_grain, out->f, fgp);
break;
case AV_FILM_GRAIN_PARAMS_AV1:
- ret = ff_aom_apply_film_grain(out->frame_grain, out->f, fgp);
+ ret = avpriv_aom_apply_film_grain(out->frame_grain, out->f, fgp);
break;
}
if (ret < 0) {
diff --git a/libavcodec/vvc/dec.c b/libavcodec/vvc/dec.c
index f69fa99c6d6..f5577bc1d91 100644
--- a/libavcodec/vvc/dec.c
+++ b/libavcodec/vvc/dec.c
@@ -1110,7 +1110,7 @@ static int frame_end(VVCContext *s, VVCFrameContext *fc)
return ret;
break;
case AV_FILM_GRAIN_PARAMS_AV1:
- ret = ff_aom_apply_film_grain(fc->ref->frame_grain,
fc->ref->frame, fgp);
+ ret = avpriv_aom_apply_film_grain(fc->ref->frame_grain,
fc->ref->frame, fgp);
if (ret < 0)
return ret;
break;
diff --git a/libavfilter/Makefile b/libavfilter/Makefile
index a196cc1bb5d..2f55f834805 100644
--- a/libavfilter/Makefile
+++ b/libavfilter/Makefile
@@ -322,6 +322,7 @@ OBJS-$(CONFIG_FIELDMATCH_FILTER) +=
vf_fieldmatch.o
OBJS-$(CONFIG_FIELDORDER_FILTER) += vf_fieldorder.o
OBJS-$(CONFIG_FILLBORDERS_FILTER) += vf_fillborders.o
OBJS-$(CONFIG_FILM_GRAIN_ADJUST_FILTER) += vf_film_grain_adjust.o
+OBJS-$(CONFIG_FILM_GRAIN_APPLY_FILTER) += vf_film_grain_apply.o
OBJS-$(CONFIG_FIND_RECT_FILTER) += vf_find_rect.o lavfutils.o
OBJS-$(CONFIG_FLIP_VULKAN_FILTER) += vf_flip_vulkan.o vulkan.o
vulkan_filter.o
OBJS-$(CONFIG_FLOODFILL_FILTER) += vf_floodfill.o
diff --git a/libavfilter/allfilters.c b/libavfilter/allfilters.c
index 4a44ca9c90f..d3f9fca8fdd 100644
--- a/libavfilter/allfilters.c
+++ b/libavfilter/allfilters.c
@@ -294,6 +294,7 @@ extern const FFFilter ff_vf_fieldmatch;
extern const FFFilter ff_vf_fieldorder;
extern const FFFilter ff_vf_fillborders;
extern const FFFilter ff_vf_film_grain_adjust;
+extern const FFFilter ff_vf_film_grain_apply;
extern const FFFilter ff_vf_find_rect;
extern const FFFilter ff_vf_flip_vulkan;
extern const FFFilter ff_vf_floodfill;
diff --git a/libavfilter/version.h b/libavfilter/version.h
index 537df129cd3..7642b670d12 100644
--- a/libavfilter/version.h
+++ b/libavfilter/version.h
@@ -31,7 +31,7 @@
#include "version_major.h"
-#define LIBAVFILTER_VERSION_MINOR 13
+#define LIBAVFILTER_VERSION_MINOR 14
#define LIBAVFILTER_VERSION_MICRO 100
diff --git a/libavfilter/vf_film_grain_apply.c
b/libavfilter/vf_film_grain_apply.c
new file mode 100644
index 00000000000..ea0091e22ca
--- /dev/null
+++ b/libavfilter/vf_film_grain_apply.c
@@ -0,0 +1,222 @@
+/*
+ * Film grain synthesis filter (AV1)
+ *
+ * Applies the AV1 film grain synthesis parameters carried on each frame as
+ * AV_FRAME_DATA_FILM_GRAIN_PARAMS side data to the pixels themselves. A frame
+ * may carry several film grain parameter sets as multiple side data entries of
+ * that type (see libavutil/frame.h); synthesis is performed with the single
+ * set av_film_grain_params_select() picks, matching the decoder-internal
+ * synthesis contract (see hevc_frame_end()). Parameter sets of other types
+ * (e.g. H.274) are not consumed by this filter: H.274 synthesis is a
+ * decoder-side duty, so frames carrying such sets pass through untouched.
+ *
+ * Once the grain has been synthesised, the film grain side data is removed
+ * from the output frame: synthesis is destructive to the metadata, and
+ * keeping the parameters would expose any downstream film grain consumer
+ * (libplacebo, an encoder, a second filter instance) to double synthesis.
+ *
+ * The filter only ever writes pixels, it does not edit the side data
+ * contents. Together with film_grain_adjust (a pixel pass-through that
+ * rewrites the grain parameters) this completes the "decode -> modify grain
+ * params -> synthesise grain -> encode" route.
+ *
+ * Copyright (c) 2026
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "libavcodec/aom_film_grain.h"
+#include "libavutil/common.h"
+#include "libavutil/opt.h"
+
+#include "avfilter.h"
+#include "filters.h"
+#include "video.h"
+
+/* mirrors the pixel format dispatch of the AV1 film grain synthesiser
+ * (libavcodec/aom_film_grain.c); formats outside this list - hardware formats
+ * in particular - are rejected at graph configuration time, before any frame
+ * is processed */
+static const enum AVPixelFormat film_grain_apply_pix_fmts[] = {
+ AV_PIX_FMT_GRAY8,
+ AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P,
+ AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ444P,
+ AV_PIX_FMT_GRAY9,
+ AV_PIX_FMT_YUV420P9, AV_PIX_FMT_YUV422P9, AV_PIX_FMT_YUV444P9,
+ AV_PIX_FMT_GRAY10,
+ AV_PIX_FMT_YUV420P10, AV_PIX_FMT_YUV422P10, AV_PIX_FMT_YUV444P10,
+ AV_PIX_FMT_GRAY12,
+ AV_PIX_FMT_YUV420P12, AV_PIX_FMT_YUV422P12, AV_PIX_FMT_YUV444P12,
+ AV_PIX_FMT_NONE
+};
+
+typedef struct FilmGrainApplyContext {
+ const AVClass *class;
+
+ int verbose;
+ int logged; /* first-frame parameter summary already logged */
+ int64_t frames_total;
+ int64_t frames_applied;
+ int64_t frames_passthrough_no_data;
+ int64_t frames_other_type;
+} FilmGrainApplyContext;
+
+static int filter_frame(AVFilterLink *inlink, AVFrame *in)
+{
+ AVFilterContext *ctx = inlink->dst;
+ AVFilterLink *outlink = ctx->outputs[0];
+ FilmGrainApplyContext *s = ctx->priv;
+ const AVFilmGrainParams *params;
+ AVFrame *out;
+ int ret;
+
+ s->frames_total++;
+
+ /* no film grain parameters on the frame: nothing to synthesise, the
+ * frame passes through with zero copies */
+ if (!av_frame_get_side_data(in, AV_FRAME_DATA_FILM_GRAIN_PARAMS)) {
+ s->frames_passthrough_no_data++;
+ return ff_filter_frame(outlink, in);
+ }
+
+ /* One synthesis per frame, with the set av_film_grain_params_select()
+ * picks: the remaining sets on the frame describe the same frame's grain
+ * as alternative parameterisations and become obsolete once the grain of
+ * the selected set is baked into the pixels. */
+ params = av_film_grain_params_select(in);
+ if (!params || params->type != AV_FILM_GRAIN_PARAMS_AV1) {
+ s->frames_other_type++;
+ if (s->verbose) {
+ if (params)
+ av_log(ctx, AV_LOG_VERBOSE,
+ "film_grain_apply: H.274 film grain parameters are "
+ "synthesised inside the decoder, passing the frame "
+ "through unchanged\n");
+ else
+ av_log(ctx, AV_LOG_VERBOSE,
+ "film_grain_apply: film grain parameter selection "
+ "returned no usable set, passing the frame through "
+ "unchanged\n");
+ }
+ out = av_frame_clone(in);
+ if (!out) {
+ av_frame_free(&in);
+ return AVERROR(ENOMEM);
+ }
+ av_frame_free(&in);
+ return ff_filter_frame(outlink, out);
+ }
+
+ /* Copy-on-write the picture buffers: the synthesiser writes the output
+ * frame, which must not share buffers with the input frame. The side
+ * data stays shared with the input frame and is only detached from the
+ * output below. */
+ out = av_frame_clone(in);
+ if (!out) {
+ av_frame_free(&in);
+ return AVERROR(ENOMEM);
+ }
+ ret = av_frame_make_writable(out);
+ if (ret < 0) {
+ av_frame_free(&out);
+ av_frame_free(&in);
+ return ret;
+ }
+
+ ret = avpriv_aom_apply_film_grain(out, in, params);
+ if (ret < 0) {
+ av_frame_free(&out);
+ av_frame_free(&in);
+ return ret;
+ }
+
+ /* "applied" semantics: the grain is now baked into the pixels, so the
+ * film grain side data is removed from the output frame to keep any
+ * downstream consumer from synthesising the same grain again. */
+ av_frame_remove_side_data(out, AV_FRAME_DATA_FILM_GRAIN_PARAMS);
+
+ s->frames_applied++;
+ if (s->verbose && !s->logged) {
+ av_log(ctx, AV_LOG_VERBOSE,
+ "film_grain_apply: first frame synthesised, selected set: "
+ "seed=%"PRIu64" bit_depth_luma=%d bit_depth_chroma=%d "
+ "num_y_points=%d num_uv_points=%d/%d "
+ "chroma_scaling_from_luma=%d ar_coeff_lag=%d "
+ "scaling_shift=%d ar_coeff_shift=%d "
+ "uv_mult=%d/%d uv_mult_luma=%d/%d uv_offset=%d/%d\n",
+ params->seed,
+ params->bit_depth_luma, params->bit_depth_chroma,
+ params->codec.aom.num_y_points,
+ params->codec.aom.num_uv_points[0],
+ params->codec.aom.num_uv_points[1],
+ params->codec.aom.chroma_scaling_from_luma,
+ params->codec.aom.ar_coeff_lag,
+ params->codec.aom.scaling_shift,
+ params->codec.aom.ar_coeff_shift,
+ params->codec.aom.uv_mult[0], params->codec.aom.uv_mult[1],
+ params->codec.aom.uv_mult_luma[0],
+ params->codec.aom.uv_mult_luma[1],
+ params->codec.aom.uv_offset[0], params->codec.aom.uv_offset[1]);
+ s->logged = 1;
+ }
+
+ av_frame_free(&in);
+ return ff_filter_frame(outlink, out);
+}
+
+static av_cold void uninit(AVFilterContext *ctx)
+{
+ FilmGrainApplyContext *s = ctx->priv;
+
+ if (s->verbose)
+ av_log(ctx, AV_LOG_VERBOSE,
+ "film_grain_apply: frames=%"PRId64" applied=%"PRId64
+ " passthrough_no_data=%"PRId64" other_type=%"PRId64"\n",
+ s->frames_total, s->frames_applied,
+ s->frames_passthrough_no_data, s->frames_other_type);
+}
+
+#define OFFSET(x) offsetof(FilmGrainApplyContext, x)
+#define VF AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_FILTERING_PARAM
+
+static const AVOption film_grain_apply_options[] = {
+ { "verbose", "log the parameters of the set av_film_grain_params_select()
picks for the first frame synthesised and a frame counter summary at exit",
+ OFFSET(verbose), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, VF },
+ { NULL }
+};
+
+static const AVFilterPad film_grain_apply_inputs[] = {
+ {
+ .name = "default",
+ .type = AVMEDIA_TYPE_VIDEO,
+ .filter_frame = filter_frame,
+ },
+};
+
+AVFILTER_DEFINE_CLASS(film_grain_apply);
+
+const FFFilter ff_vf_film_grain_apply = {
+ .p.name = "film_grain_apply",
+ .p.description = NULL_IF_CONFIG_SMALL("Apply AV1 film grain synthesis
parameters carried as frame side data to the pixels."),
+ .p.priv_class = &film_grain_apply_class,
+ .p.flags = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC,
+ .priv_size = sizeof(FilmGrainApplyContext),
+ FILTER_PIXFMTS_ARRAY(film_grain_apply_pix_fmts),
+ .uninit = uninit,
+ FILTER_INPUTS(film_grain_apply_inputs),
+ FILTER_OUTPUTS(ff_video_default_filterpad),
+};
\ No newline at end of file
diff --git a/tests/api/Makefile b/tests/api/Makefile
index 87d899fc852..c6af837f2f5 100644
--- a/tests/api/Makefile
+++ b/tests/api/Makefile
@@ -10,6 +10,7 @@ APITESTPROGS-yes += api-seek api-dump-stream-meta
APITESTPROGS-$(call DEMDEC, H263, H263) += api-band
APITESTPROGS-$(HAVE_THREADS) += api-threadmessage
APITESTPROGS-$(CONFIG_FILM_GRAIN_ADJUST_FILTER) += api-film-grain-adjust
+APITESTPROGS-$(CONFIG_FILM_GRAIN_APPLY_FILTER) += api-film-grain-apply
APITESTPROGS-$(CONFIG_AVCODEC) += api-enc-info
APITESTPROGS-$(CONFIG_PCM_S16LE_DECODER) += api-skip-samples
APITESTPROGS-$(call ALLYES, H261_ENCODER H261_PARSER) += api-enc-parser
diff --git a/tests/api/api-film-grain-apply-test.c
b/tests/api/api-film-grain-apply-test.c
new file mode 100644
index 00000000000..91892768de6
--- /dev/null
+++ b/tests/api/api-film-grain-apply-test.c
@@ -0,0 +1,436 @@
+/*
+ * Copyright (c) 2026
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/*
+ * film_grain_apply filter API test: prints the synthesis results, the
+ * pass-through/isolation behaviour and the errno symbol comparisons;
+ * the FATE reference file captures the output. Operational failures are
+ * reported on stderr and exit non-zero.
+ */
+
+#include <inttypes.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "libavfilter/avfilter.h"
+#include "libavfilter/buffersink.h"
+#include "libavfilter/buffersrc.h"
+
+#include "libavutil/crc.h"
+#include "libavutil/film_grain_params.h"
+#include "libavutil/pixfmt.h"
+
+#define WIDTH 64
+#define HEIGHT 64
+
+#define SRC_ARGS "video_size=" AV_STRINGIFY(WIDTH) "x" AV_STRINGIFY(HEIGHT) \
+ ":pix_fmt=yuv420p:time_base=1/25:pixel_aspect=1/1"
+
+/* deterministic pixel fill over the payload rows of the three planes of
+ * the yuv420p test frames; stride padding is left untouched, matching the
+ * payload-row scope of crc_frame(), so the printed CRC values are stable
+ * across runs */
+static void fill_pixels(AVFrame *f)
+{
+ for (int p = 0; p < 3; p++) {
+ int w = p ? (f->width + 1) >> 1 : f->width;
+ int h = p ? (f->height + 1) >> 1 : f->height;
+
+ for (int y = 0; y < h; y++)
+ for (int x = 0; x < w; x++)
+ f->data[p][y * f->linesize[p] + x] =
+ (uint8_t)((x + 8 * y + 16 * p) & 0xff);
+ }
+}
+
+static AVFrame *alloc_test_frame(void)
+{
+ AVFrame *f = av_frame_alloc();
+
+ if (!f)
+ return NULL;
+ f->format = AV_PIX_FMT_YUV420P;
+ f->width = WIDTH;
+ f->height = HEIGHT;
+ if (av_frame_get_buffer(f, 0) < 0)
+ av_frame_free(&f);
+ else
+ fill_pixels(f);
+ return f;
+}
+
+static void fill_aom(AVFilmGrainAOMParams *a)
+{
+ *a = (AVFilmGrainAOMParams) {
+ .num_y_points = 3,
+ .y_points = { { 10, 100 }, { 20, 150 }, { 30, 64 } },
+ .chroma_scaling_from_luma = 0,
+ .num_uv_points = { 2, 1 },
+ .uv_points = { { { 40, 40 }, { 60, 80 } }, { { 50, 200 } } },
+ .scaling_shift = 9, .ar_coeff_lag = 2, .ar_coeff_shift = 7,
+ .grain_scale_shift = 1, .uv_mult = { 5, 3 }, .uv_mult_luma = { 2, 4 },
+ .uv_offset = { 15, 25 }, .overlap_flag = 1, .limit_output_range = 0,
+ };
+}
+
+/* attach one AV1 film grain set with the default test values; the
+ * top-level fields match the yuv420p test frame so that
+ * av_film_grain_params_select() picks the set for synthesis */
+static AVFilmGrainParams *add_aom_entry(AVFrame *f, uint32_t seed)
+{
+ AVFilmGrainParams *p = av_film_grain_params_create_side_data(f);
+
+ if (p) {
+ p->type = AV_FILM_GRAIN_PARAMS_AV1;
+ p->seed = seed;
+ fill_aom(&p->codec.aom);
+ p->width = WIDTH;
+ p->height = HEIGHT;
+ p->subsampling_x = p->subsampling_y = 1;
+ p->bit_depth_luma = 8;
+ p->bit_depth_chroma = 8;
+ }
+ return p;
+}
+
+/* attach one H.274 film grain set */
+static AVFilmGrainParams *add_h274_entry(AVFrame *f, uint32_t seed)
+{
+ AVFilmGrainParams *p = av_film_grain_params_create_side_data(f);
+
+ if (p) {
+ p->type = AV_FILM_GRAIN_PARAMS_H274;
+ p->seed = seed;
+ p->codec.h274.model_id = 1;
+ p->codec.h274.log2_scale_factor = 2;
+ p->codec.h274.num_model_values[0] = 3;
+ p->codec.h274.comp_model_value[0][0][0] = -100;
+ p->codec.h274.comp_model_value[0][0][1] = 0;
+ p->codec.h274.comp_model_value[0][0][2] = 100;
+ }
+ return p;
+}
+
+/* number of film grain side data entries on the frame */
+static int count_fgs(const AVFrame *f)
+{
+ int n = 0;
+
+ for (int i = 0; i < f->nb_side_data; i++)
+ if (f->side_data[i]->type == AV_FRAME_DATA_FILM_GRAIN_PARAMS)
+ n++;
+ return n;
+}
+
+/* the frame's film grain side data matches the reference bytes */
+static int entry_matches(const AVFrame *f, const unsigned char *ref)
+{
+ AVFrameSideData *sd = av_frame_get_side_data(f,
AV_FRAME_DATA_FILM_GRAIN_PARAMS);
+
+ return sd && sd->size == sizeof(AVFilmGrainParams) &&
+ !memcmp(sd->data, ref, sizeof(AVFilmGrainParams));
+}
+
+/* pixel CRC over the payload rows of the three planes of the yuv420p
+ * test frames; stride padding is excluded so the value tracks pixels */
+static uint32_t crc_frame(const AVFrame *f)
+{
+ const AVCRC *crc_tab = av_crc_get_table(AV_CRC_32_IEEE);
+ uint32_t crc = 0;
+
+ if (!crc_tab || f->format != AV_PIX_FMT_YUV420P)
+ return 0;
+ for (int p = 0; p < 3; p++) {
+ int w = p ? (f->width + 1) >> 1 : f->width;
+ int h = p ? (f->height + 1) >> 1 : f->height;
+
+ for (int y = 0; y < h; y++)
+ crc = av_crc(crc_tab, crc, f->data[p] + (size_t)y *
f->linesize[p], w);
+ }
+ return crc;
+}
+
+/* shared graph setup: "buffer -> film_grain_apply=<args> -> buffersink" */
+static int make_graph(AVFilterGraph **graph, AVFilterContext **src,
+ AVFilterContext **sink, const char *args)
+{
+ AVFilterContext *apply = NULL;
+ int ret;
+
+ if (!avfilter_get_by_name("buffer") ||
+ !avfilter_get_by_name("buffersink") ||
+ !avfilter_get_by_name("film_grain_apply"))
+ return AVERROR(ENOSYS);
+
+ *graph = avfilter_graph_alloc();
+ if (!*graph)
+ return AVERROR(ENOMEM);
+
+ ret = avfilter_graph_create_filter(src, avfilter_get_by_name("buffer"),
+ "src", SRC_ARGS, NULL, *graph);
+ if (!ret)
+ ret = avfilter_graph_create_filter(&apply,
+
avfilter_get_by_name("film_grain_apply"),
+ "apply", args, NULL, *graph);
+ if (!ret)
+ ret = avfilter_graph_create_filter(sink,
+ avfilter_get_by_name("buffersink"),
+ "sink", NULL, NULL, *graph);
+ if (!ret)
+ ret = avfilter_link(*src, 0, apply, 0);
+ if (!ret)
+ ret = avfilter_link(apply, 0, *sink, 0);
+ if (!ret)
+ ret = avfilter_graph_config(*graph, NULL);
+
+ if (ret < 0) {
+ avfilter_graph_free(graph);
+ *src = *sink = NULL;
+ }
+ return ret;
+}
+
+/* push one frame through the shared graph setup and return the output */
+static int run_filter(AVFrame *in, AVFrame *out, const char *args)
+{
+ AVFilterGraph *graph = NULL;
+ AVFilterContext *src = NULL, *sink = NULL;
+ int ret = make_graph(&graph, &src, &sink, args);
+
+ if (ret < 0)
+ return ret;
+
+ /* KEEP_REF: the frame handed to the filter chain shares its side data
+ * buffers with the caller's frame, which is the situation the
+ * copy-on-write handling must cope with */
+ ret = av_buffersrc_add_frame_flags(src, in, AV_BUFFERSRC_FLAG_KEEP_REF);
+ if (ret >= 0)
+ ret = av_buffersink_get_frame(sink, out);
+
+ avfilter_graph_free(&graph);
+ return ret;
+}
+
+/* one AV1 set: two independent synthesis passes over the same frame
+ * produce bit-exact pixels (deterministic synthesis), the output frame
+ * carries no film grain side data and the input frame is untouched */
+static int test_single_set_apply(void)
+{
+ AVFrame *in = NULL, *out1 = NULL, *out2 = NULL;
+ unsigned char ref[sizeof(AVFilmGrainParams)];
+ uint32_t crc1, crc2;
+ int ret;
+
+ in = alloc_test_frame();
+ out1 = av_frame_alloc();
+ out2 = av_frame_alloc();
+ if (!in || !out1 || !out2 || !add_aom_entry(in, 0x12345678)) {
+ ret = AVERROR(ENOMEM);
+ goto fail;
+ }
+ memcpy(ref, av_frame_get_side_data(in,
AV_FRAME_DATA_FILM_GRAIN_PARAMS)->data,
+ sizeof(AVFilmGrainParams));
+
+ ret = run_filter(in, out1, "");
+ if (ret < 0)
+ goto fail;
+ ret = run_filter(in, out2, "");
+ if (ret < 0)
+ goto fail;
+
+ crc1 = crc_frame(out1);
+ crc2 = crc_frame(out2);
+ printf("single AV1 set apply:\n");
+ printf(" entries out=%d crc=0x%08"PRIX32"\n",
+ count_fgs(out1), crc1);
+ printf(" second pass crc=0x%08"PRIX32" bitexact=%d\n", crc2, crc1 ==
crc2);
+ printf(" in side data unchanged=%d\n", entry_matches(in, ref));
+ ret = 0;
+fail:
+ av_frame_free(&out2);
+ av_frame_free(&out1);
+ av_frame_free(&in);
+ return ret;
+}
+
+/* frames without grain side data pass through: pixels unchanged and no
+ * side data added */
+static int test_no_side_data(void)
+{
+ AVFrame *in = NULL, *out = NULL;
+ uint32_t crc_in, crc_out;
+ int ret;
+
+ in = alloc_test_frame();
+ out = av_frame_alloc();
+ if (!in || !out) {
+ ret = AVERROR(ENOMEM);
+ goto fail;
+ }
+ crc_in = crc_frame(in);
+
+ ret = run_filter(in, out, "");
+ if (ret < 0)
+ goto fail;
+ crc_out = crc_frame(out);
+ printf("no side data passthrough: crc in=0x%08"PRIX32" out=0x%08"PRIX32
+ " equal=%d entries out=%d\n",
+ crc_in, crc_out, crc_in == crc_out, count_fgs(out));
+ ret = 0;
+fail:
+ av_frame_free(&out);
+ av_frame_free(&in);
+ return ret;
+}
+
+/* a frame carrying only an H.274 set is passed through without
+ * synthesis: pixels unchanged and the side data entry is preserved */
+static int test_h274_passthrough(void)
+{
+ AVFrame *in = NULL, *out = NULL;
+ unsigned char ref[sizeof(AVFilmGrainParams)];
+ uint32_t crc_in, crc_out;
+ int ret;
+
+ in = alloc_test_frame();
+ out = av_frame_alloc();
+ if (!in || !out || !add_h274_entry(in, 0x27400001)) {
+ ret = AVERROR(ENOMEM);
+ goto fail;
+ }
+ memcpy(ref, av_frame_get_side_data(in,
AV_FRAME_DATA_FILM_GRAIN_PARAMS)->data,
+ sizeof(AVFilmGrainParams));
+ crc_in = crc_frame(in);
+
+ ret = run_filter(in, out, "");
+ if (ret < 0)
+ goto fail;
+ crc_out = crc_frame(out);
+ printf("h274-only passthrough: entries in=%d out=%d\n",
+ count_fgs(in), count_fgs(out));
+ printf(" crc equal=%d entry preserved=%d\n",
+ crc_in == crc_out, entry_matches(out, ref));
+ ret = 0;
+fail:
+ av_frame_free(&out);
+ av_frame_free(&in);
+ return ret;
+}
+
+/* three parameter sets on one frame (two AV1 + one H.274): the filter
+ * synthesises the set chosen by av_film_grain_params_select and drops
+ * all grain side data from the output; the two AV1 entries are swapped
+ * before filtering so a keep-first implementation would pick the
+ * half-size set and fail the reference */
+static int test_multiple_sets(void)
+{
+ AVFrame *in = NULL, *out = NULL;
+ AVFilmGrainParams *p;
+ const AVFilmGrainParams *sel;
+ int ret;
+
+ in = alloc_test_frame();
+ out = av_frame_alloc();
+ p = (in && out) ? add_aom_entry(in, 0xAAAA0001) : NULL;
+ if (!p) {
+ ret = AVERROR(ENOMEM);
+ goto fail;
+ }
+ /* set A: full declared size */
+ p->width = WIDTH;
+ p->height = HEIGHT;
+ p->subsampling_x = p->subsampling_y = 1;
+
+ /* set B: half declared size, 8-bit depths matching the yuv420p frame */
+ p = add_aom_entry(in, 0xBBBB0002);
+ if (!p) {
+ ret = AVERROR(ENOMEM);
+ goto fail;
+ }
+ p->width = WIDTH / 2;
+ p->height = HEIGHT / 2;
+ p->subsampling_x = p->subsampling_y = 1;
+ p->bit_depth_luma = 8;
+ p->bit_depth_chroma = 8;
+
+ if (!add_h274_entry(in, 0xCCCC0003)) {
+ ret = AVERROR(ENOMEM);
+ goto fail;
+ }
+ /* swap the two AV1 entries: the full-size set A is no longer first */
+ AVFrameSideData *tmp = in->side_data[0];
+ in->side_data[0] = in->side_data[1];
+ in->side_data[1] = tmp;
+
+ sel = av_film_grain_params_select(in);
+ printf("three-set frame: entries before=%d\n", count_fgs(in));
+ printf(" select seed=0x%08"PRIX64" y0=%d\n", sel ? sel->seed : 0,
+ sel && sel->type == AV_FILM_GRAIN_PARAMS_AV1 ?
+ sel->codec.aom.y_points[0][1] : -1);
+
+ ret = run_filter(in, out, "");
+ if (ret < 0)
+ goto fail;
+ printf(" entries after=%d crc=0x%08"PRIX32"\n",
+ count_fgs(out), crc_frame(out));
+ ret = 0;
+fail:
+ av_frame_free(&out);
+ av_frame_free(&in);
+ return ret;
+}
+
+/* option parsing failures surface a documented errno: compare against
+ * the symbol, not a literal number */
+static int test_option_errno(void)
+{
+ AVFilterGraph *graph = NULL;
+ AVFilterContext *src = NULL, *sink = NULL;
+ int ret;
+
+ ret = make_graph(&graph, &src, &sink, "verbose=bogus");
+ printf("option verbose=bogus: EINVAL=%d\n", ret == AVERROR(EINVAL));
+ return 0;
+}
+
+int main(void)
+{
+ static const struct {
+ const char *name;
+ int (*fn)(void);
+ } tests[] = {
+ { "single_set_apply", test_single_set_apply },
+ { "no_side_data", test_no_side_data },
+ { "h274_passthrough", test_h274_passthrough },
+ { "multiple_sets", test_multiple_sets },
+ { "option_errno", test_option_errno },
+ };
+
+ for (unsigned i = 0; i < sizeof(tests) / sizeof(tests[0]); i++) {
+ int ret = tests[i].fn();
+
+ if (ret < 0) {
+ fprintf(stderr, "%s failed: %d\n", tests[i].name, ret);
+ return 1;
+ }
+ }
+ printf("all tests done\n");
+ return 0;
+}
\ No newline at end of file
diff --git a/tests/fate/api.mak b/tests/fate/api.mak
index b449257509a..a5f4d42dce5 100644
--- a/tests/fate/api.mak
+++ b/tests/fate/api.mak
@@ -63,6 +63,9 @@ FATE_API-$(CONFIG_FILM_GRAIN_ADJUST_FILTER) +=
fate-api-film-grain-adjust
fate-api-film-grain-adjust: $(APITESTSDIR)/api-film-grain-adjust-test$(EXESUF)
fate-api-film-grain-adjust: CMD = run
$(APITESTSDIR)/api-film-grain-adjust-test$(EXESUF)
+FATE_API-$(CONFIG_FILM_GRAIN_APPLY_FILTER) += fate-api-film-grain-apply
+fate-api-film-grain-apply: $(APITESTSDIR)/api-film-grain-apply-test$(EXESUF)
+fate-api-film-grain-apply: CMD = run
$(APITESTSDIR)/api-film-grain-apply-test$(EXESUF)
FATE_API_SAMPLES-$(CONFIG_AVFORMAT) += $(FATE_API_SAMPLES_LIBAVFORMAT-yes)
diff --git a/tests/ref/fate/api-film-grain-apply
b/tests/ref/fate/api-film-grain-apply
new file mode 100644
index 00000000000..c15d27e425c
--- /dev/null
+++ b/tests/ref/fate/api-film-grain-apply
@@ -0,0 +1,12 @@
+single AV1 set apply:
+ entries out=0 crc=0xFB1BF15E
+ second pass crc=0xFB1BF15E bitexact=1
+ in side data unchanged=1
+no side data passthrough: crc in=0xEC3B0504 out=0xEC3B0504 equal=1 entries
out=0
+h274-only passthrough: entries in=1 out=1
+ crc equal=1 entry preserved=1
+three-set frame: entries before=3
+ select seed=0xAAAA0001 y0=100
+ entries after=0 crc=0xCB279903
+option verbose=bogus: EINVAL=1
+all tests done
--
2.54.0
_______________________________________________
ffmpeg-devel mailing list -- [email protected]
To unsubscribe send an email to [email protected]