PR #26002 opened by luoye-cpu
URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/26002
Patch URL: https://code.ffmpeg.org/FFmpeg/FFmpeg/pulls/26002.patch

AV1 film grain parameters exist in FFmpeg as AV_FRAME_DATA_FILM_GRAIN_PARAMS
frame side data: the native av1 decoder, libdav1d and qsvdec export them when
the caller asks for AV_CODEC_EXPORT_DATA_FILM_GRAIN. What no encoder does so
far is write them back into the bitstream it produces - grepping the tree, no
AV1 encoder consumes this side data anywhere. That closes the grain-migration
re-encode route: decode a grainy master with the parameters exported, degrain
the pictures, and hand them to an encoder that carries the parameters through.
The playback side then synthesises the grain the master was made with, the
pictures travel through the encode clean, and the parameters stay available
for further downstream use. This patch makes av1_nvenc the first encoder with
that passthrough. The other face of this work - authoring parameters out of
band and injecting them without input side data - is complementary and not
part of this patch.

ffnvcodec 13.1 (NVENCAPI_MAJOR/MINOR = 13/1, nvEncodeAPI.h:118-119) declares
the full AV1 film grain face of the NVENC API, so no SDK bump is needed:

- NV_ENC_FILM_GRAIN_PARAMS_AV1, the parameter set carrier
  (nvEncodeAPI.h:2041-2071). It has no grain_seed field; the driver invents
  the seed itself.
- NV_ENC_CONFIG_AV1::enableFilmGrainParams (nvEncodeAPI.h:2093), the
  session-level switch; filmGrainParams (nvEncodeAPI.h:2130) must point at a
  parameter set that stays alive for the whole encoder session.
- NV_ENC_PIC_PARAMS_AV1::filmGrainParamsUpdate (nvEncodeAPI.h:2530), the
  per-frame "this frame carries a new parameter set" flag, and
  NV_ENC_PIC_PARAMS_AV1::filmGrainParams (nvEncodeAPI.h:2551), where that set
  is handed over.

The patch uses both layers: sequence-level enableFilmGrainParams=1 with a
default parameter set signalled from the sequence header onwards, and
per-frame filmGrainParamsUpdate=1 whenever the current frame carries AV1
film grain side data. A frame without side data leaves the update flag at 0,
which is exactly the bitstream's own update_grain inheritance semantics: the
previous parameter set keeps applying.

The change is 3 files, +263/-0, purely additive, guarded by
NVENC_HAVE_AV1_FILM_GRAIN_PARAMS (defined in the ffnvcodec 13.1 branch of
nvenc.h, with a note that the floor can be lowered without any other change
if older headers turn out to declare these fields too):

