2 * H.264/HEVC hardware encoding using nvidia nvenc
3 * Copyright (c) 2016 Timo Rothenpieler <timo@rothenpieler.org>
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 #include "libavutil/hwcontext_cuda.h"
27 #include "libavutil/hwcontext.h"
28 #include "libavutil/cuda_check.h"
29 #include "libavutil/imgutils.h"
30 #include "libavutil/avassert.h"
31 #include "libavutil/mem.h"
32 #include "libavutil/pixdesc.h"
35 #define CHECK_CU(x) FF_CUDA_CHECK_DL(avctx, dl_fn->cuda_dl, x)
37 #define NVENC_CAP 0x30
38 #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR || \
39 rc == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ || \
40 rc == NV_ENC_PARAMS_RC_CBR_HQ)
42 const enum AVPixelFormat ff_nvenc_pix_fmts[] = {
47 AV_PIX_FMT_P016, // Truncated to 10bits
48 AV_PIX_FMT_YUV444P16, // Truncated to 10bits
58 #define IS_10BIT(pix_fmt) (pix_fmt == AV_PIX_FMT_P010 || \
59 pix_fmt == AV_PIX_FMT_P016 || \
60 pix_fmt == AV_PIX_FMT_YUV444P16)
62 #define IS_YUV444(pix_fmt) (pix_fmt == AV_PIX_FMT_YUV444P || \
63 pix_fmt == AV_PIX_FMT_YUV444P16)
70 { NV_ENC_SUCCESS, 0, "success" },
71 { NV_ENC_ERR_NO_ENCODE_DEVICE, AVERROR(ENOENT), "no encode device" },
72 { NV_ENC_ERR_UNSUPPORTED_DEVICE, AVERROR(ENOSYS), "unsupported device" },
73 { NV_ENC_ERR_INVALID_ENCODERDEVICE, AVERROR(EINVAL), "invalid encoder device" },
74 { NV_ENC_ERR_INVALID_DEVICE, AVERROR(EINVAL), "invalid device" },
75 { NV_ENC_ERR_DEVICE_NOT_EXIST, AVERROR(EIO), "device does not exist" },
76 { NV_ENC_ERR_INVALID_PTR, AVERROR(EFAULT), "invalid ptr" },
77 { NV_ENC_ERR_INVALID_EVENT, AVERROR(EINVAL), "invalid event" },
78 { NV_ENC_ERR_INVALID_PARAM, AVERROR(EINVAL), "invalid param" },
79 { NV_ENC_ERR_INVALID_CALL, AVERROR(EINVAL), "invalid call" },
80 { NV_ENC_ERR_OUT_OF_MEMORY, AVERROR(ENOMEM), "out of memory" },
81 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED, AVERROR(EINVAL), "encoder not initialized" },
82 { NV_ENC_ERR_UNSUPPORTED_PARAM, AVERROR(ENOSYS), "unsupported param" },
83 { NV_ENC_ERR_LOCK_BUSY, AVERROR(EAGAIN), "lock busy" },
84 { NV_ENC_ERR_NOT_ENOUGH_BUFFER, AVERROR_BUFFER_TOO_SMALL, "not enough buffer"},
85 { NV_ENC_ERR_INVALID_VERSION, AVERROR(EINVAL), "invalid version" },
86 { NV_ENC_ERR_MAP_FAILED, AVERROR(EIO), "map failed" },
87 { NV_ENC_ERR_NEED_MORE_INPUT, AVERROR(EAGAIN), "need more input" },
88 { NV_ENC_ERR_ENCODER_BUSY, AVERROR(EAGAIN), "encoder busy" },
89 { NV_ENC_ERR_EVENT_NOT_REGISTERD, AVERROR(EBADF), "event not registered" },
90 { NV_ENC_ERR_GENERIC, AVERROR_UNKNOWN, "generic error" },
91 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY, AVERROR(EINVAL), "incompatible client key" },
92 { NV_ENC_ERR_UNIMPLEMENTED, AVERROR(ENOSYS), "unimplemented" },
93 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO), "resource register failed" },
94 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED, AVERROR(EBADF), "resource not registered" },
95 { NV_ENC_ERR_RESOURCE_NOT_MAPPED, AVERROR(EBADF), "resource not mapped" },
98 static int nvenc_map_error(NVENCSTATUS err, const char **desc)
101 for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
102 if (nvenc_errors[i].nverr == err) {
104 *desc = nvenc_errors[i].desc;
105 return nvenc_errors[i].averr;
109 *desc = "unknown error";
110 return AVERROR_UNKNOWN;
113 static int nvenc_print_error(void *log_ctx, NVENCSTATUS err,
114 const char *error_string)
118 ret = nvenc_map_error(err, &desc);
119 av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
123 static void nvenc_print_driver_requirement(AVCodecContext *avctx, int level)
125 #if NVENCAPI_CHECK_VERSION(9, 2)
126 const char *minver = "(unknown)";
127 #elif NVENCAPI_CHECK_VERSION(9, 1)
128 # if defined(_WIN32) || defined(__CYGWIN__)
129 const char *minver = "436.15";
131 const char *minver = "435.21";
133 #elif NVENCAPI_CHECK_VERSION(9, 0)
134 # if defined(_WIN32) || defined(__CYGWIN__)
135 const char *minver = "418.81";
137 const char *minver = "418.30";
139 #elif NVENCAPI_CHECK_VERSION(8, 2)
140 # if defined(_WIN32) || defined(__CYGWIN__)
141 const char *minver = "397.93";
143 const char *minver = "396.24";
145 #elif NVENCAPI_CHECK_VERSION(8, 1)
146 # if defined(_WIN32) || defined(__CYGWIN__)
147 const char *minver = "390.77";
149 const char *minver = "390.25";
152 # if defined(_WIN32) || defined(__CYGWIN__)
153 const char *minver = "378.66";
155 const char *minver = "378.13";
158 av_log(avctx, level, "The minimum required Nvidia driver for nvenc is %s or newer\n", minver);
161 static av_cold int nvenc_load_libraries(AVCodecContext *avctx)
163 NvencContext *ctx = avctx->priv_data;
164 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
166 uint32_t nvenc_max_ver;
169 ret = cuda_load_functions(&dl_fn->cuda_dl, avctx);
173 ret = nvenc_load_functions(&dl_fn->nvenc_dl, avctx);
175 nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
179 err = dl_fn->nvenc_dl->NvEncodeAPIGetMaxSupportedVersion(&nvenc_max_ver);
180 if (err != NV_ENC_SUCCESS)
181 return nvenc_print_error(avctx, err, "Failed to query nvenc max version");
183 av_log(avctx, AV_LOG_VERBOSE, "Loaded Nvenc version %d.%d\n", nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
185 if ((NVENCAPI_MAJOR_VERSION << 4 | NVENCAPI_MINOR_VERSION) > nvenc_max_ver) {
186 av_log(avctx, AV_LOG_ERROR, "Driver does not support the required nvenc API version. "
187 "Required: %d.%d Found: %d.%d\n",
188 NVENCAPI_MAJOR_VERSION, NVENCAPI_MINOR_VERSION,
189 nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
190 nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
191 return AVERROR(ENOSYS);
194 dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
196 err = dl_fn->nvenc_dl->NvEncodeAPICreateInstance(&dl_fn->nvenc_funcs);
197 if (err != NV_ENC_SUCCESS)
198 return nvenc_print_error(avctx, err, "Failed to create nvenc instance");
200 av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
205 static int nvenc_push_context(AVCodecContext *avctx)
207 NvencContext *ctx = avctx->priv_data;
208 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
210 if (ctx->d3d11_device)
213 return CHECK_CU(dl_fn->cuda_dl->cuCtxPushCurrent(ctx->cu_context));
216 static int nvenc_pop_context(AVCodecContext *avctx)
218 NvencContext *ctx = avctx->priv_data;
219 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
222 if (ctx->d3d11_device)
225 return CHECK_CU(dl_fn->cuda_dl->cuCtxPopCurrent(&dummy));
228 static av_cold int nvenc_open_session(AVCodecContext *avctx)
230 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
231 NvencContext *ctx = avctx->priv_data;
232 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
235 params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
236 params.apiVersion = NVENCAPI_VERSION;
237 if (ctx->d3d11_device) {
238 params.device = ctx->d3d11_device;
239 params.deviceType = NV_ENC_DEVICE_TYPE_DIRECTX;
241 params.device = ctx->cu_context;
242 params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
245 ret = p_nvenc->nvEncOpenEncodeSessionEx(¶ms, &ctx->nvencoder);
246 if (ret != NV_ENC_SUCCESS) {
247 ctx->nvencoder = NULL;
248 return nvenc_print_error(avctx, ret, "OpenEncodeSessionEx failed");
254 static int nvenc_check_codec_support(AVCodecContext *avctx)
256 NvencContext *ctx = avctx->priv_data;
257 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
258 int i, ret, count = 0;
261 ret = p_nvenc->nvEncGetEncodeGUIDCount(ctx->nvencoder, &count);
263 if (ret != NV_ENC_SUCCESS || !count)
264 return AVERROR(ENOSYS);
266 guids = av_malloc(count * sizeof(GUID));
268 return AVERROR(ENOMEM);
270 ret = p_nvenc->nvEncGetEncodeGUIDs(ctx->nvencoder, guids, count, &count);
271 if (ret != NV_ENC_SUCCESS) {
272 ret = AVERROR(ENOSYS);
276 ret = AVERROR(ENOSYS);
277 for (i = 0; i < count; i++) {
278 if (!memcmp(&guids[i], &ctx->init_encode_params.encodeGUID, sizeof(*guids))) {
290 static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
292 NvencContext *ctx = avctx->priv_data;
293 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
294 NV_ENC_CAPS_PARAM params = { 0 };
297 params.version = NV_ENC_CAPS_PARAM_VER;
298 params.capsToQuery = cap;
300 ret = p_nvenc->nvEncGetEncodeCaps(ctx->nvencoder, ctx->init_encode_params.encodeGUID, ¶ms, &val);
302 if (ret == NV_ENC_SUCCESS)
307 static int nvenc_check_capabilities(AVCodecContext *avctx)
309 NvencContext *ctx = avctx->priv_data;
312 ret = nvenc_check_codec_support(avctx);
314 av_log(avctx, AV_LOG_VERBOSE, "Codec not supported\n");
318 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
319 if (IS_YUV444(ctx->data_pix_fmt) && ret <= 0) {
320 av_log(avctx, AV_LOG_VERBOSE, "YUV444P not supported\n");
321 return AVERROR(ENOSYS);
324 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOSSLESS_ENCODE);
325 if (ctx->preset >= PRESET_LOSSLESS_DEFAULT && ret <= 0) {
326 av_log(avctx, AV_LOG_VERBOSE, "Lossless encoding not supported\n");
327 return AVERROR(ENOSYS);
330 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
331 if (ret < avctx->width) {
332 av_log(avctx, AV_LOG_VERBOSE, "Width %d exceeds %d\n",
334 return AVERROR(ENOSYS);
337 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
338 if (ret < avctx->height) {
339 av_log(avctx, AV_LOG_VERBOSE, "Height %d exceeds %d\n",
341 return AVERROR(ENOSYS);
344 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
345 if (ret < avctx->max_b_frames) {
346 av_log(avctx, AV_LOG_VERBOSE, "Max B-frames %d exceed %d\n",
347 avctx->max_b_frames, ret);
349 return AVERROR(ENOSYS);
352 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_FIELD_ENCODING);
353 if (ret < 1 && avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
354 av_log(avctx, AV_LOG_VERBOSE,
355 "Interlaced encoding is not supported. Supported level: %d\n",
357 return AVERROR(ENOSYS);
360 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_10BIT_ENCODE);
361 if (IS_10BIT(ctx->data_pix_fmt) && ret <= 0) {
362 av_log(avctx, AV_LOG_VERBOSE, "10 bit encode not supported\n");
363 return AVERROR(ENOSYS);
366 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOOKAHEAD);
367 if (ctx->rc_lookahead > 0 && ret <= 0) {
368 av_log(avctx, AV_LOG_VERBOSE, "RC lookahead not supported\n");
369 return AVERROR(ENOSYS);
372 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_TEMPORAL_AQ);
373 if (ctx->temporal_aq > 0 && ret <= 0) {
374 av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ not supported\n");
375 return AVERROR(ENOSYS);
378 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_WEIGHTED_PREDICTION);
379 if (ctx->weighted_pred > 0 && ret <= 0) {
380 av_log (avctx, AV_LOG_VERBOSE, "Weighted Prediction not supported\n");
381 return AVERROR(ENOSYS);
384 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_CABAC);
385 if (ctx->coder == NV_ENC_H264_ENTROPY_CODING_MODE_CABAC && ret <= 0) {
386 av_log(avctx, AV_LOG_VERBOSE, "CABAC entropy coding not supported\n");
387 return AVERROR(ENOSYS);
390 #ifdef NVENC_HAVE_BFRAME_REF_MODE
391 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_BFRAME_REF_MODE);
392 if (ctx->b_ref_mode == NV_ENC_BFRAME_REF_MODE_EACH && ret != 1) {
393 av_log(avctx, AV_LOG_VERBOSE, "Each B frame as reference is not supported\n");
394 return AVERROR(ENOSYS);
395 } else if (ctx->b_ref_mode != NV_ENC_BFRAME_REF_MODE_DISABLED && ret == 0) {
396 av_log(avctx, AV_LOG_VERBOSE, "B frames as references are not supported\n");
397 return AVERROR(ENOSYS);
400 if (ctx->b_ref_mode != 0) {
401 av_log(avctx, AV_LOG_VERBOSE, "B frames as references need SDK 8.1 at build time\n");
402 return AVERROR(ENOSYS);
406 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
407 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_MULTIPLE_REF_FRAMES);
408 if(avctx->refs != NV_ENC_NUM_REF_FRAMES_AUTOSELECT && ret <= 0) {
409 av_log(avctx, AV_LOG_VERBOSE, "Multiple reference frames are not supported\n");
410 return AVERROR(ENOSYS);
413 if(avctx->refs != 0) {
414 av_log(avctx, AV_LOG_VERBOSE, "Multiple reference frames need SDK 9.1 at build time\n");
415 return AVERROR(ENOSYS);
419 ctx->support_dyn_bitrate = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_DYN_BITRATE_CHANGE);
424 static av_cold int nvenc_check_device(AVCodecContext *avctx, int idx)
426 NvencContext *ctx = avctx->priv_data;
427 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
428 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
429 char name[128] = { 0};
430 int major, minor, ret;
432 int loglevel = AV_LOG_VERBOSE;
434 if (ctx->device == LIST_DEVICES)
435 loglevel = AV_LOG_INFO;
437 ret = CHECK_CU(dl_fn->cuda_dl->cuDeviceGet(&cu_device, idx));
441 ret = CHECK_CU(dl_fn->cuda_dl->cuDeviceGetName(name, sizeof(name), cu_device));
445 ret = CHECK_CU(dl_fn->cuda_dl->cuDeviceComputeCapability(&major, &minor, cu_device));
449 av_log(avctx, loglevel, "[ GPU #%d - < %s > has Compute SM %d.%d ]\n", idx, name, major, minor);
450 if (((major << 4) | minor) < NVENC_CAP) {
451 av_log(avctx, loglevel, "does not support NVENC\n");
455 if (ctx->device != idx && ctx->device != ANY_DEVICE)
458 ret = CHECK_CU(dl_fn->cuda_dl->cuCtxCreate(&ctx->cu_context_internal, 0, cu_device));
462 ctx->cu_context = ctx->cu_context_internal;
464 if ((ret = nvenc_pop_context(avctx)) < 0)
467 if ((ret = nvenc_open_session(avctx)) < 0)
470 if ((ret = nvenc_check_capabilities(avctx)) < 0)
473 av_log(avctx, loglevel, "supports NVENC\n");
475 dl_fn->nvenc_device_count++;
477 if (ctx->device == idx || ctx->device == ANY_DEVICE)
481 if ((ret = nvenc_push_context(avctx)) < 0)
484 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
485 ctx->nvencoder = NULL;
487 if ((ret = nvenc_pop_context(avctx)) < 0)
491 CHECK_CU(dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal));
492 ctx->cu_context_internal = NULL;
495 return AVERROR(ENOSYS);
498 static av_cold int nvenc_setup_device(AVCodecContext *avctx)
500 NvencContext *ctx = avctx->priv_data;
501 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
503 switch (avctx->codec->id) {
504 case AV_CODEC_ID_H264:
505 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
507 case AV_CODEC_ID_HEVC:
508 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
514 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11 || avctx->hw_frames_ctx || avctx->hw_device_ctx) {
515 AVHWFramesContext *frames_ctx;
516 AVHWDeviceContext *hwdev_ctx;
517 AVCUDADeviceContext *cuda_device_hwctx = NULL;
519 AVD3D11VADeviceContext *d3d11_device_hwctx = NULL;
523 if (avctx->hw_frames_ctx) {
524 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
525 if (frames_ctx->format == AV_PIX_FMT_CUDA)
526 cuda_device_hwctx = frames_ctx->device_ctx->hwctx;
528 else if (frames_ctx->format == AV_PIX_FMT_D3D11)
529 d3d11_device_hwctx = frames_ctx->device_ctx->hwctx;
532 return AVERROR(EINVAL);
533 } else if (avctx->hw_device_ctx) {
534 hwdev_ctx = (AVHWDeviceContext*)avctx->hw_device_ctx->data;
535 if (hwdev_ctx->type == AV_HWDEVICE_TYPE_CUDA)
536 cuda_device_hwctx = hwdev_ctx->hwctx;
538 else if (hwdev_ctx->type == AV_HWDEVICE_TYPE_D3D11VA)
539 d3d11_device_hwctx = hwdev_ctx->hwctx;
542 return AVERROR(EINVAL);
544 return AVERROR(EINVAL);
547 if (cuda_device_hwctx) {
548 ctx->cu_context = cuda_device_hwctx->cuda_ctx;
551 else if (d3d11_device_hwctx) {
552 ctx->d3d11_device = d3d11_device_hwctx->device;
553 ID3D11Device_AddRef(ctx->d3d11_device);
557 ret = nvenc_open_session(avctx);
561 ret = nvenc_check_capabilities(avctx);
563 av_log(avctx, AV_LOG_FATAL, "Provided device doesn't support required NVENC features\n");
567 int i, nb_devices = 0;
569 if (CHECK_CU(dl_fn->cuda_dl->cuInit(0)) < 0)
570 return AVERROR_UNKNOWN;
572 if (CHECK_CU(dl_fn->cuda_dl->cuDeviceGetCount(&nb_devices)) < 0)
573 return AVERROR_UNKNOWN;
576 av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
577 return AVERROR_EXTERNAL;
580 av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", nb_devices);
582 dl_fn->nvenc_device_count = 0;
583 for (i = 0; i < nb_devices; ++i) {
584 if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
588 if (ctx->device == LIST_DEVICES)
591 if (!dl_fn->nvenc_device_count) {
592 av_log(avctx, AV_LOG_FATAL, "No NVENC capable devices found\n");
593 return AVERROR_EXTERNAL;
596 av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->device, nb_devices);
597 return AVERROR(EINVAL);
603 typedef struct GUIDTuple {
608 #define PRESET_ALIAS(alias, name, ...) \
609 [PRESET_ ## alias] = { NV_ENC_PRESET_ ## name ## _GUID, __VA_ARGS__ }
611 #define PRESET(name, ...) PRESET_ALIAS(name, name, __VA_ARGS__)
613 static void nvenc_map_preset(NvencContext *ctx)
615 GUIDTuple presets[] = {
620 PRESET_ALIAS(SLOW, HQ, NVENC_TWO_PASSES),
621 PRESET_ALIAS(MEDIUM, HQ, NVENC_ONE_PASS),
622 PRESET_ALIAS(FAST, HP, NVENC_ONE_PASS),
623 PRESET(LOW_LATENCY_DEFAULT, NVENC_LOWLATENCY),
624 PRESET(LOW_LATENCY_HP, NVENC_LOWLATENCY),
625 PRESET(LOW_LATENCY_HQ, NVENC_LOWLATENCY),
626 PRESET(LOSSLESS_DEFAULT, NVENC_LOSSLESS),
627 PRESET(LOSSLESS_HP, NVENC_LOSSLESS),
630 GUIDTuple *t = &presets[ctx->preset];
632 ctx->init_encode_params.presetGUID = t->guid;
633 ctx->flags = t->flags;
639 static av_cold void set_constqp(AVCodecContext *avctx)
641 NvencContext *ctx = avctx->priv_data;
642 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
644 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
646 if (ctx->init_qp_p >= 0) {
647 rc->constQP.qpInterP = ctx->init_qp_p;
648 if (ctx->init_qp_i >= 0 && ctx->init_qp_b >= 0) {
649 rc->constQP.qpIntra = ctx->init_qp_i;
650 rc->constQP.qpInterB = ctx->init_qp_b;
651 } else if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
652 rc->constQP.qpIntra = av_clip(
653 rc->constQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
654 rc->constQP.qpInterB = av_clip(
655 rc->constQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
657 rc->constQP.qpIntra = rc->constQP.qpInterP;
658 rc->constQP.qpInterB = rc->constQP.qpInterP;
660 } else if (ctx->cqp >= 0) {
661 rc->constQP.qpInterP = rc->constQP.qpInterB = rc->constQP.qpIntra = ctx->cqp;
662 if (avctx->b_quant_factor != 0.0)
663 rc->constQP.qpInterB = av_clip(ctx->cqp * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
664 if (avctx->i_quant_factor != 0.0)
665 rc->constQP.qpIntra = av_clip(ctx->cqp * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
672 static av_cold void set_vbr(AVCodecContext *avctx)
674 NvencContext *ctx = avctx->priv_data;
675 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
678 if (avctx->qmin >= 0 && avctx->qmax >= 0) {
682 rc->minQP.qpInterB = avctx->qmin;
683 rc->minQP.qpInterP = avctx->qmin;
684 rc->minQP.qpIntra = avctx->qmin;
686 rc->maxQP.qpInterB = avctx->qmax;
687 rc->maxQP.qpInterP = avctx->qmax;
688 rc->maxQP.qpIntra = avctx->qmax;
690 qp_inter_p = (avctx->qmax + 3 * avctx->qmin) / 4; // biased towards Qmin
691 } else if (avctx->qmin >= 0) {
694 rc->minQP.qpInterB = avctx->qmin;
695 rc->minQP.qpInterP = avctx->qmin;
696 rc->minQP.qpIntra = avctx->qmin;
698 qp_inter_p = avctx->qmin;
700 qp_inter_p = 26; // default to 26
703 rc->enableInitialRCQP = 1;
705 if (ctx->init_qp_p < 0) {
706 rc->initialRCQP.qpInterP = qp_inter_p;
708 rc->initialRCQP.qpInterP = ctx->init_qp_p;
711 if (ctx->init_qp_i < 0) {
712 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
713 rc->initialRCQP.qpIntra = av_clip(
714 rc->initialRCQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
716 rc->initialRCQP.qpIntra = rc->initialRCQP.qpInterP;
719 rc->initialRCQP.qpIntra = ctx->init_qp_i;
722 if (ctx->init_qp_b < 0) {
723 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
724 rc->initialRCQP.qpInterB = av_clip(
725 rc->initialRCQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
727 rc->initialRCQP.qpInterB = rc->initialRCQP.qpInterP;
730 rc->initialRCQP.qpInterB = ctx->init_qp_b;
734 static av_cold void set_lossless(AVCodecContext *avctx)
736 NvencContext *ctx = avctx->priv_data;
737 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
739 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
740 rc->constQP.qpInterB = 0;
741 rc->constQP.qpInterP = 0;
742 rc->constQP.qpIntra = 0;
748 static void nvenc_override_rate_control(AVCodecContext *avctx)
750 NvencContext *ctx = avctx->priv_data;
751 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
754 case NV_ENC_PARAMS_RC_CONSTQP:
757 case NV_ENC_PARAMS_RC_VBR_MINQP:
758 if (avctx->qmin < 0) {
759 av_log(avctx, AV_LOG_WARNING,
760 "The variable bitrate rate-control requires "
761 "the 'qmin' option set.\n");
766 case NV_ENC_PARAMS_RC_VBR_HQ:
767 case NV_ENC_PARAMS_RC_VBR:
770 case NV_ENC_PARAMS_RC_CBR:
771 case NV_ENC_PARAMS_RC_CBR_HQ:
772 case NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ:
776 rc->rateControlMode = ctx->rc;
779 static av_cold int nvenc_recalc_surfaces(AVCodecContext *avctx)
781 NvencContext *ctx = avctx->priv_data;
782 // default minimum of 4 surfaces
783 // multiply by 2 for number of NVENCs on gpu (hardcode to 2)
784 // another multiply by 2 to avoid blocking next PBB group
785 int nb_surfaces = FFMAX(4, ctx->encode_config.frameIntervalP * 2 * 2);
788 if (ctx->rc_lookahead > 0) {
789 // +1 is to account for lkd_bound calculation later
790 // +4 is to allow sufficient pipelining with lookahead
791 nb_surfaces = FFMAX(1, FFMAX(nb_surfaces, ctx->rc_lookahead + ctx->encode_config.frameIntervalP + 1 + 4));
792 if (nb_surfaces > ctx->nb_surfaces && ctx->nb_surfaces > 0)
794 av_log(avctx, AV_LOG_WARNING,
795 "Defined rc_lookahead requires more surfaces, "
796 "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
798 ctx->nb_surfaces = FFMAX(nb_surfaces, ctx->nb_surfaces);
800 if (ctx->encode_config.frameIntervalP > 1 && ctx->nb_surfaces < nb_surfaces && ctx->nb_surfaces > 0)
802 av_log(avctx, AV_LOG_WARNING,
803 "Defined b-frame requires more surfaces, "
804 "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
805 ctx->nb_surfaces = FFMAX(ctx->nb_surfaces, nb_surfaces);
807 else if (ctx->nb_surfaces <= 0)
808 ctx->nb_surfaces = nb_surfaces;
809 // otherwise use user specified value
812 ctx->nb_surfaces = FFMAX(1, FFMIN(MAX_REGISTERED_FRAMES, ctx->nb_surfaces));
813 ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
818 static av_cold void nvenc_setup_rate_control(AVCodecContext *avctx)
820 NvencContext *ctx = avctx->priv_data;
822 if (avctx->global_quality > 0)
823 av_log(avctx, AV_LOG_WARNING, "Using global_quality with nvenc is deprecated. Use qp instead.\n");
825 if (ctx->cqp < 0 && avctx->global_quality > 0)
826 ctx->cqp = avctx->global_quality;
828 if (avctx->bit_rate > 0) {
829 ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
830 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
831 ctx->encode_config.rcParams.maxBitRate = ctx->encode_config.rcParams.averageBitRate;
834 if (avctx->rc_max_rate > 0)
835 ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
838 if (ctx->flags & NVENC_ONE_PASS)
840 if (ctx->flags & NVENC_TWO_PASSES)
843 if (ctx->twopass < 0)
844 ctx->twopass = (ctx->flags & NVENC_LOWLATENCY) != 0;
848 ctx->rc = NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ;
850 ctx->rc = NV_ENC_PARAMS_RC_CBR;
852 } else if (ctx->cqp >= 0) {
853 ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
854 } else if (ctx->twopass) {
855 ctx->rc = NV_ENC_PARAMS_RC_VBR_HQ;
856 } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
857 ctx->rc = NV_ENC_PARAMS_RC_VBR_MINQP;
861 if (ctx->rc >= 0 && ctx->rc & RC_MODE_DEPRECATED) {
862 av_log(avctx, AV_LOG_WARNING, "Specified rc mode is deprecated.\n");
863 av_log(avctx, AV_LOG_WARNING, "\tll_2pass_quality -> cbr_ld_hq\n");
864 av_log(avctx, AV_LOG_WARNING, "\tll_2pass_size -> cbr_hq\n");
865 av_log(avctx, AV_LOG_WARNING, "\tvbr_2pass -> vbr_hq\n");
866 av_log(avctx, AV_LOG_WARNING, "\tvbr_minqp -> (no replacement)\n");
868 ctx->rc &= ~RC_MODE_DEPRECATED;
871 if (ctx->flags & NVENC_LOSSLESS) {
873 } else if (ctx->rc >= 0) {
874 nvenc_override_rate_control(avctx);
876 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
880 if (avctx->rc_buffer_size > 0) {
881 ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
882 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
883 avctx->rc_buffer_size = ctx->encode_config.rcParams.vbvBufferSize = 2 * ctx->encode_config.rcParams.averageBitRate;
887 ctx->encode_config.rcParams.enableAQ = 1;
888 ctx->encode_config.rcParams.aqStrength = ctx->aq_strength;
889 av_log(avctx, AV_LOG_VERBOSE, "AQ enabled.\n");
892 if (ctx->temporal_aq) {
893 ctx->encode_config.rcParams.enableTemporalAQ = 1;
894 av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ enabled.\n");
897 if (ctx->rc_lookahead > 0) {
898 int lkd_bound = FFMIN(ctx->nb_surfaces, ctx->async_depth) -
899 ctx->encode_config.frameIntervalP - 4;
902 av_log(avctx, AV_LOG_WARNING,
903 "Lookahead not enabled. Increase buffer delay (-delay).\n");
905 ctx->encode_config.rcParams.enableLookahead = 1;
906 ctx->encode_config.rcParams.lookaheadDepth = av_clip(ctx->rc_lookahead, 0, lkd_bound);
907 ctx->encode_config.rcParams.disableIadapt = ctx->no_scenecut;
908 ctx->encode_config.rcParams.disableBadapt = !ctx->b_adapt;
909 av_log(avctx, AV_LOG_VERBOSE,
910 "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",
911 ctx->encode_config.rcParams.lookaheadDepth,
912 ctx->encode_config.rcParams.disableIadapt ? "disabled" : "enabled",
913 ctx->encode_config.rcParams.disableBadapt ? "disabled" : "enabled");
917 if (ctx->strict_gop) {
918 ctx->encode_config.rcParams.strictGOPTarget = 1;
919 av_log(avctx, AV_LOG_VERBOSE, "Strict GOP target enabled.\n");
923 ctx->encode_config.rcParams.enableNonRefP = 1;
925 if (ctx->zerolatency)
926 ctx->encode_config.rcParams.zeroReorderDelay = 1;
930 //convert from float to fixed point 8.8
931 int tmp_quality = (int)(ctx->quality * 256.0f);
932 ctx->encode_config.rcParams.targetQuality = (uint8_t)(tmp_quality >> 8);
933 ctx->encode_config.rcParams.targetQualityLSB = (uint8_t)(tmp_quality & 0xff);
937 static av_cold int nvenc_setup_h264_config(AVCodecContext *avctx)
939 NvencContext *ctx = avctx->priv_data;
940 NV_ENC_CONFIG *cc = &ctx->encode_config;
941 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
942 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
944 vui->colourMatrix = avctx->colorspace;
945 vui->colourPrimaries = avctx->color_primaries;
946 vui->transferCharacteristics = avctx->color_trc;
947 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
948 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
950 vui->colourDescriptionPresentFlag =
951 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
953 vui->videoSignalTypePresentFlag =
954 (vui->colourDescriptionPresentFlag
955 || vui->videoFormat != 5
956 || vui->videoFullRangeFlag != 0);
959 h264->sliceModeData = 1;
961 h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
962 h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
963 h264->outputAUD = ctx->aud;
965 if (ctx->dpb_size >= 0) {
966 /* 0 means "let the hardware decide" */
967 h264->maxNumRefFrames = ctx->dpb_size;
969 if (avctx->gop_size >= 0) {
970 h264->idrPeriod = cc->gopLength;
973 if (IS_CBR(cc->rcParams.rateControlMode)) {
974 h264->outputBufferingPeriodSEI = 1;
977 h264->outputPictureTimingSEI = 1;
979 if (cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ ||
980 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_HQ ||
981 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_VBR_HQ) {
982 h264->adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
983 h264->fmoMode = NV_ENC_H264_FMO_DISABLE;
986 if (ctx->flags & NVENC_LOSSLESS) {
987 h264->qpPrimeYZeroTransformBypassFlag = 1;
989 switch(ctx->profile) {
990 case NV_ENC_H264_PROFILE_BASELINE:
991 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
992 avctx->profile = FF_PROFILE_H264_BASELINE;
994 case NV_ENC_H264_PROFILE_MAIN:
995 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
996 avctx->profile = FF_PROFILE_H264_MAIN;
998 case NV_ENC_H264_PROFILE_HIGH:
999 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
1000 avctx->profile = FF_PROFILE_H264_HIGH;
1002 case NV_ENC_H264_PROFILE_HIGH_444P:
1003 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1004 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
1009 // force setting profile as high444p if input is AV_PIX_FMT_YUV444P
1010 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P) {
1011 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1012 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
1015 h264->chromaFormatIDC = avctx->profile == FF_PROFILE_H264_HIGH_444_PREDICTIVE ? 3 : 1;
1017 h264->level = ctx->level;
1019 if (ctx->coder >= 0)
1020 h264->entropyCodingMode = ctx->coder;
1022 #ifdef NVENC_HAVE_BFRAME_REF_MODE
1023 h264->useBFramesAsRef = ctx->b_ref_mode;
1026 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
1027 h264->numRefL0 = avctx->refs;
1028 h264->numRefL1 = avctx->refs;
1034 static av_cold int nvenc_setup_hevc_config(AVCodecContext *avctx)
1036 NvencContext *ctx = avctx->priv_data;
1037 NV_ENC_CONFIG *cc = &ctx->encode_config;
1038 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
1039 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
1041 vui->colourMatrix = avctx->colorspace;
1042 vui->colourPrimaries = avctx->color_primaries;
1043 vui->transferCharacteristics = avctx->color_trc;
1044 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
1045 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
1047 vui->colourDescriptionPresentFlag =
1048 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
1050 vui->videoSignalTypePresentFlag =
1051 (vui->colourDescriptionPresentFlag
1052 || vui->videoFormat != 5
1053 || vui->videoFullRangeFlag != 0);
1055 hevc->sliceMode = 3;
1056 hevc->sliceModeData = 1;
1058 hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
1059 hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
1060 hevc->outputAUD = ctx->aud;
1062 if (ctx->dpb_size >= 0) {
1063 /* 0 means "let the hardware decide" */
1064 hevc->maxNumRefFramesInDPB = ctx->dpb_size;
1066 if (avctx->gop_size >= 0) {
1067 hevc->idrPeriod = cc->gopLength;
1070 if (IS_CBR(cc->rcParams.rateControlMode)) {
1071 hevc->outputBufferingPeriodSEI = 1;
1074 hevc->outputPictureTimingSEI = 1;
1076 switch (ctx->profile) {
1077 case NV_ENC_HEVC_PROFILE_MAIN:
1078 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
1079 avctx->profile = FF_PROFILE_HEVC_MAIN;
1081 case NV_ENC_HEVC_PROFILE_MAIN_10:
1082 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1083 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
1085 case NV_ENC_HEVC_PROFILE_REXT:
1086 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1087 avctx->profile = FF_PROFILE_HEVC_REXT;
1091 // force setting profile as main10 if input is 10 bit
1092 if (IS_10BIT(ctx->data_pix_fmt)) {
1093 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1094 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
1097 // force setting profile as rext if input is yuv444
1098 if (IS_YUV444(ctx->data_pix_fmt)) {
1099 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1100 avctx->profile = FF_PROFILE_HEVC_REXT;
1103 hevc->chromaFormatIDC = IS_YUV444(ctx->data_pix_fmt) ? 3 : 1;
1105 hevc->pixelBitDepthMinus8 = IS_10BIT(ctx->data_pix_fmt) ? 2 : 0;
1107 hevc->level = ctx->level;
1109 hevc->tier = ctx->tier;
1111 #ifdef NVENC_HAVE_HEVC_BFRAME_REF_MODE
1112 hevc->useBFramesAsRef = ctx->b_ref_mode;
1115 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
1116 hevc->numRefL0 = avctx->refs;
1117 hevc->numRefL1 = avctx->refs;
1123 static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx)
1125 switch (avctx->codec->id) {
1126 case AV_CODEC_ID_H264:
1127 return nvenc_setup_h264_config(avctx);
1128 case AV_CODEC_ID_HEVC:
1129 return nvenc_setup_hevc_config(avctx);
1130 /* Earlier switch/case will return if unknown codec is passed. */
1136 static void compute_dar(AVCodecContext *avctx, int *dw, int *dh) {
1142 if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0) {
1143 sw *= avctx->sample_aspect_ratio.num;
1144 sh *= avctx->sample_aspect_ratio.den;
1147 av_reduce(dw, dh, sw, sh, 1024 * 1024);
1150 static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
1152 NvencContext *ctx = avctx->priv_data;
1153 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1154 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1156 NV_ENC_PRESET_CONFIG preset_config = { 0 };
1157 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
1158 AVCPBProperties *cpb_props;
1162 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1163 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
1165 ctx->init_encode_params.encodeHeight = avctx->height;
1166 ctx->init_encode_params.encodeWidth = avctx->width;
1168 ctx->init_encode_params.encodeConfig = &ctx->encode_config;
1170 nvenc_map_preset(ctx);
1172 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
1173 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
1175 nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder,
1176 ctx->init_encode_params.encodeGUID,
1177 ctx->init_encode_params.presetGUID,
1179 if (nv_status != NV_ENC_SUCCESS)
1180 return nvenc_print_error(avctx, nv_status, "Cannot get the preset configuration");
1182 memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
1184 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1186 compute_dar(avctx, &dw, &dh);
1187 ctx->init_encode_params.darHeight = dh;
1188 ctx->init_encode_params.darWidth = dw;
1190 ctx->init_encode_params.frameRateNum = avctx->time_base.den;
1191 ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
1193 ctx->init_encode_params.enableEncodeAsync = 0;
1194 ctx->init_encode_params.enablePTD = 1;
1196 if (ctx->weighted_pred == 1)
1197 ctx->init_encode_params.enableWeightedPrediction = 1;
1199 if (ctx->bluray_compat) {
1201 ctx->dpb_size = FFMIN(FFMAX(avctx->refs, 0), 6);
1202 avctx->max_b_frames = FFMIN(avctx->max_b_frames, 3);
1203 switch (avctx->codec->id) {
1204 case AV_CODEC_ID_H264:
1205 /* maximum level depends on used resolution */
1207 case AV_CODEC_ID_HEVC:
1208 ctx->level = NV_ENC_LEVEL_HEVC_51;
1209 ctx->tier = NV_ENC_TIER_HEVC_HIGH;
1214 if (avctx->gop_size > 0) {
1215 if (avctx->max_b_frames >= 0) {
1216 /* 0 is intra-only, 1 is I/P only, 2 is one B-Frame, 3 two B-frames, and so on. */
1217 ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
1220 ctx->encode_config.gopLength = avctx->gop_size;
1221 } else if (avctx->gop_size == 0) {
1222 ctx->encode_config.frameIntervalP = 0;
1223 ctx->encode_config.gopLength = 1;
1226 ctx->initial_pts[0] = AV_NOPTS_VALUE;
1227 ctx->initial_pts[1] = AV_NOPTS_VALUE;
1229 nvenc_recalc_surfaces(avctx);
1231 nvenc_setup_rate_control(avctx);
1233 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1234 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
1236 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
1239 res = nvenc_setup_codec_config(avctx);
1243 res = nvenc_push_context(avctx);
1247 nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
1249 res = nvenc_pop_context(avctx);
1253 if (nv_status != NV_ENC_SUCCESS) {
1254 return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
1257 if (ctx->encode_config.frameIntervalP > 1)
1258 avctx->has_b_frames = 2;
1260 if (ctx->encode_config.rcParams.averageBitRate > 0)
1261 avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
1263 cpb_props = ff_add_cpb_side_data(avctx);
1265 return AVERROR(ENOMEM);
1266 cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
1267 cpb_props->avg_bitrate = avctx->bit_rate;
1268 cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
1273 static NV_ENC_BUFFER_FORMAT nvenc_map_buffer_format(enum AVPixelFormat pix_fmt)
1276 case AV_PIX_FMT_YUV420P:
1277 return NV_ENC_BUFFER_FORMAT_YV12_PL;
1278 case AV_PIX_FMT_NV12:
1279 return NV_ENC_BUFFER_FORMAT_NV12_PL;
1280 case AV_PIX_FMT_P010:
1281 case AV_PIX_FMT_P016:
1282 return NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1283 case AV_PIX_FMT_YUV444P:
1284 return NV_ENC_BUFFER_FORMAT_YUV444_PL;
1285 case AV_PIX_FMT_YUV444P16:
1286 return NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1287 case AV_PIX_FMT_0RGB32:
1288 return NV_ENC_BUFFER_FORMAT_ARGB;
1289 case AV_PIX_FMT_0BGR32:
1290 return NV_ENC_BUFFER_FORMAT_ABGR;
1292 return NV_ENC_BUFFER_FORMAT_UNDEFINED;
1296 static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
1298 NvencContext *ctx = avctx->priv_data;
1299 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1300 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1301 NvencSurface* tmp_surface = &ctx->surfaces[idx];
1303 NVENCSTATUS nv_status;
1304 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
1305 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1307 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1308 ctx->surfaces[idx].in_ref = av_frame_alloc();
1309 if (!ctx->surfaces[idx].in_ref)
1310 return AVERROR(ENOMEM);
1312 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1314 ctx->surfaces[idx].format = nvenc_map_buffer_format(ctx->data_pix_fmt);
1315 if (ctx->surfaces[idx].format == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1316 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1317 av_get_pix_fmt_name(ctx->data_pix_fmt));
1318 return AVERROR(EINVAL);
1321 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1322 allocSurf.width = avctx->width;
1323 allocSurf.height = avctx->height;
1324 allocSurf.bufferFmt = ctx->surfaces[idx].format;
1326 nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
1327 if (nv_status != NV_ENC_SUCCESS) {
1328 return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
1331 ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
1332 ctx->surfaces[idx].width = allocSurf.width;
1333 ctx->surfaces[idx].height = allocSurf.height;
1336 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
1337 if (nv_status != NV_ENC_SUCCESS) {
1338 int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
1339 if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
1340 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
1341 av_frame_free(&ctx->surfaces[idx].in_ref);
1345 ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1346 ctx->surfaces[idx].size = allocOut.size;
1348 av_fifo_generic_write(ctx->unused_surface_queue, &tmp_surface, sizeof(tmp_surface), NULL);
1353 static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx)
1355 NvencContext *ctx = avctx->priv_data;
1356 int i, res = 0, res2;
1358 ctx->surfaces = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->surfaces));
1360 return AVERROR(ENOMEM);
1362 ctx->timestamp_list = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
1363 if (!ctx->timestamp_list)
1364 return AVERROR(ENOMEM);
1366 ctx->unused_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1367 if (!ctx->unused_surface_queue)
1368 return AVERROR(ENOMEM);
1370 ctx->output_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1371 if (!ctx->output_surface_queue)
1372 return AVERROR(ENOMEM);
1373 ctx->output_surface_ready_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1374 if (!ctx->output_surface_ready_queue)
1375 return AVERROR(ENOMEM);
1377 res = nvenc_push_context(avctx);
1381 for (i = 0; i < ctx->nb_surfaces; i++) {
1382 if ((res = nvenc_alloc_surface(avctx, i)) < 0)
1387 res2 = nvenc_pop_context(avctx);
1394 static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
1396 NvencContext *ctx = avctx->priv_data;
1397 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1398 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1400 NVENCSTATUS nv_status;
1401 uint32_t outSize = 0;
1402 char tmpHeader[256];
1403 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1404 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1406 payload.spsppsBuffer = tmpHeader;
1407 payload.inBufferSize = sizeof(tmpHeader);
1408 payload.outSPSPPSPayloadSize = &outSize;
1410 nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
1411 if (nv_status != NV_ENC_SUCCESS) {
1412 return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
1415 avctx->extradata_size = outSize;
1416 avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
1418 if (!avctx->extradata) {
1419 return AVERROR(ENOMEM);
1422 memcpy(avctx->extradata, tmpHeader, outSize);
1427 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
1429 NvencContext *ctx = avctx->priv_data;
1430 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1431 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1434 /* the encoder has to be flushed before it can be closed */
1435 if (ctx->nvencoder) {
1436 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
1437 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
1439 res = nvenc_push_context(avctx);
1443 p_nvenc->nvEncEncodePicture(ctx->nvencoder, ¶ms);
1446 av_fifo_freep(&ctx->timestamp_list);
1447 av_fifo_freep(&ctx->output_surface_ready_queue);
1448 av_fifo_freep(&ctx->output_surface_queue);
1449 av_fifo_freep(&ctx->unused_surface_queue);
1451 if (ctx->surfaces && (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11)) {
1452 for (i = 0; i < ctx->nb_registered_frames; i++) {
1453 if (ctx->registered_frames[i].mapped)
1454 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[i].in_map.mappedResource);
1455 if (ctx->registered_frames[i].regptr)
1456 p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1458 ctx->nb_registered_frames = 0;
1461 if (ctx->surfaces) {
1462 for (i = 0; i < ctx->nb_surfaces; ++i) {
1463 if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
1464 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
1465 av_frame_free(&ctx->surfaces[i].in_ref);
1466 p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
1469 av_freep(&ctx->surfaces);
1470 ctx->nb_surfaces = 0;
1472 if (ctx->nvencoder) {
1473 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1475 res = nvenc_pop_context(avctx);
1479 ctx->nvencoder = NULL;
1481 if (ctx->cu_context_internal)
1482 CHECK_CU(dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal));
1483 ctx->cu_context = ctx->cu_context_internal = NULL;
1486 if (ctx->d3d11_device) {
1487 ID3D11Device_Release(ctx->d3d11_device);
1488 ctx->d3d11_device = NULL;
1492 nvenc_free_functions(&dl_fn->nvenc_dl);
1493 cuda_free_functions(&dl_fn->cuda_dl);
1495 dl_fn->nvenc_device_count = 0;
1497 av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
1502 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
1504 NvencContext *ctx = avctx->priv_data;
1507 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1508 AVHWFramesContext *frames_ctx;
1509 if (!avctx->hw_frames_ctx) {
1510 av_log(avctx, AV_LOG_ERROR,
1511 "hw_frames_ctx must be set when using GPU frames as input\n");
1512 return AVERROR(EINVAL);
1514 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1515 if (frames_ctx->format != avctx->pix_fmt) {
1516 av_log(avctx, AV_LOG_ERROR,
1517 "hw_frames_ctx must match the GPU frame type\n");
1518 return AVERROR(EINVAL);
1520 ctx->data_pix_fmt = frames_ctx->sw_format;
1522 ctx->data_pix_fmt = avctx->pix_fmt;
1525 if ((ret = nvenc_load_libraries(avctx)) < 0)
1528 if ((ret = nvenc_setup_device(avctx)) < 0)
1531 if ((ret = nvenc_setup_encoder(avctx)) < 0)
1534 if ((ret = nvenc_setup_surfaces(avctx)) < 0)
1537 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1538 if ((ret = nvenc_setup_extradata(avctx)) < 0)
1545 static NvencSurface *get_free_frame(NvencContext *ctx)
1547 NvencSurface *tmp_surf;
1549 if (!(av_fifo_size(ctx->unused_surface_queue) > 0))
1553 av_fifo_generic_read(ctx->unused_surface_queue, &tmp_surf, sizeof(tmp_surf), NULL);
1557 static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *nv_surface,
1558 NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params, const AVFrame *frame)
1560 int dst_linesize[4] = {
1561 lock_buffer_params->pitch,
1562 lock_buffer_params->pitch,
1563 lock_buffer_params->pitch,
1564 lock_buffer_params->pitch
1566 uint8_t *dst_data[4];
1569 if (frame->format == AV_PIX_FMT_YUV420P)
1570 dst_linesize[1] = dst_linesize[2] >>= 1;
1572 ret = av_image_fill_pointers(dst_data, frame->format, nv_surface->height,
1573 lock_buffer_params->bufferDataPtr, dst_linesize);
1577 if (frame->format == AV_PIX_FMT_YUV420P)
1578 FFSWAP(uint8_t*, dst_data[1], dst_data[2]);
1580 av_image_copy(dst_data, dst_linesize,
1581 (const uint8_t**)frame->data, frame->linesize, frame->format,
1582 avctx->width, avctx->height);
1587 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1589 NvencContext *ctx = avctx->priv_data;
1590 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1591 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1592 NVENCSTATUS nv_status;
1596 if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1597 for (first_round = 1; first_round >= 0; first_round--) {
1598 for (i = 0; i < ctx->nb_registered_frames; i++) {
1599 if (!ctx->registered_frames[i].mapped) {
1600 if (ctx->registered_frames[i].regptr) {
1603 nv_status = p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1604 if (nv_status != NV_ENC_SUCCESS)
1605 return nvenc_print_error(avctx, nv_status, "Failed unregistering unused input resource");
1606 ctx->registered_frames[i].ptr = NULL;
1607 ctx->registered_frames[i].regptr = NULL;
1614 return ctx->nb_registered_frames++;
1617 av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1618 return AVERROR(ENOMEM);
1621 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1623 NvencContext *ctx = avctx->priv_data;
1624 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1625 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1627 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frame->hw_frames_ctx->data;
1628 NV_ENC_REGISTER_RESOURCE reg;
1631 for (i = 0; i < ctx->nb_registered_frames; i++) {
1632 if (avctx->pix_fmt == AV_PIX_FMT_CUDA && ctx->registered_frames[i].ptr == frame->data[0])
1634 else if (avctx->pix_fmt == AV_PIX_FMT_D3D11 && ctx->registered_frames[i].ptr == frame->data[0] && ctx->registered_frames[i].ptr_index == (intptr_t)frame->data[1])
1638 idx = nvenc_find_free_reg_resource(avctx);
1642 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1643 reg.width = frames_ctx->width;
1644 reg.height = frames_ctx->height;
1645 reg.pitch = frame->linesize[0];
1646 reg.resourceToRegister = frame->data[0];
1648 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1649 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1651 else if (avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1652 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX;
1653 reg.subResourceIndex = (intptr_t)frame->data[1];
1656 reg.bufferFormat = nvenc_map_buffer_format(frames_ctx->sw_format);
1657 if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1658 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1659 av_get_pix_fmt_name(frames_ctx->sw_format));
1660 return AVERROR(EINVAL);
1663 ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, ®);
1664 if (ret != NV_ENC_SUCCESS) {
1665 nvenc_print_error(avctx, ret, "Error registering an input resource");
1666 return AVERROR_UNKNOWN;
1669 ctx->registered_frames[idx].ptr = frame->data[0];
1670 ctx->registered_frames[idx].ptr_index = reg.subResourceIndex;
1671 ctx->registered_frames[idx].regptr = reg.registeredResource;
1675 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1676 NvencSurface *nvenc_frame)
1678 NvencContext *ctx = avctx->priv_data;
1679 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1680 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1683 NVENCSTATUS nv_status;
1685 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1686 int reg_idx = nvenc_register_frame(avctx, frame);
1688 av_log(avctx, AV_LOG_ERROR, "Could not register an input HW frame\n");
1692 res = av_frame_ref(nvenc_frame->in_ref, frame);
1696 if (!ctx->registered_frames[reg_idx].mapped) {
1697 ctx->registered_frames[reg_idx].in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1698 ctx->registered_frames[reg_idx].in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1699 nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &ctx->registered_frames[reg_idx].in_map);
1700 if (nv_status != NV_ENC_SUCCESS) {
1701 av_frame_unref(nvenc_frame->in_ref);
1702 return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
1706 ctx->registered_frames[reg_idx].mapped += 1;
1708 nvenc_frame->reg_idx = reg_idx;
1709 nvenc_frame->input_surface = ctx->registered_frames[reg_idx].in_map.mappedResource;
1710 nvenc_frame->format = ctx->registered_frames[reg_idx].in_map.mappedBufferFmt;
1711 nvenc_frame->pitch = frame->linesize[0];
1715 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1717 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1718 lockBufferParams.inputBuffer = nvenc_frame->input_surface;
1720 nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
1721 if (nv_status != NV_ENC_SUCCESS) {
1722 return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
1725 nvenc_frame->pitch = lockBufferParams.pitch;
1726 res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
1728 nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
1729 if (nv_status != NV_ENC_SUCCESS) {
1730 return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
1737 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1738 NV_ENC_PIC_PARAMS *params,
1739 NV_ENC_SEI_PAYLOAD *sei_data)
1741 NvencContext *ctx = avctx->priv_data;
1743 switch (avctx->codec->id) {
1744 case AV_CODEC_ID_H264:
1745 params->codecPicParams.h264PicParams.sliceMode =
1746 ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1747 params->codecPicParams.h264PicParams.sliceModeData =
1748 ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1750 params->codecPicParams.h264PicParams.seiPayloadArray = sei_data;
1751 params->codecPicParams.h264PicParams.seiPayloadArrayCnt = 1;
1755 case AV_CODEC_ID_HEVC:
1756 params->codecPicParams.hevcPicParams.sliceMode =
1757 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1758 params->codecPicParams.hevcPicParams.sliceModeData =
1759 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1761 params->codecPicParams.hevcPicParams.seiPayloadArray = sei_data;
1762 params->codecPicParams.hevcPicParams.seiPayloadArrayCnt = 1;
1769 static inline void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
1771 av_fifo_generic_write(queue, ×tamp, sizeof(timestamp), NULL);
1774 static inline int64_t timestamp_queue_dequeue(AVFifoBuffer* queue)
1776 int64_t timestamp = AV_NOPTS_VALUE;
1777 if (av_fifo_size(queue) > 0)
1778 av_fifo_generic_read(queue, ×tamp, sizeof(timestamp), NULL);
1783 static int nvenc_set_timestamp(AVCodecContext *avctx,
1784 NV_ENC_LOCK_BITSTREAM *params,
1787 NvencContext *ctx = avctx->priv_data;
1789 pkt->pts = params->outputTimeStamp;
1791 /* generate the first dts by linearly extrapolating the
1792 * first two pts values to the past */
1793 if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
1794 ctx->initial_pts[1] != AV_NOPTS_VALUE) {
1795 int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
1798 if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
1799 (ts0 > 0 && ts1 < INT64_MIN + ts0))
1800 return AVERROR(ERANGE);
1803 if ((delta < 0 && ts0 > INT64_MAX + delta) ||
1804 (delta > 0 && ts0 < INT64_MIN + delta))
1805 return AVERROR(ERANGE);
1806 pkt->dts = ts0 - delta;
1808 ctx->first_packet_output = 1;
1812 pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
1817 static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
1819 NvencContext *ctx = avctx->priv_data;
1820 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1821 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1823 uint32_t slice_mode_data;
1824 uint32_t *slice_offsets = NULL;
1825 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1826 NVENCSTATUS nv_status;
1829 enum AVPictureType pict_type;
1831 switch (avctx->codec->id) {
1832 case AV_CODEC_ID_H264:
1833 slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1835 case AV_CODEC_ID_H265:
1836 slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1839 av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
1840 res = AVERROR(EINVAL);
1843 slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
1845 if (!slice_offsets) {
1846 res = AVERROR(ENOMEM);
1850 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1852 lock_params.doNotWait = 0;
1853 lock_params.outputBitstream = tmpoutsurf->output_surface;
1854 lock_params.sliceOffsets = slice_offsets;
1856 nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
1857 if (nv_status != NV_ENC_SUCCESS) {
1858 res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
1862 if (res = ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes,0)) {
1863 p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1867 memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1869 nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1870 if (nv_status != NV_ENC_SUCCESS) {
1871 res = nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
1876 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1877 ctx->registered_frames[tmpoutsurf->reg_idx].mapped -= 1;
1878 if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped == 0) {
1879 nv_status = p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[tmpoutsurf->reg_idx].in_map.mappedResource);
1880 if (nv_status != NV_ENC_SUCCESS) {
1881 res = nvenc_print_error(avctx, nv_status, "Failed unmapping input resource");
1884 } else if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped < 0) {
1889 av_frame_unref(tmpoutsurf->in_ref);
1891 tmpoutsurf->input_surface = NULL;
1894 switch (lock_params.pictureType) {
1895 case NV_ENC_PIC_TYPE_IDR:
1896 pkt->flags |= AV_PKT_FLAG_KEY;
1897 case NV_ENC_PIC_TYPE_I:
1898 pict_type = AV_PICTURE_TYPE_I;
1900 case NV_ENC_PIC_TYPE_P:
1901 pict_type = AV_PICTURE_TYPE_P;
1903 case NV_ENC_PIC_TYPE_B:
1904 pict_type = AV_PICTURE_TYPE_B;
1906 case NV_ENC_PIC_TYPE_BI:
1907 pict_type = AV_PICTURE_TYPE_BI;
1910 av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
1911 av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
1912 res = AVERROR_EXTERNAL;
1916 #if FF_API_CODED_FRAME
1917 FF_DISABLE_DEPRECATION_WARNINGS
1918 avctx->coded_frame->pict_type = pict_type;
1919 FF_ENABLE_DEPRECATION_WARNINGS
1922 ff_side_data_set_encoder_stats(pkt,
1923 (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
1925 res = nvenc_set_timestamp(avctx, &lock_params, pkt);
1929 av_free(slice_offsets);
1934 timestamp_queue_dequeue(ctx->timestamp_list);
1937 av_free(slice_offsets);
1942 static int output_ready(AVCodecContext *avctx, int flush)
1944 NvencContext *ctx = avctx->priv_data;
1945 int nb_ready, nb_pending;
1947 /* when B-frames are enabled, we wait for two initial timestamps to
1948 * calculate the first dts */
1949 if (!flush && avctx->max_b_frames > 0 &&
1950 (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
1953 nb_ready = av_fifo_size(ctx->output_surface_ready_queue) / sizeof(NvencSurface*);
1954 nb_pending = av_fifo_size(ctx->output_surface_queue) / sizeof(NvencSurface*);
1956 return nb_ready > 0;
1957 return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
1960 static void reconfig_encoder(AVCodecContext *avctx, const AVFrame *frame)
1962 NvencContext *ctx = avctx->priv_data;
1963 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
1966 NV_ENC_RECONFIGURE_PARAMS params = { 0 };
1967 int needs_reconfig = 0;
1968 int needs_encode_config = 0;
1969 int reconfig_bitrate = 0, reconfig_dar = 0;
1972 params.version = NV_ENC_RECONFIGURE_PARAMS_VER;
1973 params.reInitEncodeParams = ctx->init_encode_params;
1975 compute_dar(avctx, &dw, &dh);
1976 if (dw != ctx->init_encode_params.darWidth || dh != ctx->init_encode_params.darHeight) {
1977 av_log(avctx, AV_LOG_VERBOSE,
1978 "aspect ratio change (DAR): %d:%d -> %d:%d\n",
1979 ctx->init_encode_params.darWidth,
1980 ctx->init_encode_params.darHeight, dw, dh);
1982 params.reInitEncodeParams.darHeight = dh;
1983 params.reInitEncodeParams.darWidth = dw;
1989 if (ctx->rc != NV_ENC_PARAMS_RC_CONSTQP && ctx->support_dyn_bitrate) {
1990 if (avctx->bit_rate > 0 && params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate != avctx->bit_rate) {
1991 av_log(avctx, AV_LOG_VERBOSE,
1992 "avg bitrate change: %d -> %d\n",
1993 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate,
1994 (uint32_t)avctx->bit_rate);
1996 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate = avctx->bit_rate;
1997 reconfig_bitrate = 1;
2000 if (avctx->rc_max_rate > 0 && ctx->encode_config.rcParams.maxBitRate != avctx->rc_max_rate) {
2001 av_log(avctx, AV_LOG_VERBOSE,
2002 "max bitrate change: %d -> %d\n",
2003 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate,
2004 (uint32_t)avctx->rc_max_rate);
2006 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate = avctx->rc_max_rate;
2007 reconfig_bitrate = 1;
2010 if (avctx->rc_buffer_size > 0 && ctx->encode_config.rcParams.vbvBufferSize != avctx->rc_buffer_size) {
2011 av_log(avctx, AV_LOG_VERBOSE,
2012 "vbv buffer size change: %d -> %d\n",
2013 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize,
2014 avctx->rc_buffer_size);
2016 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize = avctx->rc_buffer_size;
2017 reconfig_bitrate = 1;
2020 if (reconfig_bitrate) {
2021 params.resetEncoder = 1;
2022 params.forceIDR = 1;
2024 needs_encode_config = 1;
2029 if (!needs_encode_config)
2030 params.reInitEncodeParams.encodeConfig = NULL;
2032 if (needs_reconfig) {
2033 ret = p_nvenc->nvEncReconfigureEncoder(ctx->nvencoder, ¶ms);
2034 if (ret != NV_ENC_SUCCESS) {
2035 nvenc_print_error(avctx, ret, "failed to reconfigure nvenc");
2038 ctx->init_encode_params.darHeight = dh;
2039 ctx->init_encode_params.darWidth = dw;
2042 if (reconfig_bitrate) {
2043 ctx->encode_config.rcParams.averageBitRate = params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate;
2044 ctx->encode_config.rcParams.maxBitRate = params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate;
2045 ctx->encode_config.rcParams.vbvBufferSize = params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize;
2052 int ff_nvenc_send_frame(AVCodecContext *avctx, const AVFrame *frame)
2054 NVENCSTATUS nv_status;
2055 NvencSurface *tmp_out_surf, *in_surf;
2057 NV_ENC_SEI_PAYLOAD *sei_data = NULL;
2060 NvencContext *ctx = avctx->priv_data;
2061 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
2062 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
2064 NV_ENC_PIC_PARAMS pic_params = { 0 };
2065 pic_params.version = NV_ENC_PIC_PARAMS_VER;
2067 if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
2068 return AVERROR(EINVAL);
2070 if (ctx->encoder_flushing) {
2071 if (avctx->internal->draining)
2074 ctx->encoder_flushing = 0;
2075 ctx->first_packet_output = 0;
2076 ctx->initial_pts[0] = AV_NOPTS_VALUE;
2077 ctx->initial_pts[1] = AV_NOPTS_VALUE;
2078 av_fifo_reset(ctx->timestamp_list);
2082 in_surf = get_free_frame(ctx);
2084 return AVERROR(EAGAIN);
2086 res = nvenc_push_context(avctx);
2090 reconfig_encoder(avctx, frame);
2092 res = nvenc_upload_frame(avctx, frame, in_surf);
2094 res2 = nvenc_pop_context(avctx);
2101 pic_params.inputBuffer = in_surf->input_surface;
2102 pic_params.bufferFmt = in_surf->format;
2103 pic_params.inputWidth = in_surf->width;
2104 pic_params.inputHeight = in_surf->height;
2105 pic_params.inputPitch = in_surf->pitch;
2106 pic_params.outputBitstream = in_surf->output_surface;
2108 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
2109 if (frame->top_field_first)
2110 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
2112 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
2114 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
2117 if (ctx->forced_idr >= 0 && frame->pict_type == AV_PICTURE_TYPE_I) {
2118 pic_params.encodePicFlags =
2119 ctx->forced_idr ? NV_ENC_PIC_FLAG_FORCEIDR : NV_ENC_PIC_FLAG_FORCEINTRA;
2121 pic_params.encodePicFlags = 0;
2124 pic_params.inputTimeStamp = frame->pts;
2126 if (ctx->a53_cc && av_frame_get_side_data(frame, AV_FRAME_DATA_A53_CC)) {
2127 if (ff_alloc_a53_sei(frame, sizeof(NV_ENC_SEI_PAYLOAD), (void**)&sei_data, &sei_size) < 0) {
2128 av_log(ctx, AV_LOG_ERROR, "Not enough memory for closed captions, skipping\n");
2132 sei_data->payloadSize = (uint32_t)sei_size;
2133 sei_data->payloadType = 4;
2134 sei_data->payload = (uint8_t*)(sei_data + 1);
2138 nvenc_codec_specific_pic_params(avctx, &pic_params, sei_data);
2140 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
2141 ctx->encoder_flushing = 1;
2144 res = nvenc_push_context(avctx);
2148 nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
2151 res = nvenc_pop_context(avctx);
2155 if (nv_status != NV_ENC_SUCCESS &&
2156 nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
2157 return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
2160 av_fifo_generic_write(ctx->output_surface_queue, &in_surf, sizeof(in_surf), NULL);
2161 timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
2163 if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
2164 ctx->initial_pts[0] = frame->pts;
2165 else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
2166 ctx->initial_pts[1] = frame->pts;
2169 /* all the pending buffers are now ready for output */
2170 if (nv_status == NV_ENC_SUCCESS) {
2171 while (av_fifo_size(ctx->output_surface_queue) > 0) {
2172 av_fifo_generic_read(ctx->output_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2173 av_fifo_generic_write(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2180 int ff_nvenc_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
2182 NvencSurface *tmp_out_surf;
2185 NvencContext *ctx = avctx->priv_data;
2187 if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
2188 return AVERROR(EINVAL);
2190 if (output_ready(avctx, ctx->encoder_flushing)) {
2191 av_fifo_generic_read(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2193 res = nvenc_push_context(avctx);
2197 res = process_output_surface(avctx, pkt, tmp_out_surf);
2199 res2 = nvenc_pop_context(avctx);
2206 av_fifo_generic_write(ctx->unused_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2207 } else if (ctx->encoder_flushing) {
2210 return AVERROR(EAGAIN);
2216 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
2217 const AVFrame *frame, int *got_packet)
2219 NvencContext *ctx = avctx->priv_data;
2222 if (!ctx->encoder_flushing) {
2223 res = ff_nvenc_send_frame(avctx, frame);
2228 res = ff_nvenc_receive_packet(avctx, pkt);
2229 if (res == AVERROR(EAGAIN) || res == AVERROR_EOF) {
2231 } else if (res < 0) {