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
27 #include "libavutil/hwcontext_cuda.h"
28 #include "libavutil/hwcontext.h"
29 #include "libavutil/cuda_check.h"
30 #include "libavutil/imgutils.h"
31 #include "libavutil/avassert.h"
32 #include "libavutil/mem.h"
33 #include "libavutil/pixdesc.h"
36 #include "packet_internal.h"
38 #define CHECK_CU(x) FF_CUDA_CHECK_DL(avctx, dl_fn->cuda_dl, x)
40 #define NVENC_CAP 0x30
41 #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR || \
42 rc == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ || \
43 rc == NV_ENC_PARAMS_RC_CBR_HQ)
45 #ifdef NVENC_HAVE_NEW_PRESETS
46 #define IS_SDK10_PRESET(p) ((p) >= PRESET_P1 && (p) <= PRESET_P7)
48 #define IS_SDK10_PRESET(p) 0
51 const enum AVPixelFormat ff_nvenc_pix_fmts[] = {
56 AV_PIX_FMT_P016, // Truncated to 10bits
57 AV_PIX_FMT_YUV444P16, // Truncated to 10bits
67 const AVCodecHWConfigInternal *ff_nvenc_hw_configs[] = {
68 HW_CONFIG_ENCODER_FRAMES(CUDA, CUDA),
69 HW_CONFIG_ENCODER_DEVICE(NONE, CUDA),
71 HW_CONFIG_ENCODER_FRAMES(D3D11, D3D11VA),
72 HW_CONFIG_ENCODER_DEVICE(NONE, D3D11VA),
77 #define IS_10BIT(pix_fmt) (pix_fmt == AV_PIX_FMT_P010 || \
78 pix_fmt == AV_PIX_FMT_P016 || \
79 pix_fmt == AV_PIX_FMT_YUV444P16)
81 #define IS_YUV444(pix_fmt) (pix_fmt == AV_PIX_FMT_YUV444P || \
82 pix_fmt == AV_PIX_FMT_YUV444P16)
89 { NV_ENC_SUCCESS, 0, "success" },
90 { NV_ENC_ERR_NO_ENCODE_DEVICE, AVERROR(ENOENT), "no encode device" },
91 { NV_ENC_ERR_UNSUPPORTED_DEVICE, AVERROR(ENOSYS), "unsupported device" },
92 { NV_ENC_ERR_INVALID_ENCODERDEVICE, AVERROR(EINVAL), "invalid encoder device" },
93 { NV_ENC_ERR_INVALID_DEVICE, AVERROR(EINVAL), "invalid device" },
94 { NV_ENC_ERR_DEVICE_NOT_EXIST, AVERROR(EIO), "device does not exist" },
95 { NV_ENC_ERR_INVALID_PTR, AVERROR(EFAULT), "invalid ptr" },
96 { NV_ENC_ERR_INVALID_EVENT, AVERROR(EINVAL), "invalid event" },
97 { NV_ENC_ERR_INVALID_PARAM, AVERROR(EINVAL), "invalid param" },
98 { NV_ENC_ERR_INVALID_CALL, AVERROR(EINVAL), "invalid call" },
99 { NV_ENC_ERR_OUT_OF_MEMORY, AVERROR(ENOMEM), "out of memory" },
100 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED, AVERROR(EINVAL), "encoder not initialized" },
101 { NV_ENC_ERR_UNSUPPORTED_PARAM, AVERROR(ENOSYS), "unsupported param" },
102 { NV_ENC_ERR_LOCK_BUSY, AVERROR(EAGAIN), "lock busy" },
103 { NV_ENC_ERR_NOT_ENOUGH_BUFFER, AVERROR_BUFFER_TOO_SMALL, "not enough buffer"},
104 { NV_ENC_ERR_INVALID_VERSION, AVERROR(EINVAL), "invalid version" },
105 { NV_ENC_ERR_MAP_FAILED, AVERROR(EIO), "map failed" },
106 { NV_ENC_ERR_NEED_MORE_INPUT, AVERROR(EAGAIN), "need more input" },
107 { NV_ENC_ERR_ENCODER_BUSY, AVERROR(EAGAIN), "encoder busy" },
108 { NV_ENC_ERR_EVENT_NOT_REGISTERD, AVERROR(EBADF), "event not registered" },
109 { NV_ENC_ERR_GENERIC, AVERROR_UNKNOWN, "generic error" },
110 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY, AVERROR(EINVAL), "incompatible client key" },
111 { NV_ENC_ERR_UNIMPLEMENTED, AVERROR(ENOSYS), "unimplemented" },
112 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO), "resource register failed" },
113 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED, AVERROR(EBADF), "resource not registered" },
114 { NV_ENC_ERR_RESOURCE_NOT_MAPPED, AVERROR(EBADF), "resource not mapped" },
117 static int nvenc_map_error(NVENCSTATUS err, const char **desc)
120 for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
121 if (nvenc_errors[i].nverr == err) {
123 *desc = nvenc_errors[i].desc;
124 return nvenc_errors[i].averr;
128 *desc = "unknown error";
129 return AVERROR_UNKNOWN;
132 static int nvenc_print_error(AVCodecContext *avctx, NVENCSTATUS err,
133 const char *error_string)
136 const char *details = "(no details)";
137 int ret = nvenc_map_error(err, &desc);
139 #ifdef NVENC_HAVE_GETLASTERRORSTRING
140 NvencContext *ctx = avctx->priv_data;
141 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
143 if (p_nvenc && ctx->nvencoder)
144 details = p_nvenc->nvEncGetLastErrorString(ctx->nvencoder);
147 av_log(avctx, AV_LOG_ERROR, "%s: %s (%d): %s\n", error_string, desc, err, details);
152 static void nvenc_print_driver_requirement(AVCodecContext *avctx, int level)
154 #if NVENCAPI_CHECK_VERSION(10, 1)
155 const char *minver = "(unknown)";
156 #elif NVENCAPI_CHECK_VERSION(10, 0)
157 # if defined(_WIN32) || defined(__CYGWIN__)
158 const char *minver = "450.51";
160 const char *minver = "445.87";
162 #elif NVENCAPI_CHECK_VERSION(9, 1)
163 # if defined(_WIN32) || defined(__CYGWIN__)
164 const char *minver = "436.15";
166 const char *minver = "435.21";
168 #elif NVENCAPI_CHECK_VERSION(9, 0)
169 # if defined(_WIN32) || defined(__CYGWIN__)
170 const char *minver = "418.81";
172 const char *minver = "418.30";
174 #elif NVENCAPI_CHECK_VERSION(8, 2)
175 # if defined(_WIN32) || defined(__CYGWIN__)
176 const char *minver = "397.93";
178 const char *minver = "396.24";
180 #elif NVENCAPI_CHECK_VERSION(8, 1)
181 # if defined(_WIN32) || defined(__CYGWIN__)
182 const char *minver = "390.77";
184 const char *minver = "390.25";
187 # if defined(_WIN32) || defined(__CYGWIN__)
188 const char *minver = "378.66";
190 const char *minver = "378.13";
193 av_log(avctx, level, "The minimum required Nvidia driver for nvenc is %s or newer\n", minver);
196 static av_cold int nvenc_load_libraries(AVCodecContext *avctx)
198 NvencContext *ctx = avctx->priv_data;
199 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
201 uint32_t nvenc_max_ver;
204 ret = cuda_load_functions(&dl_fn->cuda_dl, avctx);
208 ret = nvenc_load_functions(&dl_fn->nvenc_dl, avctx);
210 nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
214 err = dl_fn->nvenc_dl->NvEncodeAPIGetMaxSupportedVersion(&nvenc_max_ver);
215 if (err != NV_ENC_SUCCESS)
216 return nvenc_print_error(avctx, err, "Failed to query nvenc max version");
218 av_log(avctx, AV_LOG_VERBOSE, "Loaded Nvenc version %d.%d\n", nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
220 if ((NVENCAPI_MAJOR_VERSION << 4 | NVENCAPI_MINOR_VERSION) > nvenc_max_ver) {
221 av_log(avctx, AV_LOG_ERROR, "Driver does not support the required nvenc API version. "
222 "Required: %d.%d Found: %d.%d\n",
223 NVENCAPI_MAJOR_VERSION, NVENCAPI_MINOR_VERSION,
224 nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
225 nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
226 return AVERROR(ENOSYS);
229 dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
231 err = dl_fn->nvenc_dl->NvEncodeAPICreateInstance(&dl_fn->nvenc_funcs);
232 if (err != NV_ENC_SUCCESS)
233 return nvenc_print_error(avctx, err, "Failed to create nvenc instance");
235 av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
240 static int nvenc_push_context(AVCodecContext *avctx)
242 NvencContext *ctx = avctx->priv_data;
243 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
245 if (ctx->d3d11_device)
248 return CHECK_CU(dl_fn->cuda_dl->cuCtxPushCurrent(ctx->cu_context));
251 static int nvenc_pop_context(AVCodecContext *avctx)
253 NvencContext *ctx = avctx->priv_data;
254 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
257 if (ctx->d3d11_device)
260 return CHECK_CU(dl_fn->cuda_dl->cuCtxPopCurrent(&dummy));
263 static av_cold int nvenc_open_session(AVCodecContext *avctx)
265 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
266 NvencContext *ctx = avctx->priv_data;
267 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
270 params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
271 params.apiVersion = NVENCAPI_VERSION;
272 if (ctx->d3d11_device) {
273 params.device = ctx->d3d11_device;
274 params.deviceType = NV_ENC_DEVICE_TYPE_DIRECTX;
276 params.device = ctx->cu_context;
277 params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
280 ret = p_nvenc->nvEncOpenEncodeSessionEx(¶ms, &ctx->nvencoder);
281 if (ret != NV_ENC_SUCCESS) {
282 ctx->nvencoder = NULL;
283 return nvenc_print_error(avctx, ret, "OpenEncodeSessionEx failed");
289 static int nvenc_check_codec_support(AVCodecContext *avctx)
291 NvencContext *ctx = avctx->priv_data;
292 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
293 int i, ret, count = 0;
296 ret = p_nvenc->nvEncGetEncodeGUIDCount(ctx->nvencoder, &count);
298 if (ret != NV_ENC_SUCCESS || !count)
299 return AVERROR(ENOSYS);
301 guids = av_malloc(count * sizeof(GUID));
303 return AVERROR(ENOMEM);
305 ret = p_nvenc->nvEncGetEncodeGUIDs(ctx->nvencoder, guids, count, &count);
306 if (ret != NV_ENC_SUCCESS) {
307 ret = AVERROR(ENOSYS);
311 ret = AVERROR(ENOSYS);
312 for (i = 0; i < count; i++) {
313 if (!memcmp(&guids[i], &ctx->init_encode_params.encodeGUID, sizeof(*guids))) {
325 static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
327 NvencContext *ctx = avctx->priv_data;
328 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
329 NV_ENC_CAPS_PARAM params = { 0 };
332 params.version = NV_ENC_CAPS_PARAM_VER;
333 params.capsToQuery = cap;
335 ret = p_nvenc->nvEncGetEncodeCaps(ctx->nvencoder, ctx->init_encode_params.encodeGUID, ¶ms, &val);
337 if (ret == NV_ENC_SUCCESS)
342 static int nvenc_check_capabilities(AVCodecContext *avctx)
344 NvencContext *ctx = avctx->priv_data;
347 ret = nvenc_check_codec_support(avctx);
349 av_log(avctx, AV_LOG_WARNING, "Codec not supported\n");
353 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
354 if (IS_YUV444(ctx->data_pix_fmt) && ret <= 0) {
355 av_log(avctx, AV_LOG_WARNING, "YUV444P not supported\n");
356 return AVERROR(ENOSYS);
359 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOSSLESS_ENCODE);
360 if (ctx->preset >= PRESET_LOSSLESS_DEFAULT && ret <= 0) {
361 av_log(avctx, AV_LOG_WARNING, "Lossless encoding not supported\n");
362 return AVERROR(ENOSYS);
365 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
366 if (ret < avctx->width) {
367 av_log(avctx, AV_LOG_WARNING, "Width %d exceeds %d\n",
369 return AVERROR(ENOSYS);
372 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
373 if (ret < avctx->height) {
374 av_log(avctx, AV_LOG_WARNING, "Height %d exceeds %d\n",
376 return AVERROR(ENOSYS);
379 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
380 if (ret < avctx->max_b_frames) {
381 av_log(avctx, AV_LOG_WARNING, "Max B-frames %d exceed %d\n",
382 avctx->max_b_frames, ret);
384 return AVERROR(ENOSYS);
387 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_FIELD_ENCODING);
388 if (ret < 1 && avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
389 av_log(avctx, AV_LOG_WARNING,
390 "Interlaced encoding is not supported. Supported level: %d\n",
392 return AVERROR(ENOSYS);
395 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_10BIT_ENCODE);
396 if (IS_10BIT(ctx->data_pix_fmt) && ret <= 0) {
397 av_log(avctx, AV_LOG_WARNING, "10 bit encode not supported\n");
398 return AVERROR(ENOSYS);
401 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOOKAHEAD);
402 if (ctx->rc_lookahead > 0 && ret <= 0) {
403 av_log(avctx, AV_LOG_WARNING, "RC lookahead not supported\n");
404 return AVERROR(ENOSYS);
407 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_TEMPORAL_AQ);
408 if (ctx->temporal_aq > 0 && ret <= 0) {
409 av_log(avctx, AV_LOG_WARNING, "Temporal AQ not supported\n");
410 return AVERROR(ENOSYS);
413 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_WEIGHTED_PREDICTION);
414 if (ctx->weighted_pred > 0 && ret <= 0) {
415 av_log (avctx, AV_LOG_WARNING, "Weighted Prediction not supported\n");
416 return AVERROR(ENOSYS);
419 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_CABAC);
420 if (ctx->coder == NV_ENC_H264_ENTROPY_CODING_MODE_CABAC && ret <= 0) {
421 av_log(avctx, AV_LOG_WARNING, "CABAC entropy coding not supported\n");
422 return AVERROR(ENOSYS);
425 #ifdef NVENC_HAVE_BFRAME_REF_MODE
426 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_BFRAME_REF_MODE);
427 if (ctx->b_ref_mode == NV_ENC_BFRAME_REF_MODE_EACH && ret != 1 && ret != 3) {
428 av_log(avctx, AV_LOG_WARNING, "Each B frame as reference is not supported\n");
429 return AVERROR(ENOSYS);
430 } else if (ctx->b_ref_mode != NV_ENC_BFRAME_REF_MODE_DISABLED && ret == 0) {
431 av_log(avctx, AV_LOG_WARNING, "B frames as references are not supported\n");
432 return AVERROR(ENOSYS);
435 if (ctx->b_ref_mode != 0) {
436 av_log(avctx, AV_LOG_WARNING, "B frames as references need SDK 8.1 at build time\n");
437 return AVERROR(ENOSYS);
441 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
442 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_MULTIPLE_REF_FRAMES);
443 if(avctx->refs != NV_ENC_NUM_REF_FRAMES_AUTOSELECT && ret <= 0) {
444 av_log(avctx, AV_LOG_WARNING, "Multiple reference frames are not supported by the device\n");
445 return AVERROR(ENOSYS);
448 if(avctx->refs != 0) {
449 av_log(avctx, AV_LOG_WARNING, "Multiple reference frames need SDK 9.1 at build time\n");
450 return AVERROR(ENOSYS);
454 ctx->support_dyn_bitrate = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_DYN_BITRATE_CHANGE);
459 static av_cold int nvenc_check_device(AVCodecContext *avctx, int idx)
461 NvencContext *ctx = avctx->priv_data;
462 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
463 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
464 char name[128] = { 0};
465 int major, minor, ret;
467 int loglevel = AV_LOG_VERBOSE;
469 if (ctx->device == LIST_DEVICES)
470 loglevel = AV_LOG_INFO;
472 ret = CHECK_CU(dl_fn->cuda_dl->cuDeviceGet(&cu_device, idx));
476 ret = CHECK_CU(dl_fn->cuda_dl->cuDeviceGetName(name, sizeof(name), cu_device));
480 ret = CHECK_CU(dl_fn->cuda_dl->cuDeviceComputeCapability(&major, &minor, cu_device));
484 av_log(avctx, loglevel, "[ GPU #%d - < %s > has Compute SM %d.%d ]\n", idx, name, major, minor);
485 if (((major << 4) | minor) < NVENC_CAP) {
486 av_log(avctx, loglevel, "does not support NVENC\n");
490 if (ctx->device != idx && ctx->device != ANY_DEVICE)
493 ret = CHECK_CU(dl_fn->cuda_dl->cuCtxCreate(&ctx->cu_context_internal, 0, cu_device));
497 ctx->cu_context = ctx->cu_context_internal;
498 ctx->cu_stream = NULL;
500 if ((ret = nvenc_pop_context(avctx)) < 0)
503 if ((ret = nvenc_open_session(avctx)) < 0)
506 if ((ret = nvenc_check_capabilities(avctx)) < 0)
509 av_log(avctx, loglevel, "supports NVENC\n");
511 dl_fn->nvenc_device_count++;
513 if (ctx->device == idx || ctx->device == ANY_DEVICE)
517 if ((ret = nvenc_push_context(avctx)) < 0)
520 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
521 ctx->nvencoder = NULL;
523 if ((ret = nvenc_pop_context(avctx)) < 0)
527 CHECK_CU(dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal));
528 ctx->cu_context_internal = NULL;
531 return AVERROR(ENOSYS);
534 static av_cold int nvenc_setup_device(AVCodecContext *avctx)
536 NvencContext *ctx = avctx->priv_data;
537 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
539 switch (avctx->codec->id) {
540 case AV_CODEC_ID_H264:
541 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
543 case AV_CODEC_ID_HEVC:
544 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
550 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11 || avctx->hw_frames_ctx || avctx->hw_device_ctx) {
551 AVHWFramesContext *frames_ctx;
552 AVHWDeviceContext *hwdev_ctx;
553 AVCUDADeviceContext *cuda_device_hwctx = NULL;
555 AVD3D11VADeviceContext *d3d11_device_hwctx = NULL;
559 if (avctx->hw_frames_ctx) {
560 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
561 if (frames_ctx->format == AV_PIX_FMT_CUDA)
562 cuda_device_hwctx = frames_ctx->device_ctx->hwctx;
564 else if (frames_ctx->format == AV_PIX_FMT_D3D11)
565 d3d11_device_hwctx = frames_ctx->device_ctx->hwctx;
568 return AVERROR(EINVAL);
569 } else if (avctx->hw_device_ctx) {
570 hwdev_ctx = (AVHWDeviceContext*)avctx->hw_device_ctx->data;
571 if (hwdev_ctx->type == AV_HWDEVICE_TYPE_CUDA)
572 cuda_device_hwctx = hwdev_ctx->hwctx;
574 else if (hwdev_ctx->type == AV_HWDEVICE_TYPE_D3D11VA)
575 d3d11_device_hwctx = hwdev_ctx->hwctx;
578 return AVERROR(EINVAL);
580 return AVERROR(EINVAL);
583 if (cuda_device_hwctx) {
584 ctx->cu_context = cuda_device_hwctx->cuda_ctx;
585 ctx->cu_stream = cuda_device_hwctx->stream;
588 else if (d3d11_device_hwctx) {
589 ctx->d3d11_device = d3d11_device_hwctx->device;
590 ID3D11Device_AddRef(ctx->d3d11_device);
594 ret = nvenc_open_session(avctx);
598 ret = nvenc_check_capabilities(avctx);
600 av_log(avctx, AV_LOG_FATAL, "Provided device doesn't support required NVENC features\n");
604 int i, nb_devices = 0;
606 if (CHECK_CU(dl_fn->cuda_dl->cuInit(0)) < 0)
607 return AVERROR_UNKNOWN;
609 if (CHECK_CU(dl_fn->cuda_dl->cuDeviceGetCount(&nb_devices)) < 0)
610 return AVERROR_UNKNOWN;
613 av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
614 return AVERROR_EXTERNAL;
617 av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", nb_devices);
619 dl_fn->nvenc_device_count = 0;
620 for (i = 0; i < nb_devices; ++i) {
621 if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
625 if (ctx->device == LIST_DEVICES)
628 if (!dl_fn->nvenc_device_count) {
629 av_log(avctx, AV_LOG_FATAL, "No capable devices found\n");
630 return AVERROR_EXTERNAL;
633 av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->device, nb_devices);
634 return AVERROR(EINVAL);
640 typedef struct GUIDTuple {
645 #define PRESET_ALIAS(alias, name, ...) \
646 [PRESET_ ## alias] = { NV_ENC_PRESET_ ## name ## _GUID, __VA_ARGS__ }
648 #define PRESET(name, ...) PRESET_ALIAS(name, name, __VA_ARGS__)
650 static void nvenc_map_preset(NvencContext *ctx)
652 GUIDTuple presets[] = {
657 PRESET_ALIAS(SLOW, HQ, NVENC_TWO_PASSES),
658 PRESET_ALIAS(MEDIUM, HQ, NVENC_ONE_PASS),
659 PRESET_ALIAS(FAST, HP, NVENC_ONE_PASS),
660 PRESET(LOW_LATENCY_DEFAULT, NVENC_LOWLATENCY),
661 PRESET(LOW_LATENCY_HP, NVENC_LOWLATENCY),
662 PRESET(LOW_LATENCY_HQ, NVENC_LOWLATENCY),
663 PRESET(LOSSLESS_DEFAULT, NVENC_LOSSLESS),
664 PRESET(LOSSLESS_HP, NVENC_LOSSLESS),
665 #ifdef NVENC_HAVE_NEW_PRESETS
676 GUIDTuple *t = &presets[ctx->preset];
678 ctx->init_encode_params.presetGUID = t->guid;
679 ctx->flags = t->flags;
685 static av_cold void set_constqp(AVCodecContext *avctx)
687 NvencContext *ctx = avctx->priv_data;
688 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
690 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
692 if (ctx->init_qp_p >= 0) {
693 rc->constQP.qpInterP = ctx->init_qp_p;
694 if (ctx->init_qp_i >= 0 && ctx->init_qp_b >= 0) {
695 rc->constQP.qpIntra = ctx->init_qp_i;
696 rc->constQP.qpInterB = ctx->init_qp_b;
697 } else if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
698 rc->constQP.qpIntra = av_clip(
699 rc->constQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
700 rc->constQP.qpInterB = av_clip(
701 rc->constQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
703 rc->constQP.qpIntra = rc->constQP.qpInterP;
704 rc->constQP.qpInterB = rc->constQP.qpInterP;
706 } else if (ctx->cqp >= 0) {
707 rc->constQP.qpInterP = rc->constQP.qpInterB = rc->constQP.qpIntra = ctx->cqp;
708 if (avctx->b_quant_factor != 0.0)
709 rc->constQP.qpInterB = av_clip(ctx->cqp * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
710 if (avctx->i_quant_factor != 0.0)
711 rc->constQP.qpIntra = av_clip(ctx->cqp * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
718 static av_cold void set_vbr(AVCodecContext *avctx)
720 NvencContext *ctx = avctx->priv_data;
721 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
724 if (avctx->qmin >= 0 && avctx->qmax >= 0) {
728 rc->minQP.qpInterB = avctx->qmin;
729 rc->minQP.qpInterP = avctx->qmin;
730 rc->minQP.qpIntra = avctx->qmin;
732 rc->maxQP.qpInterB = avctx->qmax;
733 rc->maxQP.qpInterP = avctx->qmax;
734 rc->maxQP.qpIntra = avctx->qmax;
736 qp_inter_p = (avctx->qmax + 3 * avctx->qmin) / 4; // biased towards Qmin
737 } else if (avctx->qmin >= 0) {
740 rc->minQP.qpInterB = avctx->qmin;
741 rc->minQP.qpInterP = avctx->qmin;
742 rc->minQP.qpIntra = avctx->qmin;
744 qp_inter_p = avctx->qmin;
746 qp_inter_p = 26; // default to 26
749 rc->enableInitialRCQP = 1;
751 if (ctx->init_qp_p < 0) {
752 rc->initialRCQP.qpInterP = qp_inter_p;
754 rc->initialRCQP.qpInterP = ctx->init_qp_p;
757 if (ctx->init_qp_i < 0) {
758 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
759 rc->initialRCQP.qpIntra = av_clip(
760 rc->initialRCQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
762 rc->initialRCQP.qpIntra = rc->initialRCQP.qpInterP;
765 rc->initialRCQP.qpIntra = ctx->init_qp_i;
768 if (ctx->init_qp_b < 0) {
769 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
770 rc->initialRCQP.qpInterB = av_clip(
771 rc->initialRCQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
773 rc->initialRCQP.qpInterB = rc->initialRCQP.qpInterP;
776 rc->initialRCQP.qpInterB = ctx->init_qp_b;
780 static av_cold void set_lossless(AVCodecContext *avctx)
782 NvencContext *ctx = avctx->priv_data;
783 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
785 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
786 rc->constQP.qpInterB = 0;
787 rc->constQP.qpInterP = 0;
788 rc->constQP.qpIntra = 0;
794 static void nvenc_override_rate_control(AVCodecContext *avctx)
796 NvencContext *ctx = avctx->priv_data;
797 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
800 case NV_ENC_PARAMS_RC_CONSTQP:
803 case NV_ENC_PARAMS_RC_VBR_MINQP:
804 if (avctx->qmin < 0) {
805 av_log(avctx, AV_LOG_WARNING,
806 "The variable bitrate rate-control requires "
807 "the 'qmin' option set.\n");
812 case NV_ENC_PARAMS_RC_VBR_HQ:
813 case NV_ENC_PARAMS_RC_VBR:
816 case NV_ENC_PARAMS_RC_CBR:
817 case NV_ENC_PARAMS_RC_CBR_HQ:
818 case NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ:
822 rc->rateControlMode = ctx->rc;
825 static av_cold int nvenc_recalc_surfaces(AVCodecContext *avctx)
827 NvencContext *ctx = avctx->priv_data;
828 // default minimum of 4 surfaces
829 // multiply by 2 for number of NVENCs on gpu (hardcode to 2)
830 // another multiply by 2 to avoid blocking next PBB group
831 int nb_surfaces = FFMAX(4, ctx->encode_config.frameIntervalP * 2 * 2);
834 if (ctx->rc_lookahead > 0) {
835 // +1 is to account for lkd_bound calculation later
836 // +4 is to allow sufficient pipelining with lookahead
837 nb_surfaces = FFMAX(1, FFMAX(nb_surfaces, ctx->rc_lookahead + ctx->encode_config.frameIntervalP + 1 + 4));
838 if (nb_surfaces > ctx->nb_surfaces && ctx->nb_surfaces > 0)
840 av_log(avctx, AV_LOG_WARNING,
841 "Defined rc_lookahead requires more surfaces, "
842 "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
844 ctx->nb_surfaces = FFMAX(nb_surfaces, ctx->nb_surfaces);
846 if (ctx->encode_config.frameIntervalP > 1 && ctx->nb_surfaces < nb_surfaces && ctx->nb_surfaces > 0)
848 av_log(avctx, AV_LOG_WARNING,
849 "Defined b-frame requires more surfaces, "
850 "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
851 ctx->nb_surfaces = FFMAX(ctx->nb_surfaces, nb_surfaces);
853 else if (ctx->nb_surfaces <= 0)
854 ctx->nb_surfaces = nb_surfaces;
855 // otherwise use user specified value
858 ctx->nb_surfaces = FFMAX(1, FFMIN(MAX_REGISTERED_FRAMES, ctx->nb_surfaces));
859 ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
864 static av_cold void nvenc_setup_rate_control(AVCodecContext *avctx)
866 NvencContext *ctx = avctx->priv_data;
868 if (avctx->global_quality > 0)
869 av_log(avctx, AV_LOG_WARNING, "Using global_quality with nvenc is deprecated. Use qp instead.\n");
871 if (ctx->cqp < 0 && avctx->global_quality > 0)
872 ctx->cqp = avctx->global_quality;
874 if (avctx->bit_rate > 0) {
875 ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
876 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
877 ctx->encode_config.rcParams.maxBitRate = ctx->encode_config.rcParams.averageBitRate;
880 if (avctx->rc_max_rate > 0)
881 ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
883 #ifdef NVENC_HAVE_MULTIPASS
884 ctx->encode_config.rcParams.multiPass = ctx->multipass;
885 if (ctx->encode_config.rcParams.multiPass != NV_ENC_MULTI_PASS_DISABLED)
886 ctx->flags |= NVENC_TWO_PASSES;
890 if (ctx->flags & NVENC_ONE_PASS)
892 if (ctx->flags & NVENC_TWO_PASSES)
895 if (ctx->twopass < 0)
896 ctx->twopass = (ctx->flags & NVENC_LOWLATENCY) != 0;
900 ctx->rc = NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ;
902 ctx->rc = NV_ENC_PARAMS_RC_CBR;
904 } else if (ctx->cqp >= 0) {
905 ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
906 } else if (ctx->twopass) {
907 ctx->rc = NV_ENC_PARAMS_RC_VBR_HQ;
908 } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
909 ctx->rc = NV_ENC_PARAMS_RC_VBR_MINQP;
913 if (ctx->rc >= 0 && ctx->rc & RC_MODE_DEPRECATED) {
914 av_log(avctx, AV_LOG_WARNING, "Specified rc mode is deprecated.\n");
915 av_log(avctx, AV_LOG_WARNING, "\tll_2pass_quality -> cbr_ld_hq\n");
916 av_log(avctx, AV_LOG_WARNING, "\tll_2pass_size -> cbr_hq\n");
917 av_log(avctx, AV_LOG_WARNING, "\tvbr_2pass -> vbr_hq\n");
918 av_log(avctx, AV_LOG_WARNING, "\tvbr_minqp -> (no replacement)\n");
920 ctx->rc &= ~RC_MODE_DEPRECATED;
923 #ifdef NVENC_HAVE_LDKFS
925 ctx->encode_config.rcParams.lowDelayKeyFrameScale = ctx->ldkfs;
928 if (ctx->flags & NVENC_LOSSLESS) {
930 } else if (ctx->rc >= 0) {
931 nvenc_override_rate_control(avctx);
933 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
937 if (avctx->rc_buffer_size > 0) {
938 ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
939 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
940 avctx->rc_buffer_size = ctx->encode_config.rcParams.vbvBufferSize = 2 * ctx->encode_config.rcParams.averageBitRate;
944 ctx->encode_config.rcParams.enableAQ = 1;
945 ctx->encode_config.rcParams.aqStrength = ctx->aq_strength;
946 av_log(avctx, AV_LOG_VERBOSE, "AQ enabled.\n");
949 if (ctx->temporal_aq) {
950 ctx->encode_config.rcParams.enableTemporalAQ = 1;
951 av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ enabled.\n");
954 if (ctx->rc_lookahead > 0) {
955 int lkd_bound = FFMIN(ctx->nb_surfaces, ctx->async_depth) -
956 ctx->encode_config.frameIntervalP - 4;
959 av_log(avctx, AV_LOG_WARNING,
960 "Lookahead not enabled. Increase buffer delay (-delay).\n");
962 ctx->encode_config.rcParams.enableLookahead = 1;
963 ctx->encode_config.rcParams.lookaheadDepth = av_clip(ctx->rc_lookahead, 0, lkd_bound);
964 ctx->encode_config.rcParams.disableIadapt = ctx->no_scenecut;
965 ctx->encode_config.rcParams.disableBadapt = !ctx->b_adapt;
966 av_log(avctx, AV_LOG_VERBOSE,
967 "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",
968 ctx->encode_config.rcParams.lookaheadDepth,
969 ctx->encode_config.rcParams.disableIadapt ? "disabled" : "enabled",
970 ctx->encode_config.rcParams.disableBadapt ? "disabled" : "enabled");
974 if (ctx->strict_gop) {
975 ctx->encode_config.rcParams.strictGOPTarget = 1;
976 av_log(avctx, AV_LOG_VERBOSE, "Strict GOP target enabled.\n");
980 ctx->encode_config.rcParams.enableNonRefP = 1;
982 if (ctx->zerolatency)
983 ctx->encode_config.rcParams.zeroReorderDelay = 1;
986 //convert from float to fixed point 8.8
987 int tmp_quality = (int)(ctx->quality * 256.0f);
988 ctx->encode_config.rcParams.targetQuality = (uint8_t)(tmp_quality >> 8);
989 ctx->encode_config.rcParams.targetQualityLSB = (uint8_t)(tmp_quality & 0xff);
991 av_log(avctx, AV_LOG_VERBOSE, "CQ(%d) mode enabled.\n", tmp_quality);
993 //CQ mode shall discard avg bitrate & honor max bitrate;
994 ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate = 0;
995 ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
999 static av_cold int nvenc_setup_h264_config(AVCodecContext *avctx)
1001 NvencContext *ctx = avctx->priv_data;
1002 NV_ENC_CONFIG *cc = &ctx->encode_config;
1003 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
1004 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
1006 vui->colourMatrix = avctx->colorspace;
1007 vui->colourPrimaries = avctx->color_primaries;
1008 vui->transferCharacteristics = avctx->color_trc;
1009 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
1010 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
1012 vui->colourDescriptionPresentFlag =
1013 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
1015 vui->videoSignalTypePresentFlag =
1016 (vui->colourDescriptionPresentFlag
1017 || vui->videoFormat != 5
1018 || vui->videoFullRangeFlag != 0);
1020 h264->sliceMode = 3;
1021 h264->sliceModeData = 1;
1023 h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
1024 h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
1025 h264->outputAUD = ctx->aud;
1027 if (ctx->dpb_size >= 0) {
1028 /* 0 means "let the hardware decide" */
1029 h264->maxNumRefFrames = ctx->dpb_size;
1031 if (avctx->gop_size >= 0) {
1032 h264->idrPeriod = cc->gopLength;
1035 if (IS_CBR(cc->rcParams.rateControlMode)) {
1036 h264->outputBufferingPeriodSEI = 1;
1039 h264->outputPictureTimingSEI = 1;
1041 if (cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ ||
1042 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_HQ ||
1043 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_VBR_HQ) {
1044 h264->adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
1045 h264->fmoMode = NV_ENC_H264_FMO_DISABLE;
1048 if (ctx->flags & NVENC_LOSSLESS) {
1049 h264->qpPrimeYZeroTransformBypassFlag = 1;
1051 switch(ctx->profile) {
1052 case NV_ENC_H264_PROFILE_BASELINE:
1053 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
1054 avctx->profile = FF_PROFILE_H264_BASELINE;
1056 case NV_ENC_H264_PROFILE_MAIN:
1057 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
1058 avctx->profile = FF_PROFILE_H264_MAIN;
1060 case NV_ENC_H264_PROFILE_HIGH:
1061 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
1062 avctx->profile = FF_PROFILE_H264_HIGH;
1064 case NV_ENC_H264_PROFILE_HIGH_444P:
1065 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1066 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
1071 // force setting profile as high444p if input is AV_PIX_FMT_YUV444P
1072 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P) {
1073 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1074 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
1077 h264->chromaFormatIDC = avctx->profile == FF_PROFILE_H264_HIGH_444_PREDICTIVE ? 3 : 1;
1079 h264->level = ctx->level;
1081 if (ctx->coder >= 0)
1082 h264->entropyCodingMode = ctx->coder;
1084 #ifdef NVENC_HAVE_BFRAME_REF_MODE
1085 h264->useBFramesAsRef = ctx->b_ref_mode;
1088 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
1089 h264->numRefL0 = avctx->refs;
1090 h264->numRefL1 = avctx->refs;
1096 static av_cold int nvenc_setup_hevc_config(AVCodecContext *avctx)
1098 NvencContext *ctx = avctx->priv_data;
1099 NV_ENC_CONFIG *cc = &ctx->encode_config;
1100 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
1101 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
1103 vui->colourMatrix = avctx->colorspace;
1104 vui->colourPrimaries = avctx->color_primaries;
1105 vui->transferCharacteristics = avctx->color_trc;
1106 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
1107 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
1109 vui->colourDescriptionPresentFlag =
1110 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
1112 vui->videoSignalTypePresentFlag =
1113 (vui->colourDescriptionPresentFlag
1114 || vui->videoFormat != 5
1115 || vui->videoFullRangeFlag != 0);
1117 hevc->sliceMode = 3;
1118 hevc->sliceModeData = 1;
1120 hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
1121 hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
1122 hevc->outputAUD = ctx->aud;
1124 if (ctx->dpb_size >= 0) {
1125 /* 0 means "let the hardware decide" */
1126 hevc->maxNumRefFramesInDPB = ctx->dpb_size;
1128 if (avctx->gop_size >= 0) {
1129 hevc->idrPeriod = cc->gopLength;
1132 if (IS_CBR(cc->rcParams.rateControlMode)) {
1133 hevc->outputBufferingPeriodSEI = 1;
1136 hevc->outputPictureTimingSEI = 1;
1138 switch (ctx->profile) {
1139 case NV_ENC_HEVC_PROFILE_MAIN:
1140 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
1141 avctx->profile = FF_PROFILE_HEVC_MAIN;
1143 case NV_ENC_HEVC_PROFILE_MAIN_10:
1144 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1145 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
1147 case NV_ENC_HEVC_PROFILE_REXT:
1148 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1149 avctx->profile = FF_PROFILE_HEVC_REXT;
1153 // force setting profile as main10 if input is 10 bit
1154 if (IS_10BIT(ctx->data_pix_fmt)) {
1155 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1156 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
1159 // force setting profile as rext if input is yuv444
1160 if (IS_YUV444(ctx->data_pix_fmt)) {
1161 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1162 avctx->profile = FF_PROFILE_HEVC_REXT;
1165 hevc->chromaFormatIDC = IS_YUV444(ctx->data_pix_fmt) ? 3 : 1;
1167 hevc->pixelBitDepthMinus8 = IS_10BIT(ctx->data_pix_fmt) ? 2 : 0;
1169 hevc->level = ctx->level;
1171 hevc->tier = ctx->tier;
1173 #ifdef NVENC_HAVE_HEVC_BFRAME_REF_MODE
1174 hevc->useBFramesAsRef = ctx->b_ref_mode;
1177 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
1178 hevc->numRefL0 = avctx->refs;
1179 hevc->numRefL1 = avctx->refs;
1185 static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx)
1187 switch (avctx->codec->id) {
1188 case AV_CODEC_ID_H264:
1189 return nvenc_setup_h264_config(avctx);
1190 case AV_CODEC_ID_HEVC:
1191 return nvenc_setup_hevc_config(avctx);
1192 /* Earlier switch/case will return if unknown codec is passed. */
1198 static void compute_dar(AVCodecContext *avctx, int *dw, int *dh) {
1204 if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0) {
1205 sw *= avctx->sample_aspect_ratio.num;
1206 sh *= avctx->sample_aspect_ratio.den;
1209 av_reduce(dw, dh, sw, sh, 1024 * 1024);
1212 static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
1214 NvencContext *ctx = avctx->priv_data;
1215 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1216 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1218 NV_ENC_PRESET_CONFIG preset_config = { 0 };
1219 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
1220 AVCPBProperties *cpb_props;
1224 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1225 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
1227 ctx->init_encode_params.encodeHeight = avctx->height;
1228 ctx->init_encode_params.encodeWidth = avctx->width;
1230 ctx->init_encode_params.encodeConfig = &ctx->encode_config;
1232 nvenc_map_preset(ctx);
1234 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
1235 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
1237 if (IS_SDK10_PRESET(ctx->preset)) {
1238 #ifdef NVENC_HAVE_NEW_PRESETS
1239 ctx->init_encode_params.tuningInfo = ctx->tuning_info;
1241 nv_status = p_nvenc->nvEncGetEncodePresetConfigEx(ctx->nvencoder,
1242 ctx->init_encode_params.encodeGUID,
1243 ctx->init_encode_params.presetGUID,
1244 ctx->init_encode_params.tuningInfo,
1248 #ifdef NVENC_HAVE_NEW_PRESETS
1249 // Turn off tuning info parameter if older presets are on
1250 ctx->init_encode_params.tuningInfo = 0;
1253 nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder,
1254 ctx->init_encode_params.encodeGUID,
1255 ctx->init_encode_params.presetGUID,
1258 if (nv_status != NV_ENC_SUCCESS)
1259 return nvenc_print_error(avctx, nv_status, "Cannot get the preset configuration");
1261 memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
1263 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1265 compute_dar(avctx, &dw, &dh);
1266 ctx->init_encode_params.darHeight = dh;
1267 ctx->init_encode_params.darWidth = dw;
1269 if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {
1270 ctx->init_encode_params.frameRateNum = avctx->framerate.num;
1271 ctx->init_encode_params.frameRateDen = avctx->framerate.den;
1273 ctx->init_encode_params.frameRateNum = avctx->time_base.den;
1274 ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
1277 ctx->init_encode_params.enableEncodeAsync = 0;
1278 ctx->init_encode_params.enablePTD = 1;
1280 #ifdef NVENC_HAVE_NEW_PRESETS
1281 /* If lookahead isn't set from CLI, use value from preset.
1282 * P6 & P7 presets may enable lookahead for better quality.
1284 if (ctx->rc_lookahead == 0 && ctx->encode_config.rcParams.enableLookahead)
1285 ctx->rc_lookahead = ctx->encode_config.rcParams.lookaheadDepth;
1287 if (ctx->init_encode_params.tuningInfo == NV_ENC_TUNING_INFO_LOSSLESS)
1288 ctx->flags |= NVENC_LOSSLESS;
1291 if (ctx->weighted_pred == 1)
1292 ctx->init_encode_params.enableWeightedPrediction = 1;
1294 if (ctx->bluray_compat) {
1296 ctx->dpb_size = FFMIN(FFMAX(avctx->refs, 0), 6);
1297 avctx->max_b_frames = FFMIN(avctx->max_b_frames, 3);
1298 switch (avctx->codec->id) {
1299 case AV_CODEC_ID_H264:
1300 /* maximum level depends on used resolution */
1302 case AV_CODEC_ID_HEVC:
1303 ctx->level = NV_ENC_LEVEL_HEVC_51;
1304 ctx->tier = NV_ENC_TIER_HEVC_HIGH;
1309 if (avctx->gop_size > 0) {
1310 if (avctx->max_b_frames >= 0) {
1311 /* 0 is intra-only, 1 is I/P only, 2 is one B-Frame, 3 two B-frames, and so on. */
1312 ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
1315 ctx->encode_config.gopLength = avctx->gop_size;
1316 } else if (avctx->gop_size == 0) {
1317 ctx->encode_config.frameIntervalP = 0;
1318 ctx->encode_config.gopLength = 1;
1321 nvenc_recalc_surfaces(avctx);
1323 nvenc_setup_rate_control(avctx);
1325 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1326 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
1328 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
1331 res = nvenc_setup_codec_config(avctx);
1335 res = nvenc_push_context(avctx);
1339 nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
1340 if (nv_status != NV_ENC_SUCCESS) {
1341 nvenc_pop_context(avctx);
1342 return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
1345 #ifdef NVENC_HAVE_CUSTREAM_PTR
1346 if (ctx->cu_context) {
1347 nv_status = p_nvenc->nvEncSetIOCudaStreams(ctx->nvencoder, &ctx->cu_stream, &ctx->cu_stream);
1348 if (nv_status != NV_ENC_SUCCESS) {
1349 nvenc_pop_context(avctx);
1350 return nvenc_print_error(avctx, nv_status, "SetIOCudaStreams failed");
1355 res = nvenc_pop_context(avctx);
1359 if (ctx->encode_config.frameIntervalP > 1)
1360 avctx->has_b_frames = 2;
1362 if (ctx->encode_config.rcParams.averageBitRate > 0)
1363 avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
1365 cpb_props = ff_add_cpb_side_data(avctx);
1367 return AVERROR(ENOMEM);
1368 cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
1369 cpb_props->avg_bitrate = avctx->bit_rate;
1370 cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
1375 static NV_ENC_BUFFER_FORMAT nvenc_map_buffer_format(enum AVPixelFormat pix_fmt)
1378 case AV_PIX_FMT_YUV420P:
1379 return NV_ENC_BUFFER_FORMAT_YV12_PL;
1380 case AV_PIX_FMT_NV12:
1381 return NV_ENC_BUFFER_FORMAT_NV12_PL;
1382 case AV_PIX_FMT_P010:
1383 case AV_PIX_FMT_P016:
1384 return NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1385 case AV_PIX_FMT_YUV444P:
1386 return NV_ENC_BUFFER_FORMAT_YUV444_PL;
1387 case AV_PIX_FMT_YUV444P16:
1388 return NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1389 case AV_PIX_FMT_0RGB32:
1390 return NV_ENC_BUFFER_FORMAT_ARGB;
1391 case AV_PIX_FMT_0BGR32:
1392 return NV_ENC_BUFFER_FORMAT_ABGR;
1394 return NV_ENC_BUFFER_FORMAT_UNDEFINED;
1398 static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
1400 NvencContext *ctx = avctx->priv_data;
1401 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1402 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1403 NvencSurface* tmp_surface = &ctx->surfaces[idx];
1405 NVENCSTATUS nv_status;
1406 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
1407 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1409 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1410 ctx->surfaces[idx].in_ref = av_frame_alloc();
1411 if (!ctx->surfaces[idx].in_ref)
1412 return AVERROR(ENOMEM);
1414 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1416 ctx->surfaces[idx].format = nvenc_map_buffer_format(ctx->data_pix_fmt);
1417 if (ctx->surfaces[idx].format == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1418 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1419 av_get_pix_fmt_name(ctx->data_pix_fmt));
1420 return AVERROR(EINVAL);
1423 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1424 allocSurf.width = avctx->width;
1425 allocSurf.height = avctx->height;
1426 allocSurf.bufferFmt = ctx->surfaces[idx].format;
1428 nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
1429 if (nv_status != NV_ENC_SUCCESS) {
1430 return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
1433 ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
1434 ctx->surfaces[idx].width = allocSurf.width;
1435 ctx->surfaces[idx].height = allocSurf.height;
1438 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
1439 if (nv_status != NV_ENC_SUCCESS) {
1440 int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
1441 if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
1442 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
1443 av_frame_free(&ctx->surfaces[idx].in_ref);
1447 ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1448 ctx->surfaces[idx].size = allocOut.size;
1450 av_fifo_generic_write(ctx->unused_surface_queue, &tmp_surface, sizeof(tmp_surface), NULL);
1455 static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx)
1457 NvencContext *ctx = avctx->priv_data;
1458 int i, res = 0, res2;
1460 ctx->surfaces = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->surfaces));
1462 return AVERROR(ENOMEM);
1464 ctx->timestamp_list = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
1465 if (!ctx->timestamp_list)
1466 return AVERROR(ENOMEM);
1468 ctx->unused_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1469 if (!ctx->unused_surface_queue)
1470 return AVERROR(ENOMEM);
1472 ctx->output_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1473 if (!ctx->output_surface_queue)
1474 return AVERROR(ENOMEM);
1475 ctx->output_surface_ready_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1476 if (!ctx->output_surface_ready_queue)
1477 return AVERROR(ENOMEM);
1479 res = nvenc_push_context(avctx);
1483 for (i = 0; i < ctx->nb_surfaces; i++) {
1484 if ((res = nvenc_alloc_surface(avctx, i)) < 0)
1489 res2 = nvenc_pop_context(avctx);
1496 static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
1498 NvencContext *ctx = avctx->priv_data;
1499 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1500 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1502 NVENCSTATUS nv_status;
1503 uint32_t outSize = 0;
1504 char tmpHeader[256];
1505 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1506 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1508 payload.spsppsBuffer = tmpHeader;
1509 payload.inBufferSize = sizeof(tmpHeader);
1510 payload.outSPSPPSPayloadSize = &outSize;
1512 nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
1513 if (nv_status != NV_ENC_SUCCESS) {
1514 return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
1517 avctx->extradata_size = outSize;
1518 avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
1520 if (!avctx->extradata) {
1521 return AVERROR(ENOMEM);
1524 memcpy(avctx->extradata, tmpHeader, outSize);
1529 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
1531 NvencContext *ctx = avctx->priv_data;
1532 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1533 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1536 /* the encoder has to be flushed before it can be closed */
1537 if (ctx->nvencoder) {
1538 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
1539 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
1541 res = nvenc_push_context(avctx);
1545 p_nvenc->nvEncEncodePicture(ctx->nvencoder, ¶ms);
1548 av_fifo_freep(&ctx->timestamp_list);
1549 av_fifo_freep(&ctx->output_surface_ready_queue);
1550 av_fifo_freep(&ctx->output_surface_queue);
1551 av_fifo_freep(&ctx->unused_surface_queue);
1553 if (ctx->surfaces && (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11)) {
1554 for (i = 0; i < ctx->nb_registered_frames; i++) {
1555 if (ctx->registered_frames[i].mapped)
1556 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[i].in_map.mappedResource);
1557 if (ctx->registered_frames[i].regptr)
1558 p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1560 ctx->nb_registered_frames = 0;
1563 if (ctx->surfaces) {
1564 for (i = 0; i < ctx->nb_surfaces; ++i) {
1565 if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
1566 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
1567 av_frame_free(&ctx->surfaces[i].in_ref);
1568 p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
1571 av_freep(&ctx->surfaces);
1572 ctx->nb_surfaces = 0;
1574 av_frame_free(&ctx->frame);
1576 if (ctx->nvencoder) {
1577 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1579 res = nvenc_pop_context(avctx);
1583 ctx->nvencoder = NULL;
1585 if (ctx->cu_context_internal)
1586 CHECK_CU(dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal));
1587 ctx->cu_context = ctx->cu_context_internal = NULL;
1590 if (ctx->d3d11_device) {
1591 ID3D11Device_Release(ctx->d3d11_device);
1592 ctx->d3d11_device = NULL;
1596 nvenc_free_functions(&dl_fn->nvenc_dl);
1597 cuda_free_functions(&dl_fn->cuda_dl);
1599 dl_fn->nvenc_device_count = 0;
1601 av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
1606 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
1608 NvencContext *ctx = avctx->priv_data;
1611 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1612 AVHWFramesContext *frames_ctx;
1613 if (!avctx->hw_frames_ctx) {
1614 av_log(avctx, AV_LOG_ERROR,
1615 "hw_frames_ctx must be set when using GPU frames as input\n");
1616 return AVERROR(EINVAL);
1618 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1619 if (frames_ctx->format != avctx->pix_fmt) {
1620 av_log(avctx, AV_LOG_ERROR,
1621 "hw_frames_ctx must match the GPU frame type\n");
1622 return AVERROR(EINVAL);
1624 ctx->data_pix_fmt = frames_ctx->sw_format;
1626 ctx->data_pix_fmt = avctx->pix_fmt;
1629 ctx->frame = av_frame_alloc();
1631 return AVERROR(ENOMEM);
1633 if ((ret = nvenc_load_libraries(avctx)) < 0)
1636 if ((ret = nvenc_setup_device(avctx)) < 0)
1639 if ((ret = nvenc_setup_encoder(avctx)) < 0)
1642 if ((ret = nvenc_setup_surfaces(avctx)) < 0)
1645 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1646 if ((ret = nvenc_setup_extradata(avctx)) < 0)
1653 static NvencSurface *get_free_frame(NvencContext *ctx)
1655 NvencSurface *tmp_surf;
1657 if (!(av_fifo_size(ctx->unused_surface_queue) > 0))
1661 av_fifo_generic_read(ctx->unused_surface_queue, &tmp_surf, sizeof(tmp_surf), NULL);
1665 static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *nv_surface,
1666 NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params, const AVFrame *frame)
1668 int dst_linesize[4] = {
1669 lock_buffer_params->pitch,
1670 lock_buffer_params->pitch,
1671 lock_buffer_params->pitch,
1672 lock_buffer_params->pitch
1674 uint8_t *dst_data[4];
1677 if (frame->format == AV_PIX_FMT_YUV420P)
1678 dst_linesize[1] = dst_linesize[2] >>= 1;
1680 ret = av_image_fill_pointers(dst_data, frame->format, nv_surface->height,
1681 lock_buffer_params->bufferDataPtr, dst_linesize);
1685 if (frame->format == AV_PIX_FMT_YUV420P)
1686 FFSWAP(uint8_t*, dst_data[1], dst_data[2]);
1688 av_image_copy(dst_data, dst_linesize,
1689 (const uint8_t**)frame->data, frame->linesize, frame->format,
1690 avctx->width, avctx->height);
1695 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1697 NvencContext *ctx = avctx->priv_data;
1698 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1699 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1700 NVENCSTATUS nv_status;
1704 if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1705 for (first_round = 1; first_round >= 0; first_round--) {
1706 for (i = 0; i < ctx->nb_registered_frames; i++) {
1707 if (!ctx->registered_frames[i].mapped) {
1708 if (ctx->registered_frames[i].regptr) {
1711 nv_status = p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1712 if (nv_status != NV_ENC_SUCCESS)
1713 return nvenc_print_error(avctx, nv_status, "Failed unregistering unused input resource");
1714 ctx->registered_frames[i].ptr = NULL;
1715 ctx->registered_frames[i].regptr = NULL;
1722 return ctx->nb_registered_frames++;
1725 av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1726 return AVERROR(ENOMEM);
1729 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1731 NvencContext *ctx = avctx->priv_data;
1732 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1733 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1735 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frame->hw_frames_ctx->data;
1736 NV_ENC_REGISTER_RESOURCE reg;
1739 for (i = 0; i < ctx->nb_registered_frames; i++) {
1740 if (avctx->pix_fmt == AV_PIX_FMT_CUDA && ctx->registered_frames[i].ptr == frame->data[0])
1742 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])
1746 idx = nvenc_find_free_reg_resource(avctx);
1750 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1751 reg.width = frames_ctx->width;
1752 reg.height = frames_ctx->height;
1753 reg.pitch = frame->linesize[0];
1754 reg.resourceToRegister = frame->data[0];
1756 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1757 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1759 else if (avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1760 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX;
1761 reg.subResourceIndex = (intptr_t)frame->data[1];
1764 reg.bufferFormat = nvenc_map_buffer_format(frames_ctx->sw_format);
1765 if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1766 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1767 av_get_pix_fmt_name(frames_ctx->sw_format));
1768 return AVERROR(EINVAL);
1771 ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, ®);
1772 if (ret != NV_ENC_SUCCESS) {
1773 nvenc_print_error(avctx, ret, "Error registering an input resource");
1774 return AVERROR_UNKNOWN;
1777 ctx->registered_frames[idx].ptr = frame->data[0];
1778 ctx->registered_frames[idx].ptr_index = reg.subResourceIndex;
1779 ctx->registered_frames[idx].regptr = reg.registeredResource;
1783 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1784 NvencSurface *nvenc_frame)
1786 NvencContext *ctx = avctx->priv_data;
1787 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1788 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1791 NVENCSTATUS nv_status;
1793 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1794 int reg_idx = nvenc_register_frame(avctx, frame);
1796 av_log(avctx, AV_LOG_ERROR, "Could not register an input HW frame\n");
1800 res = av_frame_ref(nvenc_frame->in_ref, frame);
1804 if (!ctx->registered_frames[reg_idx].mapped) {
1805 ctx->registered_frames[reg_idx].in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1806 ctx->registered_frames[reg_idx].in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1807 nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &ctx->registered_frames[reg_idx].in_map);
1808 if (nv_status != NV_ENC_SUCCESS) {
1809 av_frame_unref(nvenc_frame->in_ref);
1810 return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
1814 ctx->registered_frames[reg_idx].mapped += 1;
1816 nvenc_frame->reg_idx = reg_idx;
1817 nvenc_frame->input_surface = ctx->registered_frames[reg_idx].in_map.mappedResource;
1818 nvenc_frame->format = ctx->registered_frames[reg_idx].in_map.mappedBufferFmt;
1819 nvenc_frame->pitch = frame->linesize[0];
1823 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1825 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1826 lockBufferParams.inputBuffer = nvenc_frame->input_surface;
1828 nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
1829 if (nv_status != NV_ENC_SUCCESS) {
1830 return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
1833 nvenc_frame->pitch = lockBufferParams.pitch;
1834 res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
1836 nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
1837 if (nv_status != NV_ENC_SUCCESS) {
1838 return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
1845 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1846 NV_ENC_PIC_PARAMS *params,
1847 NV_ENC_SEI_PAYLOAD *sei_data,
1850 NvencContext *ctx = avctx->priv_data;
1852 switch (avctx->codec->id) {
1853 case AV_CODEC_ID_H264:
1854 params->codecPicParams.h264PicParams.sliceMode =
1855 ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1856 params->codecPicParams.h264PicParams.sliceModeData =
1857 ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1858 if (sei_count > 0) {
1859 params->codecPicParams.h264PicParams.seiPayloadArray = sei_data;
1860 params->codecPicParams.h264PicParams.seiPayloadArrayCnt = sei_count;
1864 case AV_CODEC_ID_HEVC:
1865 params->codecPicParams.hevcPicParams.sliceMode =
1866 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1867 params->codecPicParams.hevcPicParams.sliceModeData =
1868 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1869 if (sei_count > 0) {
1870 params->codecPicParams.hevcPicParams.seiPayloadArray = sei_data;
1871 params->codecPicParams.hevcPicParams.seiPayloadArrayCnt = sei_count;
1878 static inline void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
1880 av_fifo_generic_write(queue, ×tamp, sizeof(timestamp), NULL);
1883 static inline int64_t timestamp_queue_dequeue(AVFifoBuffer* queue)
1885 int64_t timestamp = AV_NOPTS_VALUE;
1886 if (av_fifo_size(queue) > 0)
1887 av_fifo_generic_read(queue, ×tamp, sizeof(timestamp), NULL);
1892 static int nvenc_set_timestamp(AVCodecContext *avctx,
1893 NV_ENC_LOCK_BITSTREAM *params,
1896 NvencContext *ctx = avctx->priv_data;
1898 pkt->pts = params->outputTimeStamp;
1899 pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
1901 pkt->dts -= FFMAX(avctx->max_b_frames, 0) * FFMIN(avctx->ticks_per_frame, 1);
1906 static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
1908 NvencContext *ctx = avctx->priv_data;
1909 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1910 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1912 uint32_t slice_mode_data;
1913 uint32_t *slice_offsets = NULL;
1914 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1915 NVENCSTATUS nv_status;
1918 enum AVPictureType pict_type;
1920 switch (avctx->codec->id) {
1921 case AV_CODEC_ID_H264:
1922 slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1924 case AV_CODEC_ID_H265:
1925 slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1928 av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
1929 res = AVERROR(EINVAL);
1932 slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
1934 if (!slice_offsets) {
1935 res = AVERROR(ENOMEM);
1939 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1941 lock_params.doNotWait = 0;
1942 lock_params.outputBitstream = tmpoutsurf->output_surface;
1943 lock_params.sliceOffsets = slice_offsets;
1945 nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
1946 if (nv_status != NV_ENC_SUCCESS) {
1947 res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
1951 res = av_new_packet(pkt, lock_params.bitstreamSizeInBytes);
1954 p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1958 memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1960 nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1961 if (nv_status != NV_ENC_SUCCESS) {
1962 res = nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
1967 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1968 ctx->registered_frames[tmpoutsurf->reg_idx].mapped -= 1;
1969 if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped == 0) {
1970 nv_status = p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[tmpoutsurf->reg_idx].in_map.mappedResource);
1971 if (nv_status != NV_ENC_SUCCESS) {
1972 res = nvenc_print_error(avctx, nv_status, "Failed unmapping input resource");
1975 } else if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped < 0) {
1980 av_frame_unref(tmpoutsurf->in_ref);
1982 tmpoutsurf->input_surface = NULL;
1985 switch (lock_params.pictureType) {
1986 case NV_ENC_PIC_TYPE_IDR:
1987 pkt->flags |= AV_PKT_FLAG_KEY;
1988 case NV_ENC_PIC_TYPE_I:
1989 pict_type = AV_PICTURE_TYPE_I;
1991 case NV_ENC_PIC_TYPE_P:
1992 pict_type = AV_PICTURE_TYPE_P;
1994 case NV_ENC_PIC_TYPE_B:
1995 pict_type = AV_PICTURE_TYPE_B;
1997 case NV_ENC_PIC_TYPE_BI:
1998 pict_type = AV_PICTURE_TYPE_BI;
2001 av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
2002 av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
2003 res = AVERROR_EXTERNAL;
2007 #if FF_API_CODED_FRAME
2008 FF_DISABLE_DEPRECATION_WARNINGS
2009 avctx->coded_frame->pict_type = pict_type;
2010 FF_ENABLE_DEPRECATION_WARNINGS
2013 ff_side_data_set_encoder_stats(pkt,
2014 (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
2016 res = nvenc_set_timestamp(avctx, &lock_params, pkt);
2020 av_free(slice_offsets);
2025 timestamp_queue_dequeue(ctx->timestamp_list);
2028 av_free(slice_offsets);
2033 static int output_ready(AVCodecContext *avctx, int flush)
2035 NvencContext *ctx = avctx->priv_data;
2036 int nb_ready, nb_pending;
2038 nb_ready = av_fifo_size(ctx->output_surface_ready_queue) / sizeof(NvencSurface*);
2039 nb_pending = av_fifo_size(ctx->output_surface_queue) / sizeof(NvencSurface*);
2041 return nb_ready > 0;
2042 return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
2045 static void reconfig_encoder(AVCodecContext *avctx, const AVFrame *frame)
2047 NvencContext *ctx = avctx->priv_data;
2048 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
2051 NV_ENC_RECONFIGURE_PARAMS params = { 0 };
2052 int needs_reconfig = 0;
2053 int needs_encode_config = 0;
2054 int reconfig_bitrate = 0, reconfig_dar = 0;
2057 params.version = NV_ENC_RECONFIGURE_PARAMS_VER;
2058 params.reInitEncodeParams = ctx->init_encode_params;
2060 compute_dar(avctx, &dw, &dh);
2061 if (dw != ctx->init_encode_params.darWidth || dh != ctx->init_encode_params.darHeight) {
2062 av_log(avctx, AV_LOG_VERBOSE,
2063 "aspect ratio change (DAR): %d:%d -> %d:%d\n",
2064 ctx->init_encode_params.darWidth,
2065 ctx->init_encode_params.darHeight, dw, dh);
2067 params.reInitEncodeParams.darHeight = dh;
2068 params.reInitEncodeParams.darWidth = dw;
2074 if (ctx->rc != NV_ENC_PARAMS_RC_CONSTQP && ctx->support_dyn_bitrate) {
2075 if (avctx->bit_rate > 0 && params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate != avctx->bit_rate) {
2076 av_log(avctx, AV_LOG_VERBOSE,
2077 "avg bitrate change: %d -> %d\n",
2078 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate,
2079 (uint32_t)avctx->bit_rate);
2081 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate = avctx->bit_rate;
2082 reconfig_bitrate = 1;
2085 if (avctx->rc_max_rate > 0 && ctx->encode_config.rcParams.maxBitRate != avctx->rc_max_rate) {
2086 av_log(avctx, AV_LOG_VERBOSE,
2087 "max bitrate change: %d -> %d\n",
2088 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate,
2089 (uint32_t)avctx->rc_max_rate);
2091 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate = avctx->rc_max_rate;
2092 reconfig_bitrate = 1;
2095 if (avctx->rc_buffer_size > 0 && ctx->encode_config.rcParams.vbvBufferSize != avctx->rc_buffer_size) {
2096 av_log(avctx, AV_LOG_VERBOSE,
2097 "vbv buffer size change: %d -> %d\n",
2098 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize,
2099 avctx->rc_buffer_size);
2101 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize = avctx->rc_buffer_size;
2102 reconfig_bitrate = 1;
2105 if (reconfig_bitrate) {
2106 params.resetEncoder = 1;
2107 params.forceIDR = 1;
2109 needs_encode_config = 1;
2114 if (!needs_encode_config)
2115 params.reInitEncodeParams.encodeConfig = NULL;
2117 if (needs_reconfig) {
2118 ret = p_nvenc->nvEncReconfigureEncoder(ctx->nvencoder, ¶ms);
2119 if (ret != NV_ENC_SUCCESS) {
2120 nvenc_print_error(avctx, ret, "failed to reconfigure nvenc");
2123 ctx->init_encode_params.darHeight = dh;
2124 ctx->init_encode_params.darWidth = dw;
2127 if (reconfig_bitrate) {
2128 ctx->encode_config.rcParams.averageBitRate = params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate;
2129 ctx->encode_config.rcParams.maxBitRate = params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate;
2130 ctx->encode_config.rcParams.vbvBufferSize = params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize;
2137 static int nvenc_send_frame(AVCodecContext *avctx, const AVFrame *frame)
2139 NVENCSTATUS nv_status;
2140 NvencSurface *tmp_out_surf, *in_surf;
2142 NV_ENC_SEI_PAYLOAD sei_data[8];
2146 NvencContext *ctx = avctx->priv_data;
2147 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
2148 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
2150 NV_ENC_PIC_PARAMS pic_params = { 0 };
2151 pic_params.version = NV_ENC_PIC_PARAMS_VER;
2153 if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
2154 return AVERROR(EINVAL);
2156 if (frame && frame->buf[0]) {
2157 in_surf = get_free_frame(ctx);
2159 return AVERROR(EAGAIN);
2161 res = nvenc_push_context(avctx);
2165 reconfig_encoder(avctx, frame);
2167 res = nvenc_upload_frame(avctx, frame, in_surf);
2169 res2 = nvenc_pop_context(avctx);
2176 pic_params.inputBuffer = in_surf->input_surface;
2177 pic_params.bufferFmt = in_surf->format;
2178 pic_params.inputWidth = in_surf->width;
2179 pic_params.inputHeight = in_surf->height;
2180 pic_params.inputPitch = in_surf->pitch;
2181 pic_params.outputBitstream = in_surf->output_surface;
2183 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
2184 if (frame->top_field_first)
2185 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
2187 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
2189 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
2192 if (ctx->forced_idr >= 0 && frame->pict_type == AV_PICTURE_TYPE_I) {
2193 pic_params.encodePicFlags =
2194 ctx->forced_idr ? NV_ENC_PIC_FLAG_FORCEIDR : NV_ENC_PIC_FLAG_FORCEINTRA;
2196 pic_params.encodePicFlags = 0;
2199 pic_params.inputTimeStamp = frame->pts;
2201 if (ctx->a53_cc && av_frame_get_side_data(frame, AV_FRAME_DATA_A53_CC)) {
2202 void *a53_data = NULL;
2203 size_t a53_size = 0;
2205 if (ff_alloc_a53_sei(frame, 0, (void**)&a53_data, &a53_size) < 0) {
2206 av_log(ctx, AV_LOG_ERROR, "Not enough memory for closed captions, skipping\n");
2210 sei_data[sei_count].payloadSize = (uint32_t)a53_size;
2211 sei_data[sei_count].payloadType = 4;
2212 sei_data[sei_count].payload = (uint8_t*)a53_data;
2217 if (ctx->s12m_tc && av_frame_get_side_data(frame, AV_FRAME_DATA_S12M_TIMECODE)) {
2218 void *tc_data = NULL;
2221 if (ff_alloc_timecode_sei(frame, 0, (void**)&tc_data, &tc_size) < 0) {
2222 av_log(ctx, AV_LOG_ERROR, "Not enough memory for timecode sei, skipping\n");
2226 sei_data[sei_count].payloadSize = (uint32_t)tc_size;
2227 sei_data[sei_count].payloadType = HEVC_SEI_TYPE_TIME_CODE;
2228 sei_data[sei_count].payload = (uint8_t*)tc_data;
2233 nvenc_codec_specific_pic_params(avctx, &pic_params, sei_data, sei_count);
2235 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
2238 res = nvenc_push_context(avctx);
2242 nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
2244 for ( i = 0; i < sei_count; i++)
2245 av_freep(&sei_data[i].payload);
2247 res = nvenc_pop_context(avctx);
2251 if (nv_status != NV_ENC_SUCCESS &&
2252 nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
2253 return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
2255 if (frame && frame->buf[0]) {
2256 av_fifo_generic_write(ctx->output_surface_queue, &in_surf, sizeof(in_surf), NULL);
2257 timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
2260 /* all the pending buffers are now ready for output */
2261 if (nv_status == NV_ENC_SUCCESS) {
2262 while (av_fifo_size(ctx->output_surface_queue) > 0) {
2263 av_fifo_generic_read(ctx->output_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2264 av_fifo_generic_write(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2271 int ff_nvenc_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
2273 NvencSurface *tmp_out_surf;
2276 NvencContext *ctx = avctx->priv_data;
2278 AVFrame *frame = ctx->frame;
2280 if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
2281 return AVERROR(EINVAL);
2283 if (!frame->buf[0]) {
2284 res = ff_encode_get_frame(avctx, frame);
2285 if (res < 0 && res != AVERROR_EOF)
2289 res = nvenc_send_frame(avctx, frame);
2291 if (res != AVERROR(EAGAIN))
2294 av_frame_unref(frame);
2296 if (output_ready(avctx, avctx->internal->draining)) {
2297 av_fifo_generic_read(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2299 res = nvenc_push_context(avctx);
2303 res = process_output_surface(avctx, pkt, tmp_out_surf);
2305 res2 = nvenc_pop_context(avctx);
2312 av_fifo_generic_write(ctx->unused_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2313 } else if (avctx->internal->draining) {
2316 return AVERROR(EAGAIN);
2322 av_cold void ff_nvenc_encode_flush(AVCodecContext *avctx)
2324 NvencContext *ctx = avctx->priv_data;
2326 nvenc_send_frame(avctx, NULL);
2327 av_fifo_reset(ctx->timestamp_list);