1. Conversion AVFilmGrainAOMParams -> NV_ENC_FILM_GRAIN_PARAMS_AV1. Full
   field mapping plus the biases the decoders removed:
   AVFilmGrainAOMParams stores auto-regressive coefficients and chroma
   multipliers de-biased as signed values (dav1d/aom: mult = raw-128,
   offset = raw-256) while NVENC wants the raw syntax values, so the patch
   re-applies +128 on the AR coefficients and on the chroma
   mult/luma_mult and +256 on the chroma offsets, and derives
   grainScalingMinus8 = scaling_shift - 8, arCoeffShiftMinus6 =
   ar_coeff_shift - 6 and the num_pos_luma/num_pos_chroma slot counts from
   ar_coeff_lag. Array slots beyond num_pos_* stay at the neutral value 128
   (coefficient 0) so a reused scratch structure can never leak a stale
   coefficient. Masking the chroma offsets with 0x1FF (two's complement) or
   clipping them to 0 would destroy the negative values and silently corrupt
   chroma grain on the passthrough route - that lesson is carried as a
   comment where the bias is applied.
2. Per-frame consumption in nvenc_send_frame(): guard on AV1 codec id and
   -filmgrain (return immediately otherwise), look up
   AV_FRAME_DATA_FILM_GRAIN_PARAMS on the frame, return without touching
   anything when it is absent (inheritance semantics), warn and ignore
   non-AV1-type parameters (H.274 side data), and otherwise convert and set
   filmGrainParamsUpdate=1 with the new parameter set.
3. A sequence-level default parameter set: a mild but legal grain verified on
   hardware to be accepted by nvEncInitializeEncoder and to land verbatim in
   the emitted film_grain_params syntax element, so a run that forgot to
   feed side data still produces a sane stream instead of a broken one. An
   all-zero set was rejected deliberately: no such set was ever exercised on
   real hardware, and the driver picks the seed anyway, so the "invisible"
   default buys nothing.
4. Session wiring in nvenc_setup_av1_config(): with -filmgrain,
   enableFilmGrainParams=1, filmGrainParams points at the context-resident
   parameter set (it must outlive the session), and chromaSamplePosition
   falls back to 1 inside the same branch, because NVENC requires all AV1
   VUI colour fields to be non-zero and this is the only one nvenc does not
   derive from the AVCodecContext.
5. The -filmgrain boolean option on av1_nvenc, default off. Its help text
   documents the three contracts: NVENC has no analysis leg, so the
   parameters come only from the side data; the master must be degrained
   beforehand, otherwise grain is applied twice; and grain_seed is
   driver-generated, so regression comparisons must read bitstream fields,
   never file hashes.

The option defaults to off, so nothing changes for existing users of
av1_nvenc: -h encoder=av1_nvenc reports it as "(default false)", and a
negative-control encode without -filmgrain produces a stream whose sequence
header has film_grain_params_present = 0 and whose frames carry no film
grain at all.

## Testing

Verified on RTX 4060 Laptop GPU, driver 621.01, ffnvcodec 13.1 headers, with
a bitstream-level dump/compare harness (field assertions, no hash
comparisons):

- decode baseline: the reference stream dumped in both hw (NVDEC) and sw
  (libdav1d) modes reproduces the historical reference logs byte-for-byte;
- injection: ffmpeg -export_side_data film_grain -i master.ivf -c:v av1_nvenc
  -filmgrain 1 out.ivf encodes 48/48 frames, exit 0, no NVENC warnings;
- bitstream field comparison (trace_headers): the bias round-trip passes line
  by line - uv_mult[cb] -27 -> cb_mult 101 (+128), uv_mult_luma[cb] -24 ->
  cb_luma_mult 104, uv_offset[cb] -153 -> cb_offset 103 (+256), uv_mult[cr]
  -26 -> cr_mult 102, uv_offset[cr] -150 -> cr_offset 106; the AR coefficient
  rows read back 129,133,...,173 / 111..123 / 151..163; point tables and
  structural fields (grain_scaling_minus_8=2, ar_coeff_lag=2,
  ar_coeff_shift_minus_6=2, grain_scale_shift=1, overlap_flag=1,
  clip_to_restricted_range=0) all verbatim. 48/48 frames carry
  film_grain_params and the sequence header has film_grain_params_present=1.
  The negative sentinels hold across all four test streams: no 0x1FF-masking
  artefacts (the historical bug produced 456 for a -153 offset) and no
  clipped-to-0 offsets - cb_offset/cr_offset are 103/106 throughout;
- per-frame inheritance: a concat of 24 frames with side data and 48 without,
  encoded once with -filmgrain 1, gives 72/72 frames with exit 0 and 71/71
  INTER frames with update_grain = 0 reusing the previous parameter set - the
  bitstream inheritance semantics work as specified;
- sequence-level default: encoding without any side data lands the documented
  default set in the KEY frame's film_grain_params (every value matching the
  table in the patch) and all 48 frames decode without error;
- negative control: the same input encoded without -filmgrain decodes 5/5
  frames as FILM_GRAIN_COUNT=0 ABSENT, distinguishing "grain carried" from
  "grain absent".

## Film grain behaviour observed on the verification driver

Two driver-side behaviours on driver 621.01 are recorded verbatim; both are
consistent with the ffnvcodec 13.1 contract and neither is a defect of this
patch:

- The per-frame filmGrainParamsUpdate=1 path is not observable in the
  bitstream on this driver: streams encoded from inputs where every frame
  carries side data, from an input where none does, and from a mixed input
  all show the same per-count film grain block shape. Instrumenting the
  ffmpeg side confirms the guard chain passes, the side data is present on
  every encoder frame and the update flag is set; a -filmgrain 0 control
  rules out the driver inheriting parameters from CUDA surface metadata
  automatically. The sequence-level parameter set and the bitstream's
  update_grain inheritance semantics work as specified throughout.
- grain_seed is deterministically derived by this driver from the input pts:
  the seed sequences of three independently encoded streams match frame for
  frame, and their value set matches the input side data's seeds with the
  order permuted. The "two encodes never produce identical bytes" rationale
  in the option help text therefore does not hold on this driver; the rule
  it motivates (compare bitstream fields, never file hashes) stays the right
  one.

## Limitations

- AV1 (AOM) parameters only. H.274-type film grain side data is warned about
  and ignored, and the sequence-level default set is AV1-specific.
- Verified on one hardware/driver combination (RTX 4060 Laptop GPU,
  driver 621.01). The bitstream visibility of the per-frame update flag and
  the seed derivation noted above are driver implementation details and may
  differ across driver versions; the sequence-level path and the field-level
  bitstream contract are what this patch can guarantee.
- Verification environment: with a win32 toolchain FFmpeg's configure writes
  all of its ffconf temporary files with relative paths into the source tree
  ("Use a relative path for TMPDIR", configure:4975-4981), so the source
  directory has to be readable and writable in place for the build checks;
  on an msys64 host TMPDIR additionally has to point to a Windows-native
  path or configure aborts with "Unable to create temporary file".


>From d28ad5ee29802e83de08c2ad06372137f088148d Mon Sep 17 00:00:00 2001
From: FGS Research Team <[email protected]>
Date: Wed, 14 Oct 2026 00:00:00 +0800
Subject: [PATCH] nvenc: add AV1 film grain side-data consumer (-filmgrain)

Add the AV1 film grain side-data consumer for av1_nvenc:
  - register -filmgrain (bool, default off)
  - per-frame: read AV_FRAME_DATA_FILM_GRAIN_PARAMS side data, fill
    NV_ENC_PIC_PARAMS_AV1.filmGrainParams and set filmGrainParamsUpdate=1
  - sequence-level default set when no side data is present
  - convert AVFilmGrainAOMParams -> NV_ENC_FILM_GRAIN_PARAMS_AV1, re-applying
    the decoder's bias so the bitstream round-trips: AR coeffs +128,
    chroma mult/luma_mult +128, chroma offset +256 (matches dav1d/aom, which
    store these de-biased as signed values). Using two's-complement masking
    or clipping here corrupts negative chroma values on the passthrough route.
NVENC has no analysis leg; the parameters come only from side data.
---
 libavcodec/nvenc.c     | 236 +++++++++++++++++++++++++++++++++++++++++
 libavcodec/nvenc.h     |  18 ++++
 libavcodec/nvenc_av1.c |   9 ++
 3 files changed, 263 insertions(+)

diff --git a/libavcodec/nvenc.c b/libavcodec/nvenc.c
index 9a4e84f870b..89e8b06571d 100644
--- a/libavcodec/nvenc.c
+++ b/libavcodec/nvenc.c
@@ -31,6 +31,7 @@
 #include "libavutil/hwcontext_cuda.h"
 #include "libavutil/hwcontext.h"
 #include "libavutil/cuda_check.h"
+#include "libavutil/film_grain_params.h"
 #include "libavutil/imgutils.h"
 #include "libavutil/mem.h"
 #include "libavutil/pixdesc.h"
@@ -1524,7 +1525,206 @@ static av_cold int 
nvenc_setup_hevc_config(AVCodecContext *avctx)
     return 0;
 }
 
+#ifdef NVENC_HAVE_AV1_FILM_GRAIN_PARAMS
+/*
+ * AVFilmGrainAOMParams -> NV_ENC_FILM_GRAIN_PARAMS_AV1.
+ *
+ * Two biases have to be undone on the way in:
+ *   - NVENC stores the auto-regressive coefficients as an unsigned
+ *     "coefficient + 128" byte (arCoeffs*Plus128), AVFilmGrainAOMParams keeps
+ *     the signed coefficient;
+ *   - the chroma scaling function offsets are an su(9) syntax element which
+ *     NVENC keeps as the raw 9 bit word inside a uint16_t. Masking with 0x1FF
+ *     is the identity for the [0, 511] raw values some decoders export and
+ *     gives the two's complement word for the signed [-256, 255] values that
+ *     others do, so it is correct for both conventions.
+ *
+ * The number of coefficients per plane follows the bitstream syntax:
+ *   num_pos_luma   = 2 * ar_coeff_lag * (ar_coeff_lag + 1)
+ *   num_pos_chroma = num_pos_luma + (num_y_points > 0)
+ * Only those leading entries are consumed by the driver; the remaining array
+ * slots are kept at the neutral value 128 (coefficient 0) so that a reused
+ * scratch structure can never leak a stale coefficient.
+ */
+static void nvenc_av1_film_grain_params(NV_ENC_FILM_GRAIN_PARAMS_AV1 *nv,
+                                        const AVFilmGrainParams *fgp)
+{
+    const AVFilmGrainAOMParams *aom = &fgp->codec.aom;
+    const int ar_coeff_lag   = av_clip(aom->ar_coeff_lag, 0, 3);
+    const int num_y_points   = av_clip(aom->num_y_points,     0, 
FF_ARRAY_ELEMS(nv->pointYValue));
+    const int num_pos_luma   = 2 * ar_coeff_lag * (ar_coeff_lag + 1);
+    const int num_pos_chroma = num_pos_luma + (num_y_points > 0);
+    int i;
+
+    nv->applyGrain            = 1;
+    nv->chromaScalingFromLuma = aom->chroma_scaling_from_luma;
+    nv->overlapFlag           = aom->overlap_flag;
+    nv->clipToRestrictedRange = aom->limit_output_range;
+
+    /* NVENC keeps the raw syntax values, AVFilmGrainAOMParams the decoded 
ones */
+    nv->grainScalingMinus8 = av_clip(aom->scaling_shift - 8, 0, 3);
+    nv->arCoeffLag         = ar_coeff_lag;
+    nv->arCoeffShiftMinus6 = av_clip(aom->ar_coeff_shift - 6, 0, 3);
+    nv->grainScaleShift    = av_clip(aom->grain_scale_shift, 0, 3);
+
+    nv->numYPoints  = num_y_points;
+    nv->numCbPoints = av_clip(aom->num_uv_points[0], 0, 
FF_ARRAY_ELEMS(nv->pointCbValue));
+    nv->numCrPoints = av_clip(aom->num_uv_points[1], 0, 
FF_ARRAY_ELEMS(nv->pointCrValue));
+
+    for (i = 0; i < nv->numYPoints; i++) {
+        nv->pointYValue[i]   = aom->y_points[i][0];
+        nv->pointYScaling[i] = aom->y_points[i][1];
+    }
+    for (i = 0; i < nv->numCbPoints; i++) {
+        nv->pointCbValue[i]   = aom->uv_points[0][i][0];
+        nv->pointCbScaling[i] = aom->uv_points[0][i][1];
+    }
+    for (i = 0; i < nv->numCrPoints; i++) {
+        nv->pointCrValue[i]   = aom->uv_points[1][i][0];
+        nv->pointCrScaling[i] = aom->uv_points[1][i][1];
+    }
+
+    for (i = 0; i < FF_ARRAY_ELEMS(nv->arCoeffsYPlus128); i++)
+        nv->arCoeffsYPlus128[i]  = 128;
+    for (i = 0; i < FF_ARRAY_ELEMS(nv->arCoeffsCbPlus128); i++)
+        nv->arCoeffsCbPlus128[i] = 128;
+    for (i = 0; i < FF_ARRAY_ELEMS(nv->arCoeffsCrPlus128); i++)
+        nv->arCoeffsCrPlus128[i] = 128;
+
+    for (i = 0; i < num_pos_luma && i < FF_ARRAY_ELEMS(nv->arCoeffsYPlus128); 
i++)
+        nv->arCoeffsYPlus128[i] = (uint8_t)(aom->ar_coeffs_y[i] + 128);
+    for (i = 0; i < num_pos_chroma && i < 
FF_ARRAY_ELEMS(nv->arCoeffsCbPlus128); i++)
+        nv->arCoeffsCbPlus128[i] = (uint8_t)(aom->ar_coeffs_uv[0][i] + 128);
+    for (i = 0; i < num_pos_chroma && i < 
FF_ARRAY_ELEMS(nv->arCoeffsCrPlus128); i++)
+        nv->arCoeffsCrPlus128[i] = (uint8_t)(aom->ar_coeffs_uv[1][i] + 128);
+
+    /* Chroma scaling-function coefficients are stored de-biased (signed) in
+     * AVFilmGrainAOMParams (dav1d/aom: mult = raw-128, offset = raw-256), 
while
+     * NVENC wants the raw syntax values. Re-apply the same bias the decoder
+     * removed, exactly as done for the +128 AR coefficients above. Masking
+     * with 0x1FF (two's complement) or clipping to 0 would destroy negative
+     * values and silently corrupt chroma grain on the passthrough/Path A 
route. */
+    nv->cbMult     = (uint8_t)av_clip(aom->uv_mult[0]     + 128, 0, 255);
+    nv->cbLumaMult = (uint8_t)av_clip(aom->uv_mult_luma[0] + 128, 0, 255);
+    nv->cbOffset   = (uint16_t)av_clip(aom->uv_offset[0]   + 256, 0, 511);
+    nv->crMult     = (uint8_t)av_clip(aom->uv_mult[1]     + 128, 0, 255);
+    nv->crLumaMult = (uint8_t)av_clip(aom->uv_mult_luma[1] + 128, 0, 255);
+    nv->crOffset   = (uint16_t)av_clip(aom->uv_offset[1]   + 256, 0, 511);
+}
+
+/*
+ * Per frame path: NVENC has no analysis leg at all, so it can neither estimate
+ * nor carry film grain parameters on its own - they have to come from outside.
+ * We take them from the AV_FRAME_DATA_FILM_GRAIN_PARAMS side data of the input
+ * frame (which is what a decoding pass of a grainy master, or libaom's
+ * --denoise-noise-level analysis, exports) and ask the encoder to signal an
+ * updated parameter set in the current frame header.
+ *
+ * If the side data is missing, the update flag is left alone so that the
+ * encoder keeps signalling the previous parameter set - which is exactly how
+ * the bitstream itself inherits film grain parameters across frames.
+ *
+ * NOTE: grain_seed is not part of the API; the driver invents it per frame and
+ * per render, so two encodes of the same input with the same parameters never
+ * produce identical bytes. Any regression comparison must read the bitstream
+ * fields, never compare file hashes.
+ */
+static int nvenc_set_av1_film_grain_params(AVCodecContext *avctx, 
NV_ENC_PIC_PARAMS *pic_params,
+                                           NV_ENC_FILM_GRAIN_PARAMS_AV1 
*film_grain_params,
+                                           const AVFrame *frame)
+{
+    NvencContext *ctx = avctx->priv_data;
+    const AVFrameSideData *sd;
+    const AVFilmGrainParams *fgp;
+
+    if (avctx->codec->id != AV_CODEC_ID_AV1 || !ctx->filmgrain)
+        return 0;
+
+    sd = av_frame_get_side_data(frame, AV_FRAME_DATA_FILM_GRAIN_PARAMS);
+    if (!sd)
+        return 0;
+
+    fgp = (const AVFilmGrainParams *)sd->data;
+    if (fgp->type != AV_FILM_GRAIN_PARAMS_AV1) {
+        av_log(avctx, AV_LOG_WARNING,
+               "Ignoring film grain side data of unsupported type %d\n", 
fgp->type);
+        return 0;
+    }
+
+    nvenc_av1_film_grain_params(film_grain_params, fgp);
+
+    pic_params->codecPicParams.av1PicParams.filmGrainParamsUpdate = 1;
+    pic_params->codecPicParams.av1PicParams.filmGrainParams      = 
film_grain_params;
+
+    return 0;
+}
+#endif
+
 #if CONFIG_AV1_NVENC_ENCODER
+#ifdef NVENC_HAVE_AV1_FILM_GRAIN_PARAMS
+/*
+ * Sequence level default: the parameter set that is signalled from the
+ * sequence header onwards, until the first frame that carries
+ * AV_FRAME_DATA_FILM_GRAIN_PARAMS side data takes over.
+ *
+ * These are exactly the values the hardware probe (Ada/4060, driver 13.1)
+ * verified to be accepted by nvEncInitializeEncoder and to land verbatim in
+ * the emitted film_grain_params syntax element - apply_grain=1,
+ * grain_scaling_minus_8=2, ar_coeff_lag=2, 3 luma / 2+2 chroma points,
+ * 129..165 luma and 111..120 / 151..160 chroma AR coefficients. They form a
+ * deliberately mild grain (overlap on, no restricted range clipping) so that
+ * a run that forgot to feed side data still produces a sane, legal stream
+ * instead of a broken one. An all-zero set would have been the other obvious
+ * choice, but no such set was ever exercised on real hardware, and grain_seed
+ * is picked by the driver anyway, so there is nothing to gain from the
+ * "invisible" default.
+ */
+static void nvenc_av1_film_grain_default(NV_ENC_FILM_GRAIN_PARAMS_AV1 *nv)
+{
+    int i;
+
+    memset(nv, 0, sizeof(*nv));
+
+    nv->applyGrain            = 1;
+    nv->chromaScalingFromLuma = 0;
+    nv->overlapFlag           = 1;
+    nv->clipToRestrictedRange = 0;
+    nv->grainScalingMinus8    = 2;
+    nv->arCoeffLag            = 2;
+    nv->arCoeffShiftMinus6    = 2;
+    nv->grainScaleShift       = 1;
+
+    nv->numYPoints  = 3;
+    nv->numCbPoints = 2;
+    nv->numCrPoints = 2;
+
+    nv->pointYValue[0] = 17;  nv->pointYScaling[0] = 9;
+    nv->pointYValue[1] = 85;  nv->pointYScaling[1] = 41;
+    nv->pointYValue[2] = 213; nv->pointYScaling[2] = 202;
+
+    nv->pointCbValue[0] = 23;  nv->pointCbScaling[0] = 31;
+    nv->pointCbValue[1] = 199; nv->pointCbScaling[1] = 187;
+
+    nv->pointCrValue[0] = 43;  nv->pointCrScaling[0] = 53;
+    nv->pointCrValue[1] = 177; nv->pointCrScaling[1] = 167;
+
+    /* ar_coeff_lag = 2: 12 luma coefficients, 13 chroma coefficients */
+    for (i = 0; i < FF_ARRAY_ELEMS(nv->arCoeffsYPlus128); i++)
+        nv->arCoeffsYPlus128[i]  = (i < 12) ? (uint8_t)(129 + 4 * i) : 128;
+    for (i = 0; i < FF_ARRAY_ELEMS(nv->arCoeffsCbPlus128); i++)
+        nv->arCoeffsCbPlus128[i] = (i < 13) ? (uint8_t)(111 + i) : 128;
+    for (i = 0; i < FF_ARRAY_ELEMS(nv->arCoeffsCrPlus128); i++)
+        nv->arCoeffsCrPlus128[i] = (i < 13) ? (uint8_t)(151 + i) : 128;
+
+    nv->cbMult     = 101;
+    nv->cbLumaMult = 104;
+    nv->cbOffset   = 103;
+    nv->crMult     = 102;
+    nv->crLumaMult = 105;
+    nv->crOffset   = 106;
+}
+#endif
+
 static av_cold int nvenc_setup_av1_config(AVCodecContext *avctx)
 {
     NvencContext *ctx      = avctx->priv_data;
@@ -1632,6 +1832,33 @@ static av_cold int nvenc_setup_av1_config(AVCodecContext 
*avctx)
     }
 #endif
 
+#ifdef NVENC_HAVE_AV1_FILM_GRAIN_PARAMS
+    /*
+     * AV1 film grain signalling. NVENC never analyses the input and never
+     * denoises it, so the parameter set has to be supplied from outside - the
+     * per frame side data, see nvenc_set_av1_film_grain_params(). Everything
+     * before the first frame that carries such side data is signalled with the
+     * sequence level default below.
+     *
+     * The master has to be degrained before it reaches this encoder: NVENC
+     * synthesises grain from the parameter set on top of whatever is already
+     * baked into the pixels, so a grainy input would end up with grain applied
+     * twice.
+     */
+    if (ctx->filmgrain) {
+        nvenc_av1_film_grain_default(&ctx->film_grain_params);
+        av1->enableFilmGrainParams = 1;
+        av1->filmGrainParams      = &ctx->film_grain_params;
+
+        /* The AV1 VUI colour fields must all be non-zero for NVENC, and
+         * chromaSamplePosition is the only one nvenc does not derive from the
+         * AVCodecContext. 1 is the variant that is co-sitted horizontally,
+         * which is what the hardware probe used. */
+        if (!av1->chromaSamplePosition)
+            av1->chromaSamplePosition = 1;
+    }
+#endif
+
     return 0;
 }
 #endif
@@ -3053,6 +3280,9 @@ static int nvenc_send_frame(AVCodecContext *avctx, const 
AVFrame *frame)
 #ifdef NVENC_HAVE_MVHEVC
     HEVC_3D_REFERENCE_DISPLAY_INFO ref_disp_info = { 0 };
 #endif
+#ifdef NVENC_HAVE_AV1_FILM_GRAIN_PARAMS
+    NV_ENC_FILM_GRAIN_PARAMS_AV1 film_grain_params = { 0 };
+#endif
 
     NvencContext *ctx = avctx->priv_data;
     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
@@ -3123,6 +3353,12 @@ static int nvenc_send_frame(AVCodecContext *avctx, const 
AVFrame *frame)
             return res;
 #endif
 
+#ifdef NVENC_HAVE_AV1_FILM_GRAIN_PARAMS
+        res = nvenc_set_av1_film_grain_params(avctx, &pic_params, 
&film_grain_params, frame);
+        if (res < 0)
+            return res;
+#endif
+
 #ifdef NVENC_HAVE_MVHEVC
         if (ctx->multiview) {
             const AVFrameSideData *sd_tdrdi = av_frame_get_side_data(frame, 
AV_FRAME_DATA_3D_REFERENCE_DISPLAYS);
diff --git a/libavcodec/nvenc.h b/libavcodec/nvenc.h
index 7bb74a17a98..e87a7e14454 100644
--- a/libavcodec/nvenc.h
+++ b/libavcodec/nvenc.h
@@ -79,8 +79,17 @@ typedef void ID3D11Device;
 #define NVENC_NEW_COUNTING_TYPE
 #define NVENC_HAVE_AV1_HGOP_SUPPORT
 #define NVENC_HAVE_CUDA_ARRAY_INPUT_SUPPORT
+#define NVENC_HAVE_AV1_FILM_GRAIN_PARAMS
 #endif
 
+// NOTE: NVENC_HAVE_AV1_FILM_GRAIN_PARAMS guards the AV1 film grain support of
+// this encoder (-filmgrain). 13.1 is the version of the ffnvcodec header the
+// feature was developed and verified against; if the film grain fields
+// (NV_ENC_CONFIG_AV1::enableFilmGrainParams / filmGrainParams,
+// NV_ENC_PIC_PARAMS_AV1::filmGrainParamsUpdate / filmGrainParams and
+// NV_ENC_FILM_GRAIN_PARAMS_AV1) turn out to be declared by older headers too,
+// this floor can be lowered without any other change.
+
 typedef struct NvencSurface
 {
     NV_ENC_INPUT_PTR input_surface;
@@ -277,6 +286,15 @@ typedef struct NvencContext
     int cbr_padding;
     int multiview, multiview_supported;
     int display_sei_sent;
+#ifdef NVENC_HAVE_AV1_FILM_GRAIN_PARAMS
+    int filmgrain;
+    /*
+     * Sequence level AV1 film grain parameters. This lives in the context and
+     * not in a local because NV_ENC_CONFIG_AV1::filmGrainParams points at it
+     * for the whole lifetime of the encoder session.
+     */
+    NV_ENC_FILM_GRAIN_PARAMS_AV1 film_grain_params;
+#endif
 } NvencContext;
 
 int ff_nvenc_encode_init(AVCodecContext *avctx);
diff --git a/libavcodec/nvenc_av1.c b/libavcodec/nvenc_av1.c
index b687260ef76..31b5a0d7c9f 100644
--- a/libavcodec/nvenc_av1.c
+++ b/libavcodec/nvenc_av1.c
@@ -162,6 +162,15 @@ static const AVOption options[] = {
                                                             OFFSET(extra_sei), 
   AV_OPT_TYPE_BOOL,  { .i64 = 1 }, 0, 1, VE },
     { "a53cc",        "Use A53 Closed Captions (if available)", 
OFFSET(a53_cc),   AV_OPT_TYPE_BOOL,  { .i64 = 1 }, 0, 1, VE },
     { "s12m_tc",      "Use timecode (if available)",        OFFSET(s12m_tc),   
   AV_OPT_TYPE_BOOL,  { .i64 = 1 }, 0, 1, VE },
+#ifdef NVENC_HAVE_AV1_FILM_GRAIN_PARAMS
+    { "filmgrain",    "Signal AV1 film grain parameters. NVENC has no analysis 
leg, so the parameters are read "
+                      "from the AV_FRAME_DATA_FILM_GRAIN_PARAMS side data of 
each input frame (a decoding pass "
+                      "of a grainy master, or libaom --denoise-noise-level, 
produces it); frames without such "
+                      "side data keep the previous parameter set. The master 
must be degrained beforehand, "
+                      "otherwise grain is applied twice. grain_seed is 
invented by the driver, so two runs are "
+                      "never byte-identical - compare bitstream fields, not 
file hashes.",
+                                                             
OFFSET(filmgrain),   AV_OPT_TYPE_BOOL,  { .i64 = 0 }, 0, 1, VE },
+#endif
     { "cbr_padding",  "Pad the bitstream to ensure bitrate does not drop below 
the target in CBR mode",
                                                             
OFFSET(cbr_padding),  AV_OPT_TYPE_BOOL,  { .i64 = 0 }, 0, 1, VE },
 #ifdef NVENC_HAVE_H264_AND_AV1_TEMPORAL_FILTER
-- 
2.54.0

_______________________________________________
ffmpeg-devel mailing list -- [email protected]
To unsubscribe send an email to [email protected]

Reply via email to