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"
37 #include "packet_internal.h"
39 #define CHECK_CU(x) FF_CUDA_CHECK_DL(avctx, dl_fn->cuda_dl, x)
41 #define NVENC_CAP 0x30
42 #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR || \
43 rc == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ || \
44 rc == NV_ENC_PARAMS_RC_CBR_HQ)
46 #ifdef NVENC_HAVE_NEW_PRESETS
47 #define IS_SDK10_PRESET(p) ((p) >= PRESET_P1 && (p) <= PRESET_P7)
49 #define IS_SDK10_PRESET(p) 0
52 const enum AVPixelFormat ff_nvenc_pix_fmts[] = {
57 AV_PIX_FMT_P016, // Truncated to 10bits
58 AV_PIX_FMT_YUV444P16, // Truncated to 10bits
68 const AVCodecHWConfigInternal *ff_nvenc_hw_configs[] = {
69 HW_CONFIG_ENCODER_FRAMES(CUDA, CUDA),
70 HW_CONFIG_ENCODER_DEVICE(NONE, CUDA),
72 HW_CONFIG_ENCODER_FRAMES(D3D11, D3D11VA),
73 HW_CONFIG_ENCODER_DEVICE(NONE, D3D11VA),
78 #define IS_10BIT(pix_fmt) (pix_fmt == AV_PIX_FMT_P010 || \
79 pix_fmt == AV_PIX_FMT_P016 || \
80 pix_fmt == AV_PIX_FMT_YUV444P16)
82 #define IS_YUV444(pix_fmt) (pix_fmt == AV_PIX_FMT_YUV444P || \
83 pix_fmt == AV_PIX_FMT_YUV444P16)
90 { NV_ENC_SUCCESS, 0, "success" },
91 { NV_ENC_ERR_NO_ENCODE_DEVICE, AVERROR(ENOENT), "no encode device" },
92 { NV_ENC_ERR_UNSUPPORTED_DEVICE, AVERROR(ENOSYS), "unsupported device" },
93 { NV_ENC_ERR_INVALID_ENCODERDEVICE, AVERROR(EINVAL), "invalid encoder device" },
94 { NV_ENC_ERR_INVALID_DEVICE, AVERROR(EINVAL), "invalid device" },
95 { NV_ENC_ERR_DEVICE_NOT_EXIST, AVERROR(EIO), "device does not exist" },
96 { NV_ENC_ERR_INVALID_PTR, AVERROR(EFAULT), "invalid ptr" },
97 { NV_ENC_ERR_INVALID_EVENT, AVERROR(EINVAL), "invalid event" },
98 { NV_ENC_ERR_INVALID_PARAM, AVERROR(EINVAL), "invalid param" },
99 { NV_ENC_ERR_INVALID_CALL, AVERROR(EINVAL), "invalid call" },
100 { NV_ENC_ERR_OUT_OF_MEMORY, AVERROR(ENOMEM), "out of memory" },
101 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED, AVERROR(EINVAL), "encoder not initialized" },
102 { NV_ENC_ERR_UNSUPPORTED_PARAM, AVERROR(ENOSYS), "unsupported param" },
103 { NV_ENC_ERR_LOCK_BUSY, AVERROR(EAGAIN), "lock busy" },
104 { NV_ENC_ERR_NOT_ENOUGH_BUFFER, AVERROR_BUFFER_TOO_SMALL, "not enough buffer"},
105 { NV_ENC_ERR_INVALID_VERSION, AVERROR(EINVAL), "invalid version" },
106 { NV_ENC_ERR_MAP_FAILED, AVERROR(EIO), "map failed" },
107 { NV_ENC_ERR_NEED_MORE_INPUT, AVERROR(EAGAIN), "need more input" },
108 { NV_ENC_ERR_ENCODER_BUSY, AVERROR(EAGAIN), "encoder busy" },
109 { NV_ENC_ERR_EVENT_NOT_REGISTERD, AVERROR(EBADF), "event not registered" },
110 { NV_ENC_ERR_GENERIC, AVERROR_UNKNOWN, "generic error" },
111 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY, AVERROR(EINVAL), "incompatible client key" },
112 { NV_ENC_ERR_UNIMPLEMENTED, AVERROR(ENOSYS), "unimplemented" },
113 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO), "resource register failed" },
114 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED, AVERROR(EBADF), "resource not registered" },
115 { NV_ENC_ERR_RESOURCE_NOT_MAPPED, AVERROR(EBADF), "resource not mapped" },
118 static int nvenc_map_error(NVENCSTATUS err, const char **desc)
121 for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
122 if (nvenc_errors[i].nverr == err) {
124 *desc = nvenc_errors[i].desc;
125 return nvenc_errors[i].averr;
129 *desc = "unknown error";
130 return AVERROR_UNKNOWN;
133 static int nvenc_print_error(AVCodecContext *avctx, NVENCSTATUS err,
134 const char *error_string)
137 const char *details = "(no details)";
138 int ret = nvenc_map_error(err, &desc);
140 #ifdef NVENC_HAVE_GETLASTERRORSTRING
141 NvencContext *ctx = avctx->priv_data;
142 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
144 if (p_nvenc && ctx->nvencoder)
145 details = p_nvenc->nvEncGetLastErrorString(ctx->nvencoder);
148 av_log(avctx, AV_LOG_ERROR, "%s: %s (%d): %s\n", error_string, desc, err, details);
153 static void nvenc_print_driver_requirement(AVCodecContext *avctx, int level)
155 #if NVENCAPI_CHECK_VERSION(11, 1)
156 const char *minver = "(unknown)";
157 #elif NVENCAPI_CHECK_VERSION(11, 0)
158 # if defined(_WIN32) || defined(__CYGWIN__)
159 const char *minver = "456.71";
161 const char *minver = "455.28";
163 #elif NVENCAPI_CHECK_VERSION(10, 0)
164 # if defined(_WIN32) || defined(__CYGWIN__)
165 const char *minver = "450.51";
167 const char *minver = "445.87";
169 #elif NVENCAPI_CHECK_VERSION(9, 1)
170 # if defined(_WIN32) || defined(__CYGWIN__)
171 const char *minver = "436.15";
173 const char *minver = "435.21";
175 #elif NVENCAPI_CHECK_VERSION(9, 0)
176 # if defined(_WIN32) || defined(__CYGWIN__)
177 const char *minver = "418.81";
179 const char *minver = "418.30";
181 #elif NVENCAPI_CHECK_VERSION(8, 2)
182 # if defined(_WIN32) || defined(__CYGWIN__)
183 const char *minver = "397.93";
185 const char *minver = "396.24";
187 #elif NVENCAPI_CHECK_VERSION(8, 1)
188 # if defined(_WIN32) || defined(__CYGWIN__)
189 const char *minver = "390.77";
191 const char *minver = "390.25";
194 # if defined(_WIN32) || defined(__CYGWIN__)
195 const char *minver = "378.66";
197 const char *minver = "378.13";
200 av_log(avctx, level, "The minimum required Nvidia driver for nvenc is %s or newer\n", minver);
203 static av_cold int nvenc_load_libraries(AVCodecContext *avctx)
205 NvencContext *ctx = avctx->priv_data;
206 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
208 uint32_t nvenc_max_ver;
211 ret = cuda_load_functions(&dl_fn->cuda_dl, avctx);
215 ret = nvenc_load_functions(&dl_fn->nvenc_dl, avctx);
217 nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
221 err = dl_fn->nvenc_dl->NvEncodeAPIGetMaxSupportedVersion(&nvenc_max_ver);
222 if (err != NV_ENC_SUCCESS)
223 return nvenc_print_error(avctx, err, "Failed to query nvenc max version");
225 av_log(avctx, AV_LOG_VERBOSE, "Loaded Nvenc version %d.%d\n", nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
227 if ((NVENCAPI_MAJOR_VERSION << 4 | NVENCAPI_MINOR_VERSION) > nvenc_max_ver) {
228 av_log(avctx, AV_LOG_ERROR, "Driver does not support the required nvenc API version. "
229 "Required: %d.%d Found: %d.%d\n",
230 NVENCAPI_MAJOR_VERSION, NVENCAPI_MINOR_VERSION,
231 nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
232 nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
233 return AVERROR(ENOSYS);
236 dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
238 err = dl_fn->nvenc_dl->NvEncodeAPICreateInstance(&dl_fn->nvenc_funcs);
239 if (err != NV_ENC_SUCCESS)
240 return nvenc_print_error(avctx, err, "Failed to create nvenc instance");
242 av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
247 static int nvenc_push_context(AVCodecContext *avctx)
249 NvencContext *ctx = avctx->priv_data;
250 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
252 if (ctx->d3d11_device)
255 return CHECK_CU(dl_fn->cuda_dl->cuCtxPushCurrent(ctx->cu_context));
258 static int nvenc_pop_context(AVCodecContext *avctx)
260 NvencContext *ctx = avctx->priv_data;
261 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
264 if (ctx->d3d11_device)
267 return CHECK_CU(dl_fn->cuda_dl->cuCtxPopCurrent(&dummy));
270 static av_cold int nvenc_open_session(AVCodecContext *avctx)
272 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
273 NvencContext *ctx = avctx->priv_data;
274 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
277 params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
278 params.apiVersion = NVENCAPI_VERSION;
279 if (ctx->d3d11_device) {
280 params.device = ctx->d3d11_device;
281 params.deviceType = NV_ENC_DEVICE_TYPE_DIRECTX;
283 params.device = ctx->cu_context;
284 params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
287 ret = p_nvenc->nvEncOpenEncodeSessionEx(¶ms, &ctx->nvencoder);
288 if (ret != NV_ENC_SUCCESS) {
289 ctx->nvencoder = NULL;
290 return nvenc_print_error(avctx, ret, "OpenEncodeSessionEx failed");
296 static int nvenc_check_codec_support(AVCodecContext *avctx)
298 NvencContext *ctx = avctx->priv_data;
299 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
300 int i, ret, count = 0;
303 ret = p_nvenc->nvEncGetEncodeGUIDCount(ctx->nvencoder, &count);
305 if (ret != NV_ENC_SUCCESS || !count)
306 return AVERROR(ENOSYS);
308 guids = av_malloc(count * sizeof(GUID));
310 return AVERROR(ENOMEM);
312 ret = p_nvenc->nvEncGetEncodeGUIDs(ctx->nvencoder, guids, count, &count);
313 if (ret != NV_ENC_SUCCESS) {
314 ret = AVERROR(ENOSYS);
318 ret = AVERROR(ENOSYS);
319 for (i = 0; i < count; i++) {
320 if (!memcmp(&guids[i], &ctx->init_encode_params.encodeGUID, sizeof(*guids))) {
332 static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
334 NvencContext *ctx = avctx->priv_data;
335 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
336 NV_ENC_CAPS_PARAM params = { 0 };
339 params.version = NV_ENC_CAPS_PARAM_VER;
340 params.capsToQuery = cap;
342 ret = p_nvenc->nvEncGetEncodeCaps(ctx->nvencoder, ctx->init_encode_params.encodeGUID, ¶ms, &val);
344 if (ret == NV_ENC_SUCCESS)
349 static int nvenc_check_capabilities(AVCodecContext *avctx)
351 NvencContext *ctx = avctx->priv_data;
354 ret = nvenc_check_codec_support(avctx);
356 av_log(avctx, AV_LOG_WARNING, "Codec not supported\n");
360 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
361 if (IS_YUV444(ctx->data_pix_fmt) && ret <= 0) {
362 av_log(avctx, AV_LOG_WARNING, "YUV444P not supported\n");
363 return AVERROR(ENOSYS);
366 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOSSLESS_ENCODE);
367 if (ctx->preset >= PRESET_LOSSLESS_DEFAULT && ret <= 0) {
368 av_log(avctx, AV_LOG_WARNING, "Lossless encoding not supported\n");
369 return AVERROR(ENOSYS);
372 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
373 if (ret < avctx->width) {
374 av_log(avctx, AV_LOG_WARNING, "Width %d exceeds %d\n",
376 return AVERROR(ENOSYS);
379 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
380 if (ret < avctx->height) {
381 av_log(avctx, AV_LOG_WARNING, "Height %d exceeds %d\n",
383 return AVERROR(ENOSYS);
386 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
387 if (ret < avctx->max_b_frames) {
388 av_log(avctx, AV_LOG_WARNING, "Max B-frames %d exceed %d\n",
389 avctx->max_b_frames, ret);
391 return AVERROR(ENOSYS);
394 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_FIELD_ENCODING);
395 if (ret < 1 && avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
396 av_log(avctx, AV_LOG_WARNING,
397 "Interlaced encoding is not supported. Supported level: %d\n",
399 return AVERROR(ENOSYS);
402 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_10BIT_ENCODE);
403 if (IS_10BIT(ctx->data_pix_fmt) && ret <= 0) {
404 av_log(avctx, AV_LOG_WARNING, "10 bit encode not supported\n");
405 return AVERROR(ENOSYS);
408 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOOKAHEAD);
409 if (ctx->rc_lookahead > 0 && ret <= 0) {
410 av_log(avctx, AV_LOG_WARNING, "RC lookahead not supported\n");
411 return AVERROR(ENOSYS);
414 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_TEMPORAL_AQ);
415 if (ctx->temporal_aq > 0 && ret <= 0) {
416 av_log(avctx, AV_LOG_WARNING, "Temporal AQ not supported\n");
417 return AVERROR(ENOSYS);
420 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_WEIGHTED_PREDICTION);
421 if (ctx->weighted_pred > 0 && ret <= 0) {
422 av_log (avctx, AV_LOG_WARNING, "Weighted Prediction not supported\n");
423 return AVERROR(ENOSYS);
426 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_CABAC);
427 if (ctx->coder == NV_ENC_H264_ENTROPY_CODING_MODE_CABAC && ret <= 0) {
428 av_log(avctx, AV_LOG_WARNING, "CABAC entropy coding not supported\n");
429 return AVERROR(ENOSYS);
432 #ifdef NVENC_HAVE_BFRAME_REF_MODE
433 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_BFRAME_REF_MODE);
434 if (ctx->b_ref_mode == NV_ENC_BFRAME_REF_MODE_EACH && ret != 1 && ret != 3) {
435 av_log(avctx, AV_LOG_WARNING, "Each B frame as reference is not supported\n");
436 return AVERROR(ENOSYS);
437 } else if (ctx->b_ref_mode != NV_ENC_BFRAME_REF_MODE_DISABLED && ret == 0) {
438 av_log(avctx, AV_LOG_WARNING, "B frames as references are not supported\n");
439 return AVERROR(ENOSYS);
442 if (ctx->b_ref_mode != 0) {
443 av_log(avctx, AV_LOG_WARNING, "B frames as references need SDK 8.1 at build time\n");
444 return AVERROR(ENOSYS);
448 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
449 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_MULTIPLE_REF_FRAMES);
450 if(avctx->refs != NV_ENC_NUM_REF_FRAMES_AUTOSELECT && ret <= 0) {
451 av_log(avctx, AV_LOG_WARNING, "Multiple reference frames are not supported by the device\n");
452 return AVERROR(ENOSYS);
455 if(avctx->refs != 0) {
456 av_log(avctx, AV_LOG_WARNING, "Multiple reference frames need SDK 9.1 at build time\n");
457 return AVERROR(ENOSYS);
461 ctx->support_dyn_bitrate = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_DYN_BITRATE_CHANGE);
466 static av_cold int nvenc_check_device(AVCodecContext *avctx, int idx)
468 NvencContext *ctx = avctx->priv_data;
469 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
470 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
471 char name[128] = { 0};
472 int major, minor, ret;
474 int loglevel = AV_LOG_VERBOSE;
476 if (ctx->device == LIST_DEVICES)
477 loglevel = AV_LOG_INFO;
479 ret = CHECK_CU(dl_fn->cuda_dl->cuDeviceGet(&cu_device, idx));
483 ret = CHECK_CU(dl_fn->cuda_dl->cuDeviceGetName(name, sizeof(name), cu_device));
487 ret = CHECK_CU(dl_fn->cuda_dl->cuDeviceComputeCapability(&major, &minor, cu_device));
491 av_log(avctx, loglevel, "[ GPU #%d - < %s > has Compute SM %d.%d ]\n", idx, name, major, minor);
492 if (((major << 4) | minor) < NVENC_CAP) {
493 av_log(avctx, loglevel, "does not support NVENC\n");
497 if (ctx->device != idx && ctx->device != ANY_DEVICE)
500 ret = CHECK_CU(dl_fn->cuda_dl->cuCtxCreate(&ctx->cu_context_internal, 0, cu_device));
504 ctx->cu_context = ctx->cu_context_internal;
505 ctx->cu_stream = NULL;
507 if ((ret = nvenc_pop_context(avctx)) < 0)
510 if ((ret = nvenc_open_session(avctx)) < 0)
513 if ((ret = nvenc_check_capabilities(avctx)) < 0)
516 av_log(avctx, loglevel, "supports NVENC\n");
518 dl_fn->nvenc_device_count++;
520 if (ctx->device == idx || ctx->device == ANY_DEVICE)
524 if ((ret = nvenc_push_context(avctx)) < 0)
527 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
528 ctx->nvencoder = NULL;
530 if ((ret = nvenc_pop_context(avctx)) < 0)
534 CHECK_CU(dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal));
535 ctx->cu_context_internal = NULL;
538 return AVERROR(ENOSYS);
541 static av_cold int nvenc_setup_device(AVCodecContext *avctx)
543 NvencContext *ctx = avctx->priv_data;
544 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
546 switch (avctx->codec->id) {
547 case AV_CODEC_ID_H264:
548 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
550 case AV_CODEC_ID_HEVC:
551 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
557 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11 || avctx->hw_frames_ctx || avctx->hw_device_ctx) {
558 AVHWFramesContext *frames_ctx;
559 AVHWDeviceContext *hwdev_ctx;
560 AVCUDADeviceContext *cuda_device_hwctx = NULL;
562 AVD3D11VADeviceContext *d3d11_device_hwctx = NULL;
566 if (avctx->hw_frames_ctx) {
567 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
568 if (frames_ctx->format == AV_PIX_FMT_CUDA)
569 cuda_device_hwctx = frames_ctx->device_ctx->hwctx;
571 else if (frames_ctx->format == AV_PIX_FMT_D3D11)
572 d3d11_device_hwctx = frames_ctx->device_ctx->hwctx;
575 return AVERROR(EINVAL);
576 } else if (avctx->hw_device_ctx) {
577 hwdev_ctx = (AVHWDeviceContext*)avctx->hw_device_ctx->data;
578 if (hwdev_ctx->type == AV_HWDEVICE_TYPE_CUDA)
579 cuda_device_hwctx = hwdev_ctx->hwctx;
581 else if (hwdev_ctx->type == AV_HWDEVICE_TYPE_D3D11VA)
582 d3d11_device_hwctx = hwdev_ctx->hwctx;
585 return AVERROR(EINVAL);
587 return AVERROR(EINVAL);
590 if (cuda_device_hwctx) {
591 ctx->cu_context = cuda_device_hwctx->cuda_ctx;
592 ctx->cu_stream = cuda_device_hwctx->stream;
595 else if (d3d11_device_hwctx) {
596 ctx->d3d11_device = d3d11_device_hwctx->device;
597 ID3D11Device_AddRef(ctx->d3d11_device);
601 ret = nvenc_open_session(avctx);
605 ret = nvenc_check_capabilities(avctx);
607 av_log(avctx, AV_LOG_FATAL, "Provided device doesn't support required NVENC features\n");
611 int i, nb_devices = 0;
613 if (CHECK_CU(dl_fn->cuda_dl->cuInit(0)) < 0)
614 return AVERROR_UNKNOWN;
616 if (CHECK_CU(dl_fn->cuda_dl->cuDeviceGetCount(&nb_devices)) < 0)
617 return AVERROR_UNKNOWN;
620 av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
621 return AVERROR_EXTERNAL;
624 av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", nb_devices);
626 dl_fn->nvenc_device_count = 0;
627 for (i = 0; i < nb_devices; ++i) {
628 if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
632 if (ctx->device == LIST_DEVICES)
635 if (!dl_fn->nvenc_device_count) {
636 av_log(avctx, AV_LOG_FATAL, "No capable devices found\n");
637 return AVERROR_EXTERNAL;
640 av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->device, nb_devices);
641 return AVERROR(EINVAL);
647 typedef struct GUIDTuple {
652 #define PRESET_ALIAS(alias, name, ...) \
653 [PRESET_ ## alias] = { NV_ENC_PRESET_ ## name ## _GUID, __VA_ARGS__ }
655 #define PRESET(name, ...) PRESET_ALIAS(name, name, __VA_ARGS__)
657 static void nvenc_map_preset(NvencContext *ctx)
659 GUIDTuple presets[] = {
660 #ifdef NVENC_HAVE_NEW_PRESETS
668 PRESET_ALIAS(SLOW, P7, NVENC_TWO_PASSES),
669 PRESET_ALIAS(MEDIUM, P4, NVENC_ONE_PASS),
670 PRESET_ALIAS(FAST, P1, NVENC_ONE_PASS),
672 PRESET_ALIAS(DEFAULT, P4, NVENC_DEPRECATED_PRESET),
673 PRESET_ALIAS(HP, P1, NVENC_DEPRECATED_PRESET),
674 PRESET_ALIAS(HQ, P7, NVENC_DEPRECATED_PRESET),
675 PRESET_ALIAS(BD, P5, NVENC_DEPRECATED_PRESET),
676 PRESET_ALIAS(LOW_LATENCY_DEFAULT, P4, NVENC_DEPRECATED_PRESET | NVENC_LOWLATENCY),
677 PRESET_ALIAS(LOW_LATENCY_HP, P1, NVENC_DEPRECATED_PRESET | NVENC_LOWLATENCY),
678 PRESET_ALIAS(LOW_LATENCY_HQ, P7, NVENC_DEPRECATED_PRESET | NVENC_LOWLATENCY),
679 PRESET_ALIAS(LOSSLESS_DEFAULT, P4, NVENC_DEPRECATED_PRESET | NVENC_LOSSLESS),
680 PRESET_ALIAS(LOSSLESS_HP, P1, NVENC_DEPRECATED_PRESET | NVENC_LOSSLESS),
686 PRESET_ALIAS(SLOW, HQ, NVENC_TWO_PASSES),
687 PRESET_ALIAS(MEDIUM, HQ, NVENC_ONE_PASS),
688 PRESET_ALIAS(FAST, HP, NVENC_ONE_PASS),
689 PRESET(LOW_LATENCY_DEFAULT, NVENC_LOWLATENCY),
690 PRESET(LOW_LATENCY_HP, NVENC_LOWLATENCY),
691 PRESET(LOW_LATENCY_HQ, NVENC_LOWLATENCY),
692 PRESET(LOSSLESS_DEFAULT, NVENC_LOSSLESS),
693 PRESET(LOSSLESS_HP, NVENC_LOSSLESS),
697 GUIDTuple *t = &presets[ctx->preset];
699 ctx->init_encode_params.presetGUID = t->guid;
700 ctx->flags = t->flags;
706 static av_cold void set_constqp(AVCodecContext *avctx)
708 NvencContext *ctx = avctx->priv_data;
709 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
711 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
713 if (ctx->init_qp_p >= 0) {
714 rc->constQP.qpInterP = ctx->init_qp_p;
715 if (ctx->init_qp_i >= 0 && ctx->init_qp_b >= 0) {
716 rc->constQP.qpIntra = ctx->init_qp_i;
717 rc->constQP.qpInterB = ctx->init_qp_b;
718 } else if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
719 rc->constQP.qpIntra = av_clip(
720 rc->constQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
721 rc->constQP.qpInterB = av_clip(
722 rc->constQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
724 rc->constQP.qpIntra = rc->constQP.qpInterP;
725 rc->constQP.qpInterB = rc->constQP.qpInterP;
727 } else if (ctx->cqp >= 0) {
728 rc->constQP.qpInterP = rc->constQP.qpInterB = rc->constQP.qpIntra = ctx->cqp;
729 if (avctx->b_quant_factor != 0.0)
730 rc->constQP.qpInterB = av_clip(ctx->cqp * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
731 if (avctx->i_quant_factor != 0.0)
732 rc->constQP.qpIntra = av_clip(ctx->cqp * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
739 static av_cold void set_vbr(AVCodecContext *avctx)
741 NvencContext *ctx = avctx->priv_data;
742 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
745 if (avctx->qmin >= 0 && avctx->qmax >= 0) {
749 rc->minQP.qpInterB = avctx->qmin;
750 rc->minQP.qpInterP = avctx->qmin;
751 rc->minQP.qpIntra = avctx->qmin;
753 rc->maxQP.qpInterB = avctx->qmax;
754 rc->maxQP.qpInterP = avctx->qmax;
755 rc->maxQP.qpIntra = avctx->qmax;
757 qp_inter_p = (avctx->qmax + 3 * avctx->qmin) / 4; // biased towards Qmin
758 } else if (avctx->qmin >= 0) {
761 rc->minQP.qpInterB = avctx->qmin;
762 rc->minQP.qpInterP = avctx->qmin;
763 rc->minQP.qpIntra = avctx->qmin;
765 qp_inter_p = avctx->qmin;
767 qp_inter_p = 26; // default to 26
770 rc->enableInitialRCQP = 1;
772 if (ctx->init_qp_p < 0) {
773 rc->initialRCQP.qpInterP = qp_inter_p;
775 rc->initialRCQP.qpInterP = ctx->init_qp_p;
778 if (ctx->init_qp_i < 0) {
779 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
780 rc->initialRCQP.qpIntra = av_clip(
781 rc->initialRCQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
783 rc->initialRCQP.qpIntra = rc->initialRCQP.qpInterP;
786 rc->initialRCQP.qpIntra = ctx->init_qp_i;
789 if (ctx->init_qp_b < 0) {
790 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
791 rc->initialRCQP.qpInterB = av_clip(
792 rc->initialRCQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
794 rc->initialRCQP.qpInterB = rc->initialRCQP.qpInterP;
797 rc->initialRCQP.qpInterB = ctx->init_qp_b;
801 static av_cold void set_lossless(AVCodecContext *avctx)
803 NvencContext *ctx = avctx->priv_data;
804 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
806 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
807 rc->constQP.qpInterB = 0;
808 rc->constQP.qpInterP = 0;
809 rc->constQP.qpIntra = 0;
815 static void nvenc_override_rate_control(AVCodecContext *avctx)
817 NvencContext *ctx = avctx->priv_data;
818 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
821 case NV_ENC_PARAMS_RC_CONSTQP:
824 case NV_ENC_PARAMS_RC_VBR_MINQP:
825 if (avctx->qmin < 0) {
826 av_log(avctx, AV_LOG_WARNING,
827 "The variable bitrate rate-control requires "
828 "the 'qmin' option set.\n");
833 case NV_ENC_PARAMS_RC_VBR_HQ:
834 case NV_ENC_PARAMS_RC_VBR:
837 case NV_ENC_PARAMS_RC_CBR:
838 case NV_ENC_PARAMS_RC_CBR_HQ:
839 case NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ:
843 rc->rateControlMode = ctx->rc;
846 static av_cold int nvenc_recalc_surfaces(AVCodecContext *avctx)
848 NvencContext *ctx = avctx->priv_data;
849 // default minimum of 4 surfaces
850 // multiply by 2 for number of NVENCs on gpu (hardcode to 2)
851 // another multiply by 2 to avoid blocking next PBB group
852 int nb_surfaces = FFMAX(4, ctx->encode_config.frameIntervalP * 2 * 2);
855 if (ctx->rc_lookahead > 0) {
856 // +1 is to account for lkd_bound calculation later
857 // +4 is to allow sufficient pipelining with lookahead
858 nb_surfaces = FFMAX(1, FFMAX(nb_surfaces, ctx->rc_lookahead + ctx->encode_config.frameIntervalP + 1 + 4));
859 if (nb_surfaces > ctx->nb_surfaces && ctx->nb_surfaces > 0)
861 av_log(avctx, AV_LOG_WARNING,
862 "Defined rc_lookahead requires more surfaces, "
863 "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
865 ctx->nb_surfaces = FFMAX(nb_surfaces, ctx->nb_surfaces);
867 if (ctx->encode_config.frameIntervalP > 1 && ctx->nb_surfaces < nb_surfaces && ctx->nb_surfaces > 0)
869 av_log(avctx, AV_LOG_WARNING,
870 "Defined b-frame requires more surfaces, "
871 "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
872 ctx->nb_surfaces = FFMAX(ctx->nb_surfaces, nb_surfaces);
874 else if (ctx->nb_surfaces <= 0)
875 ctx->nb_surfaces = nb_surfaces;
876 // otherwise use user specified value
879 ctx->nb_surfaces = FFMAX(1, FFMIN(MAX_REGISTERED_FRAMES, ctx->nb_surfaces));
880 ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
885 static av_cold void nvenc_setup_rate_control(AVCodecContext *avctx)
887 NvencContext *ctx = avctx->priv_data;
889 if (avctx->global_quality > 0)
890 av_log(avctx, AV_LOG_WARNING, "Using global_quality with nvenc is deprecated. Use qp instead.\n");
892 if (ctx->cqp < 0 && avctx->global_quality > 0)
893 ctx->cqp = avctx->global_quality;
895 if (avctx->bit_rate > 0) {
896 ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
897 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
898 ctx->encode_config.rcParams.maxBitRate = ctx->encode_config.rcParams.averageBitRate;
901 if (avctx->rc_max_rate > 0)
902 ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
904 #ifdef NVENC_HAVE_MULTIPASS
905 ctx->encode_config.rcParams.multiPass = ctx->multipass;
906 if (ctx->encode_config.rcParams.multiPass != NV_ENC_MULTI_PASS_DISABLED)
907 ctx->flags |= NVENC_TWO_PASSES;
911 if (ctx->flags & NVENC_ONE_PASS)
913 if (ctx->flags & NVENC_TWO_PASSES)
916 if (ctx->twopass < 0)
917 ctx->twopass = (ctx->flags & NVENC_LOWLATENCY) != 0;
921 ctx->rc = NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ;
923 ctx->rc = NV_ENC_PARAMS_RC_CBR;
925 } else if (ctx->cqp >= 0) {
926 ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
927 } else if (ctx->twopass) {
928 ctx->rc = NV_ENC_PARAMS_RC_VBR_HQ;
929 } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
930 ctx->rc = NV_ENC_PARAMS_RC_VBR_MINQP;
934 if (ctx->rc >= 0 && ctx->rc & RC_MODE_DEPRECATED) {
935 av_log(avctx, AV_LOG_WARNING, "Specified rc mode is deprecated.\n");
936 av_log(avctx, AV_LOG_WARNING, "\tll_2pass_quality -> cbr_ld_hq\n");
937 av_log(avctx, AV_LOG_WARNING, "\tll_2pass_size -> cbr_hq\n");
938 av_log(avctx, AV_LOG_WARNING, "\tvbr_2pass -> vbr_hq\n");
939 av_log(avctx, AV_LOG_WARNING, "\tvbr_minqp -> (no replacement)\n");
941 ctx->rc &= ~RC_MODE_DEPRECATED;
944 #ifdef NVENC_HAVE_LDKFS
946 ctx->encode_config.rcParams.lowDelayKeyFrameScale = ctx->ldkfs;
949 if (ctx->flags & NVENC_LOSSLESS) {
951 } else if (ctx->rc >= 0) {
952 nvenc_override_rate_control(avctx);
954 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
958 if (avctx->rc_buffer_size > 0) {
959 ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
960 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
961 avctx->rc_buffer_size = ctx->encode_config.rcParams.vbvBufferSize = 2 * ctx->encode_config.rcParams.averageBitRate;
965 ctx->encode_config.rcParams.enableAQ = 1;
966 ctx->encode_config.rcParams.aqStrength = ctx->aq_strength;
967 av_log(avctx, AV_LOG_VERBOSE, "AQ enabled.\n");
970 if (ctx->temporal_aq) {
971 ctx->encode_config.rcParams.enableTemporalAQ = 1;
972 av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ enabled.\n");
975 if (ctx->rc_lookahead > 0) {
976 int lkd_bound = FFMIN(ctx->nb_surfaces, ctx->async_depth) -
977 ctx->encode_config.frameIntervalP - 4;
980 av_log(avctx, AV_LOG_WARNING,
981 "Lookahead not enabled. Increase buffer delay (-delay).\n");
983 ctx->encode_config.rcParams.enableLookahead = 1;
984 ctx->encode_config.rcParams.lookaheadDepth = av_clip(ctx->rc_lookahead, 0, lkd_bound);
985 ctx->encode_config.rcParams.disableIadapt = ctx->no_scenecut;
986 ctx->encode_config.rcParams.disableBadapt = !ctx->b_adapt;
987 av_log(avctx, AV_LOG_VERBOSE,
988 "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",
989 ctx->encode_config.rcParams.lookaheadDepth,
990 ctx->encode_config.rcParams.disableIadapt ? "disabled" : "enabled",
991 ctx->encode_config.rcParams.disableBadapt ? "disabled" : "enabled");
995 if (ctx->strict_gop) {
996 ctx->encode_config.rcParams.strictGOPTarget = 1;
997 av_log(avctx, AV_LOG_VERBOSE, "Strict GOP target enabled.\n");
1001 ctx->encode_config.rcParams.enableNonRefP = 1;
1003 if (ctx->zerolatency)
1004 ctx->encode_config.rcParams.zeroReorderDelay = 1;
1007 //convert from float to fixed point 8.8
1008 int tmp_quality = (int)(ctx->quality * 256.0f);
1009 ctx->encode_config.rcParams.targetQuality = (uint8_t)(tmp_quality >> 8);
1010 ctx->encode_config.rcParams.targetQualityLSB = (uint8_t)(tmp_quality & 0xff);
1012 av_log(avctx, AV_LOG_VERBOSE, "CQ(%d) mode enabled.\n", tmp_quality);
1014 //CQ mode shall discard avg bitrate & honor max bitrate;
1015 ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate = 0;
1016 ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
1020 static av_cold int nvenc_setup_h264_config(AVCodecContext *avctx)
1022 NvencContext *ctx = avctx->priv_data;
1023 NV_ENC_CONFIG *cc = &ctx->encode_config;
1024 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
1025 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
1027 vui->colourMatrix = avctx->colorspace;
1028 vui->colourPrimaries = avctx->color_primaries;
1029 vui->transferCharacteristics = avctx->color_trc;
1030 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
1031 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
1033 vui->colourDescriptionPresentFlag =
1034 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
1036 vui->videoSignalTypePresentFlag =
1037 (vui->colourDescriptionPresentFlag
1038 || vui->videoFormat != 5
1039 || vui->videoFullRangeFlag != 0);
1041 h264->sliceMode = 3;
1042 h264->sliceModeData = 1;
1044 h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
1045 h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
1046 h264->outputAUD = ctx->aud;
1048 if (ctx->dpb_size >= 0) {
1049 /* 0 means "let the hardware decide" */
1050 h264->maxNumRefFrames = ctx->dpb_size;
1052 if (avctx->gop_size >= 0) {
1053 h264->idrPeriod = cc->gopLength;
1056 if (IS_CBR(cc->rcParams.rateControlMode)) {
1057 h264->outputBufferingPeriodSEI = 1;
1060 h264->outputPictureTimingSEI = 1;
1062 if (cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ ||
1063 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_HQ ||
1064 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_VBR_HQ) {
1065 h264->adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
1066 h264->fmoMode = NV_ENC_H264_FMO_DISABLE;
1069 if (ctx->flags & NVENC_LOSSLESS) {
1070 h264->qpPrimeYZeroTransformBypassFlag = 1;
1072 switch(ctx->profile) {
1073 case NV_ENC_H264_PROFILE_BASELINE:
1074 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
1075 avctx->profile = FF_PROFILE_H264_BASELINE;
1077 case NV_ENC_H264_PROFILE_MAIN:
1078 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
1079 avctx->profile = FF_PROFILE_H264_MAIN;
1081 case NV_ENC_H264_PROFILE_HIGH:
1082 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
1083 avctx->profile = FF_PROFILE_H264_HIGH;
1085 case NV_ENC_H264_PROFILE_HIGH_444P:
1086 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1087 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
1092 // force setting profile as high444p if input is AV_PIX_FMT_YUV444P
1093 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P) {
1094 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1095 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
1098 h264->chromaFormatIDC = avctx->profile == FF_PROFILE_H264_HIGH_444_PREDICTIVE ? 3 : 1;
1100 h264->level = ctx->level;
1102 if (ctx->coder >= 0)
1103 h264->entropyCodingMode = ctx->coder;
1105 #ifdef NVENC_HAVE_BFRAME_REF_MODE
1106 h264->useBFramesAsRef = ctx->b_ref_mode;
1109 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
1110 h264->numRefL0 = avctx->refs;
1111 h264->numRefL1 = avctx->refs;
1117 static av_cold int nvenc_setup_hevc_config(AVCodecContext *avctx)
1119 NvencContext *ctx = avctx->priv_data;
1120 NV_ENC_CONFIG *cc = &ctx->encode_config;
1121 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
1122 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
1124 vui->colourMatrix = avctx->colorspace;
1125 vui->colourPrimaries = avctx->color_primaries;
1126 vui->transferCharacteristics = avctx->color_trc;
1127 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
1128 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
1130 vui->colourDescriptionPresentFlag =
1131 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
1133 vui->videoSignalTypePresentFlag =
1134 (vui->colourDescriptionPresentFlag
1135 || vui->videoFormat != 5
1136 || vui->videoFullRangeFlag != 0);
1138 hevc->sliceMode = 3;
1139 hevc->sliceModeData = 1;
1141 hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
1142 hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
1143 hevc->outputAUD = ctx->aud;
1145 if (ctx->dpb_size >= 0) {
1146 /* 0 means "let the hardware decide" */
1147 hevc->maxNumRefFramesInDPB = ctx->dpb_size;
1149 if (avctx->gop_size >= 0) {
1150 hevc->idrPeriod = cc->gopLength;
1153 if (IS_CBR(cc->rcParams.rateControlMode)) {
1154 hevc->outputBufferingPeriodSEI = 1;
1157 hevc->outputPictureTimingSEI = 1;
1159 switch (ctx->profile) {
1160 case NV_ENC_HEVC_PROFILE_MAIN:
1161 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
1162 avctx->profile = FF_PROFILE_HEVC_MAIN;
1164 case NV_ENC_HEVC_PROFILE_MAIN_10:
1165 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1166 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
1168 case NV_ENC_HEVC_PROFILE_REXT:
1169 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1170 avctx->profile = FF_PROFILE_HEVC_REXT;
1174 // force setting profile as main10 if input is 10 bit
1175 if (IS_10BIT(ctx->data_pix_fmt)) {
1176 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1177 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
1180 // force setting profile as rext if input is yuv444
1181 if (IS_YUV444(ctx->data_pix_fmt)) {
1182 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1183 avctx->profile = FF_PROFILE_HEVC_REXT;
1186 hevc->chromaFormatIDC = IS_YUV444(ctx->data_pix_fmt) ? 3 : 1;
1188 hevc->pixelBitDepthMinus8 = IS_10BIT(ctx->data_pix_fmt) ? 2 : 0;
1190 hevc->level = ctx->level;
1192 hevc->tier = ctx->tier;
1194 #ifdef NVENC_HAVE_HEVC_BFRAME_REF_MODE
1195 hevc->useBFramesAsRef = ctx->b_ref_mode;
1198 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
1199 hevc->numRefL0 = avctx->refs;
1200 hevc->numRefL1 = avctx->refs;
1206 static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx)
1208 switch (avctx->codec->id) {
1209 case AV_CODEC_ID_H264:
1210 return nvenc_setup_h264_config(avctx);
1211 case AV_CODEC_ID_HEVC:
1212 return nvenc_setup_hevc_config(avctx);
1213 /* Earlier switch/case will return if unknown codec is passed. */
1219 static void compute_dar(AVCodecContext *avctx, int *dw, int *dh) {
1225 if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0) {
1226 sw *= avctx->sample_aspect_ratio.num;
1227 sh *= avctx->sample_aspect_ratio.den;
1230 av_reduce(dw, dh, sw, sh, 1024 * 1024);
1233 static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
1235 NvencContext *ctx = avctx->priv_data;
1236 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1237 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1239 NV_ENC_PRESET_CONFIG preset_config = { 0 };
1240 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
1241 AVCPBProperties *cpb_props;
1245 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1246 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
1248 ctx->init_encode_params.encodeHeight = avctx->height;
1249 ctx->init_encode_params.encodeWidth = avctx->width;
1251 ctx->init_encode_params.encodeConfig = &ctx->encode_config;
1253 nvenc_map_preset(ctx);
1255 if (ctx->flags & NVENC_DEPRECATED_PRESET)
1256 av_log(avctx, AV_LOG_WARNING, "The selected preset is deprecated. Use p1 to p7 + -tune or fast/medium/slow.\n");
1258 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
1259 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
1261 if (IS_SDK10_PRESET(ctx->preset)) {
1262 #ifdef NVENC_HAVE_NEW_PRESETS
1263 ctx->init_encode_params.tuningInfo = ctx->tuning_info;
1265 nv_status = p_nvenc->nvEncGetEncodePresetConfigEx(ctx->nvencoder,
1266 ctx->init_encode_params.encodeGUID,
1267 ctx->init_encode_params.presetGUID,
1268 ctx->init_encode_params.tuningInfo,
1272 #ifdef NVENC_HAVE_NEW_PRESETS
1273 // Turn off tuning info parameter if older presets are on
1274 ctx->init_encode_params.tuningInfo = 0;
1277 nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder,
1278 ctx->init_encode_params.encodeGUID,
1279 ctx->init_encode_params.presetGUID,
1282 if (nv_status != NV_ENC_SUCCESS)
1283 return nvenc_print_error(avctx, nv_status, "Cannot get the preset configuration");
1285 memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
1287 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1289 compute_dar(avctx, &dw, &dh);
1290 ctx->init_encode_params.darHeight = dh;
1291 ctx->init_encode_params.darWidth = dw;
1293 if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {
1294 ctx->init_encode_params.frameRateNum = avctx->framerate.num;
1295 ctx->init_encode_params.frameRateDen = avctx->framerate.den;
1297 ctx->init_encode_params.frameRateNum = avctx->time_base.den;
1298 ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
1301 ctx->init_encode_params.enableEncodeAsync = 0;
1302 ctx->init_encode_params.enablePTD = 1;
1304 #ifdef NVENC_HAVE_NEW_PRESETS
1305 /* If lookahead isn't set from CLI, use value from preset.
1306 * P6 & P7 presets may enable lookahead for better quality.
1308 if (ctx->rc_lookahead == 0 && ctx->encode_config.rcParams.enableLookahead)
1309 ctx->rc_lookahead = ctx->encode_config.rcParams.lookaheadDepth;
1311 if (ctx->init_encode_params.tuningInfo == NV_ENC_TUNING_INFO_LOSSLESS)
1312 ctx->flags |= NVENC_LOSSLESS;
1315 if (ctx->weighted_pred == 1)
1316 ctx->init_encode_params.enableWeightedPrediction = 1;
1318 if (ctx->bluray_compat) {
1320 ctx->dpb_size = FFMIN(FFMAX(avctx->refs, 0), 6);
1321 avctx->max_b_frames = FFMIN(avctx->max_b_frames, 3);
1322 switch (avctx->codec->id) {
1323 case AV_CODEC_ID_H264:
1324 /* maximum level depends on used resolution */
1326 case AV_CODEC_ID_HEVC:
1327 ctx->level = NV_ENC_LEVEL_HEVC_51;
1328 ctx->tier = NV_ENC_TIER_HEVC_HIGH;
1333 if (avctx->gop_size > 0) {
1334 if (avctx->max_b_frames >= 0) {
1335 /* 0 is intra-only, 1 is I/P only, 2 is one B-Frame, 3 two B-frames, and so on. */
1336 ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
1339 ctx->encode_config.gopLength = avctx->gop_size;
1340 } else if (avctx->gop_size == 0) {
1341 ctx->encode_config.frameIntervalP = 0;
1342 ctx->encode_config.gopLength = 1;
1345 nvenc_recalc_surfaces(avctx);
1347 nvenc_setup_rate_control(avctx);
1349 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1350 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
1352 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
1355 res = nvenc_setup_codec_config(avctx);
1359 res = nvenc_push_context(avctx);
1363 nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
1364 if (nv_status != NV_ENC_SUCCESS) {
1365 nvenc_pop_context(avctx);
1366 return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
1369 #ifdef NVENC_HAVE_CUSTREAM_PTR
1370 if (ctx->cu_context) {
1371 nv_status = p_nvenc->nvEncSetIOCudaStreams(ctx->nvencoder, &ctx->cu_stream, &ctx->cu_stream);
1372 if (nv_status != NV_ENC_SUCCESS) {
1373 nvenc_pop_context(avctx);
1374 return nvenc_print_error(avctx, nv_status, "SetIOCudaStreams failed");
1379 res = nvenc_pop_context(avctx);
1383 if (ctx->encode_config.frameIntervalP > 1)
1384 avctx->has_b_frames = 2;
1386 if (ctx->encode_config.rcParams.averageBitRate > 0)
1387 avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
1389 cpb_props = ff_add_cpb_side_data(avctx);
1391 return AVERROR(ENOMEM);
1392 cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
1393 cpb_props->avg_bitrate = avctx->bit_rate;
1394 cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
1399 static NV_ENC_BUFFER_FORMAT nvenc_map_buffer_format(enum AVPixelFormat pix_fmt)
1402 case AV_PIX_FMT_YUV420P:
1403 return NV_ENC_BUFFER_FORMAT_YV12_PL;
1404 case AV_PIX_FMT_NV12:
1405 return NV_ENC_BUFFER_FORMAT_NV12_PL;
1406 case AV_PIX_FMT_P010:
1407 case AV_PIX_FMT_P016:
1408 return NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1409 case AV_PIX_FMT_YUV444P:
1410 return NV_ENC_BUFFER_FORMAT_YUV444_PL;
1411 case AV_PIX_FMT_YUV444P16:
1412 return NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1413 case AV_PIX_FMT_0RGB32:
1414 return NV_ENC_BUFFER_FORMAT_ARGB;
1415 case AV_PIX_FMT_0BGR32:
1416 return NV_ENC_BUFFER_FORMAT_ABGR;
1418 return NV_ENC_BUFFER_FORMAT_UNDEFINED;
1422 static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
1424 NvencContext *ctx = avctx->priv_data;
1425 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1426 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1427 NvencSurface* tmp_surface = &ctx->surfaces[idx];
1429 NVENCSTATUS nv_status;
1430 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
1431 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1433 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1434 ctx->surfaces[idx].in_ref = av_frame_alloc();
1435 if (!ctx->surfaces[idx].in_ref)
1436 return AVERROR(ENOMEM);
1438 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1440 ctx->surfaces[idx].format = nvenc_map_buffer_format(ctx->data_pix_fmt);
1441 if (ctx->surfaces[idx].format == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1442 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1443 av_get_pix_fmt_name(ctx->data_pix_fmt));
1444 return AVERROR(EINVAL);
1447 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1448 allocSurf.width = avctx->width;
1449 allocSurf.height = avctx->height;
1450 allocSurf.bufferFmt = ctx->surfaces[idx].format;
1452 nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
1453 if (nv_status != NV_ENC_SUCCESS) {
1454 return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
1457 ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
1458 ctx->surfaces[idx].width = allocSurf.width;
1459 ctx->surfaces[idx].height = allocSurf.height;
1462 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
1463 if (nv_status != NV_ENC_SUCCESS) {
1464 int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
1465 if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
1466 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
1467 av_frame_free(&ctx->surfaces[idx].in_ref);
1471 ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1472 ctx->surfaces[idx].size = allocOut.size;
1474 av_fifo_generic_write(ctx->unused_surface_queue, &tmp_surface, sizeof(tmp_surface), NULL);
1479 static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx)
1481 NvencContext *ctx = avctx->priv_data;
1482 int i, res = 0, res2;
1484 ctx->surfaces = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->surfaces));
1486 return AVERROR(ENOMEM);
1488 ctx->timestamp_list = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
1489 if (!ctx->timestamp_list)
1490 return AVERROR(ENOMEM);
1492 ctx->unused_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1493 if (!ctx->unused_surface_queue)
1494 return AVERROR(ENOMEM);
1496 ctx->output_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1497 if (!ctx->output_surface_queue)
1498 return AVERROR(ENOMEM);
1499 ctx->output_surface_ready_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1500 if (!ctx->output_surface_ready_queue)
1501 return AVERROR(ENOMEM);
1503 res = nvenc_push_context(avctx);
1507 for (i = 0; i < ctx->nb_surfaces; i++) {
1508 if ((res = nvenc_alloc_surface(avctx, i)) < 0)
1513 res2 = nvenc_pop_context(avctx);
1520 static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
1522 NvencContext *ctx = avctx->priv_data;
1523 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1524 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1526 NVENCSTATUS nv_status;
1527 uint32_t outSize = 0;
1528 char tmpHeader[256];
1529 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1530 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1532 payload.spsppsBuffer = tmpHeader;
1533 payload.inBufferSize = sizeof(tmpHeader);
1534 payload.outSPSPPSPayloadSize = &outSize;
1536 nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
1537 if (nv_status != NV_ENC_SUCCESS) {
1538 return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
1541 avctx->extradata_size = outSize;
1542 avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
1544 if (!avctx->extradata) {
1545 return AVERROR(ENOMEM);
1548 memcpy(avctx->extradata, tmpHeader, outSize);
1553 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
1555 NvencContext *ctx = avctx->priv_data;
1556 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1557 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1560 /* the encoder has to be flushed before it can be closed */
1561 if (ctx->nvencoder) {
1562 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
1563 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
1565 res = nvenc_push_context(avctx);
1569 p_nvenc->nvEncEncodePicture(ctx->nvencoder, ¶ms);
1572 av_fifo_freep(&ctx->timestamp_list);
1573 av_fifo_freep(&ctx->output_surface_ready_queue);
1574 av_fifo_freep(&ctx->output_surface_queue);
1575 av_fifo_freep(&ctx->unused_surface_queue);
1577 if (ctx->surfaces && (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11)) {
1578 for (i = 0; i < ctx->nb_registered_frames; i++) {
1579 if (ctx->registered_frames[i].mapped)
1580 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[i].in_map.mappedResource);
1581 if (ctx->registered_frames[i].regptr)
1582 p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1584 ctx->nb_registered_frames = 0;
1587 if (ctx->surfaces) {
1588 for (i = 0; i < ctx->nb_surfaces; ++i) {
1589 if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
1590 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
1591 av_frame_free(&ctx->surfaces[i].in_ref);
1592 p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
1595 av_freep(&ctx->surfaces);
1596 ctx->nb_surfaces = 0;
1598 av_frame_free(&ctx->frame);
1600 if (ctx->nvencoder) {
1601 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1603 res = nvenc_pop_context(avctx);
1607 ctx->nvencoder = NULL;
1609 if (ctx->cu_context_internal)
1610 CHECK_CU(dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal));
1611 ctx->cu_context = ctx->cu_context_internal = NULL;
1614 if (ctx->d3d11_device) {
1615 ID3D11Device_Release(ctx->d3d11_device);
1616 ctx->d3d11_device = NULL;
1620 nvenc_free_functions(&dl_fn->nvenc_dl);
1621 cuda_free_functions(&dl_fn->cuda_dl);
1623 dl_fn->nvenc_device_count = 0;
1625 av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
1630 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
1632 NvencContext *ctx = avctx->priv_data;
1635 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1636 AVHWFramesContext *frames_ctx;
1637 if (!avctx->hw_frames_ctx) {
1638 av_log(avctx, AV_LOG_ERROR,
1639 "hw_frames_ctx must be set when using GPU frames as input\n");
1640 return AVERROR(EINVAL);
1642 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1643 if (frames_ctx->format != avctx->pix_fmt) {
1644 av_log(avctx, AV_LOG_ERROR,
1645 "hw_frames_ctx must match the GPU frame type\n");
1646 return AVERROR(EINVAL);
1648 ctx->data_pix_fmt = frames_ctx->sw_format;
1650 ctx->data_pix_fmt = avctx->pix_fmt;
1653 ctx->frame = av_frame_alloc();
1655 return AVERROR(ENOMEM);
1657 if ((ret = nvenc_load_libraries(avctx)) < 0)
1660 if ((ret = nvenc_setup_device(avctx)) < 0)
1663 if ((ret = nvenc_setup_encoder(avctx)) < 0)
1666 if ((ret = nvenc_setup_surfaces(avctx)) < 0)
1669 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1670 if ((ret = nvenc_setup_extradata(avctx)) < 0)
1677 static NvencSurface *get_free_frame(NvencContext *ctx)
1679 NvencSurface *tmp_surf;
1681 if (!(av_fifo_size(ctx->unused_surface_queue) > 0))
1685 av_fifo_generic_read(ctx->unused_surface_queue, &tmp_surf, sizeof(tmp_surf), NULL);
1689 static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *nv_surface,
1690 NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params, const AVFrame *frame)
1692 int dst_linesize[4] = {
1693 lock_buffer_params->pitch,
1694 lock_buffer_params->pitch,
1695 lock_buffer_params->pitch,
1696 lock_buffer_params->pitch
1698 uint8_t *dst_data[4];
1701 if (frame->format == AV_PIX_FMT_YUV420P)
1702 dst_linesize[1] = dst_linesize[2] >>= 1;
1704 ret = av_image_fill_pointers(dst_data, frame->format, nv_surface->height,
1705 lock_buffer_params->bufferDataPtr, dst_linesize);
1709 if (frame->format == AV_PIX_FMT_YUV420P)
1710 FFSWAP(uint8_t*, dst_data[1], dst_data[2]);
1712 av_image_copy(dst_data, dst_linesize,
1713 (const uint8_t**)frame->data, frame->linesize, frame->format,
1714 avctx->width, avctx->height);
1719 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1721 NvencContext *ctx = avctx->priv_data;
1722 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1723 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1724 NVENCSTATUS nv_status;
1728 if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1729 for (first_round = 1; first_round >= 0; first_round--) {
1730 for (i = 0; i < ctx->nb_registered_frames; i++) {
1731 if (!ctx->registered_frames[i].mapped) {
1732 if (ctx->registered_frames[i].regptr) {
1735 nv_status = p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1736 if (nv_status != NV_ENC_SUCCESS)
1737 return nvenc_print_error(avctx, nv_status, "Failed unregistering unused input resource");
1738 ctx->registered_frames[i].ptr = NULL;
1739 ctx->registered_frames[i].regptr = NULL;
1746 return ctx->nb_registered_frames++;
1749 av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1750 return AVERROR(ENOMEM);
1753 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1755 NvencContext *ctx = avctx->priv_data;
1756 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1757 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1759 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frame->hw_frames_ctx->data;
1760 NV_ENC_REGISTER_RESOURCE reg;
1763 for (i = 0; i < ctx->nb_registered_frames; i++) {
1764 if (avctx->pix_fmt == AV_PIX_FMT_CUDA && ctx->registered_frames[i].ptr == frame->data[0])
1766 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])
1770 idx = nvenc_find_free_reg_resource(avctx);
1774 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1775 reg.width = frames_ctx->width;
1776 reg.height = frames_ctx->height;
1777 reg.pitch = frame->linesize[0];
1778 reg.resourceToRegister = frame->data[0];
1780 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1781 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1783 else if (avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1784 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX;
1785 reg.subResourceIndex = (intptr_t)frame->data[1];
1788 reg.bufferFormat = nvenc_map_buffer_format(frames_ctx->sw_format);
1789 if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1790 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1791 av_get_pix_fmt_name(frames_ctx->sw_format));
1792 return AVERROR(EINVAL);
1795 ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, ®);
1796 if (ret != NV_ENC_SUCCESS) {
1797 nvenc_print_error(avctx, ret, "Error registering an input resource");
1798 return AVERROR_UNKNOWN;
1801 ctx->registered_frames[idx].ptr = frame->data[0];
1802 ctx->registered_frames[idx].ptr_index = reg.subResourceIndex;
1803 ctx->registered_frames[idx].regptr = reg.registeredResource;
1807 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1808 NvencSurface *nvenc_frame)
1810 NvencContext *ctx = avctx->priv_data;
1811 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1812 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1815 NVENCSTATUS nv_status;
1817 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1818 int reg_idx = nvenc_register_frame(avctx, frame);
1820 av_log(avctx, AV_LOG_ERROR, "Could not register an input HW frame\n");
1824 res = av_frame_ref(nvenc_frame->in_ref, frame);
1828 if (!ctx->registered_frames[reg_idx].mapped) {
1829 ctx->registered_frames[reg_idx].in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1830 ctx->registered_frames[reg_idx].in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1831 nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &ctx->registered_frames[reg_idx].in_map);
1832 if (nv_status != NV_ENC_SUCCESS) {
1833 av_frame_unref(nvenc_frame->in_ref);
1834 return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
1838 ctx->registered_frames[reg_idx].mapped += 1;
1840 nvenc_frame->reg_idx = reg_idx;
1841 nvenc_frame->input_surface = ctx->registered_frames[reg_idx].in_map.mappedResource;
1842 nvenc_frame->format = ctx->registered_frames[reg_idx].in_map.mappedBufferFmt;
1843 nvenc_frame->pitch = frame->linesize[0];
1847 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1849 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1850 lockBufferParams.inputBuffer = nvenc_frame->input_surface;
1852 nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
1853 if (nv_status != NV_ENC_SUCCESS) {
1854 return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
1857 nvenc_frame->pitch = lockBufferParams.pitch;
1858 res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
1860 nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
1861 if (nv_status != NV_ENC_SUCCESS) {
1862 return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
1869 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1870 NV_ENC_PIC_PARAMS *params,
1871 NV_ENC_SEI_PAYLOAD *sei_data,
1874 NvencContext *ctx = avctx->priv_data;
1876 switch (avctx->codec->id) {
1877 case AV_CODEC_ID_H264:
1878 params->codecPicParams.h264PicParams.sliceMode =
1879 ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1880 params->codecPicParams.h264PicParams.sliceModeData =
1881 ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1882 if (sei_count > 0) {
1883 params->codecPicParams.h264PicParams.seiPayloadArray = sei_data;
1884 params->codecPicParams.h264PicParams.seiPayloadArrayCnt = sei_count;
1888 case AV_CODEC_ID_HEVC:
1889 params->codecPicParams.hevcPicParams.sliceMode =
1890 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1891 params->codecPicParams.hevcPicParams.sliceModeData =
1892 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1893 if (sei_count > 0) {
1894 params->codecPicParams.hevcPicParams.seiPayloadArray = sei_data;
1895 params->codecPicParams.hevcPicParams.seiPayloadArrayCnt = sei_count;
1902 static inline void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
1904 av_fifo_generic_write(queue, ×tamp, sizeof(timestamp), NULL);
1907 static inline int64_t timestamp_queue_dequeue(AVFifoBuffer* queue)
1909 int64_t timestamp = AV_NOPTS_VALUE;
1910 if (av_fifo_size(queue) > 0)
1911 av_fifo_generic_read(queue, ×tamp, sizeof(timestamp), NULL);
1916 static int nvenc_set_timestamp(AVCodecContext *avctx,
1917 NV_ENC_LOCK_BITSTREAM *params,
1920 NvencContext *ctx = avctx->priv_data;
1922 pkt->pts = params->outputTimeStamp;
1923 pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
1925 pkt->dts -= FFMAX(avctx->max_b_frames, 0) * FFMIN(avctx->ticks_per_frame, 1);
1930 static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
1932 NvencContext *ctx = avctx->priv_data;
1933 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1934 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1936 uint32_t slice_mode_data;
1937 uint32_t *slice_offsets = NULL;
1938 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1939 NVENCSTATUS nv_status;
1942 enum AVPictureType pict_type;
1944 switch (avctx->codec->id) {
1945 case AV_CODEC_ID_H264:
1946 slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1948 case AV_CODEC_ID_H265:
1949 slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1952 av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
1953 res = AVERROR(EINVAL);
1956 slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
1958 if (!slice_offsets) {
1959 res = AVERROR(ENOMEM);
1963 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1965 lock_params.doNotWait = 0;
1966 lock_params.outputBitstream = tmpoutsurf->output_surface;
1967 lock_params.sliceOffsets = slice_offsets;
1969 nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
1970 if (nv_status != NV_ENC_SUCCESS) {
1971 res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
1975 res = av_new_packet(pkt, lock_params.bitstreamSizeInBytes);
1978 p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1982 memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1984 nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1985 if (nv_status != NV_ENC_SUCCESS) {
1986 res = nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
1991 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1992 ctx->registered_frames[tmpoutsurf->reg_idx].mapped -= 1;
1993 if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped == 0) {
1994 nv_status = p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[tmpoutsurf->reg_idx].in_map.mappedResource);
1995 if (nv_status != NV_ENC_SUCCESS) {
1996 res = nvenc_print_error(avctx, nv_status, "Failed unmapping input resource");
1999 } else if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped < 0) {
2004 av_frame_unref(tmpoutsurf->in_ref);
2006 tmpoutsurf->input_surface = NULL;
2009 switch (lock_params.pictureType) {
2010 case NV_ENC_PIC_TYPE_IDR:
2011 pkt->flags |= AV_PKT_FLAG_KEY;
2012 case NV_ENC_PIC_TYPE_I:
2013 pict_type = AV_PICTURE_TYPE_I;
2015 case NV_ENC_PIC_TYPE_P:
2016 pict_type = AV_PICTURE_TYPE_P;
2018 case NV_ENC_PIC_TYPE_B:
2019 pict_type = AV_PICTURE_TYPE_B;
2021 case NV_ENC_PIC_TYPE_BI:
2022 pict_type = AV_PICTURE_TYPE_BI;
2025 av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
2026 av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
2027 res = AVERROR_EXTERNAL;
2031 #if FF_API_CODED_FRAME
2032 FF_DISABLE_DEPRECATION_WARNINGS
2033 avctx->coded_frame->pict_type = pict_type;
2034 FF_ENABLE_DEPRECATION_WARNINGS
2037 ff_side_data_set_encoder_stats(pkt,
2038 (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
2040 res = nvenc_set_timestamp(avctx, &lock_params, pkt);
2044 av_free(slice_offsets);
2049 timestamp_queue_dequeue(ctx->timestamp_list);
2052 av_free(slice_offsets);
2057 static int output_ready(AVCodecContext *avctx, int flush)
2059 NvencContext *ctx = avctx->priv_data;
2060 int nb_ready, nb_pending;
2062 nb_ready = av_fifo_size(ctx->output_surface_ready_queue) / sizeof(NvencSurface*);
2063 nb_pending = av_fifo_size(ctx->output_surface_queue) / sizeof(NvencSurface*);
2065 return nb_ready > 0;
2066 return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
2069 static void reconfig_encoder(AVCodecContext *avctx, const AVFrame *frame)
2071 NvencContext *ctx = avctx->priv_data;
2072 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
2075 NV_ENC_RECONFIGURE_PARAMS params = { 0 };
2076 int needs_reconfig = 0;
2077 int needs_encode_config = 0;
2078 int reconfig_bitrate = 0, reconfig_dar = 0;
2081 params.version = NV_ENC_RECONFIGURE_PARAMS_VER;
2082 params.reInitEncodeParams = ctx->init_encode_params;
2084 compute_dar(avctx, &dw, &dh);
2085 if (dw != ctx->init_encode_params.darWidth || dh != ctx->init_encode_params.darHeight) {
2086 av_log(avctx, AV_LOG_VERBOSE,
2087 "aspect ratio change (DAR): %d:%d -> %d:%d\n",
2088 ctx->init_encode_params.darWidth,
2089 ctx->init_encode_params.darHeight, dw, dh);
2091 params.reInitEncodeParams.darHeight = dh;
2092 params.reInitEncodeParams.darWidth = dw;
2098 if (ctx->rc != NV_ENC_PARAMS_RC_CONSTQP && ctx->support_dyn_bitrate) {
2099 if (avctx->bit_rate > 0 && params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate != avctx->bit_rate) {
2100 av_log(avctx, AV_LOG_VERBOSE,
2101 "avg bitrate change: %d -> %d\n",
2102 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate,
2103 (uint32_t)avctx->bit_rate);
2105 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate = avctx->bit_rate;
2106 reconfig_bitrate = 1;
2109 if (avctx->rc_max_rate > 0 && ctx->encode_config.rcParams.maxBitRate != avctx->rc_max_rate) {
2110 av_log(avctx, AV_LOG_VERBOSE,
2111 "max bitrate change: %d -> %d\n",
2112 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate,
2113 (uint32_t)avctx->rc_max_rate);
2115 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate = avctx->rc_max_rate;
2116 reconfig_bitrate = 1;
2119 if (avctx->rc_buffer_size > 0 && ctx->encode_config.rcParams.vbvBufferSize != avctx->rc_buffer_size) {
2120 av_log(avctx, AV_LOG_VERBOSE,
2121 "vbv buffer size change: %d -> %d\n",
2122 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize,
2123 avctx->rc_buffer_size);
2125 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize = avctx->rc_buffer_size;
2126 reconfig_bitrate = 1;
2129 if (reconfig_bitrate) {
2130 params.resetEncoder = 1;
2131 params.forceIDR = 1;
2133 needs_encode_config = 1;
2138 if (!needs_encode_config)
2139 params.reInitEncodeParams.encodeConfig = NULL;
2141 if (needs_reconfig) {
2142 ret = p_nvenc->nvEncReconfigureEncoder(ctx->nvencoder, ¶ms);
2143 if (ret != NV_ENC_SUCCESS) {
2144 nvenc_print_error(avctx, ret, "failed to reconfigure nvenc");
2147 ctx->init_encode_params.darHeight = dh;
2148 ctx->init_encode_params.darWidth = dw;
2151 if (reconfig_bitrate) {
2152 ctx->encode_config.rcParams.averageBitRate = params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate;
2153 ctx->encode_config.rcParams.maxBitRate = params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate;
2154 ctx->encode_config.rcParams.vbvBufferSize = params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize;
2161 static int nvenc_send_frame(AVCodecContext *avctx, const AVFrame *frame)
2163 NVENCSTATUS nv_status;
2164 NvencSurface *tmp_out_surf, *in_surf;
2166 NV_ENC_SEI_PAYLOAD sei_data[8];
2170 NvencContext *ctx = avctx->priv_data;
2171 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
2172 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
2174 NV_ENC_PIC_PARAMS pic_params = { 0 };
2175 pic_params.version = NV_ENC_PIC_PARAMS_VER;
2177 if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
2178 return AVERROR(EINVAL);
2180 if (frame && frame->buf[0]) {
2181 in_surf = get_free_frame(ctx);
2183 return AVERROR(EAGAIN);
2185 res = nvenc_push_context(avctx);
2189 reconfig_encoder(avctx, frame);
2191 res = nvenc_upload_frame(avctx, frame, in_surf);
2193 res2 = nvenc_pop_context(avctx);
2200 pic_params.inputBuffer = in_surf->input_surface;
2201 pic_params.bufferFmt = in_surf->format;
2202 pic_params.inputWidth = in_surf->width;
2203 pic_params.inputHeight = in_surf->height;
2204 pic_params.inputPitch = in_surf->pitch;
2205 pic_params.outputBitstream = in_surf->output_surface;
2207 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
2208 if (frame->top_field_first)
2209 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
2211 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
2213 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
2216 if (ctx->forced_idr >= 0 && frame->pict_type == AV_PICTURE_TYPE_I) {
2217 pic_params.encodePicFlags =
2218 ctx->forced_idr ? NV_ENC_PIC_FLAG_FORCEIDR : NV_ENC_PIC_FLAG_FORCEINTRA;
2220 pic_params.encodePicFlags = 0;
2223 pic_params.inputTimeStamp = frame->pts;
2225 if (ctx->a53_cc && av_frame_get_side_data(frame, AV_FRAME_DATA_A53_CC)) {
2226 void *a53_data = NULL;
2227 size_t a53_size = 0;
2229 if (ff_alloc_a53_sei(frame, 0, (void**)&a53_data, &a53_size) < 0) {
2230 av_log(ctx, AV_LOG_ERROR, "Not enough memory for closed captions, skipping\n");
2234 sei_data[sei_count].payloadSize = (uint32_t)a53_size;
2235 sei_data[sei_count].payloadType = 4;
2236 sei_data[sei_count].payload = (uint8_t*)a53_data;
2241 if (ctx->s12m_tc && av_frame_get_side_data(frame, AV_FRAME_DATA_S12M_TIMECODE)) {
2242 void *tc_data = NULL;
2245 if (ff_alloc_timecode_sei(frame, avctx->framerate, 0, (void**)&tc_data, &tc_size) < 0) {
2246 av_log(ctx, AV_LOG_ERROR, "Not enough memory for timecode sei, skipping\n");
2250 sei_data[sei_count].payloadSize = (uint32_t)tc_size;
2251 sei_data[sei_count].payloadType = HEVC_SEI_TYPE_TIME_CODE;
2252 sei_data[sei_count].payload = (uint8_t*)tc_data;
2257 nvenc_codec_specific_pic_params(avctx, &pic_params, sei_data, sei_count);
2259 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
2262 res = nvenc_push_context(avctx);
2266 nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
2268 for ( i = 0; i < sei_count; i++)
2269 av_freep(&sei_data[i].payload);
2271 res = nvenc_pop_context(avctx);
2275 if (nv_status != NV_ENC_SUCCESS &&
2276 nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
2277 return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
2279 if (frame && frame->buf[0]) {
2280 av_fifo_generic_write(ctx->output_surface_queue, &in_surf, sizeof(in_surf), NULL);
2281 timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
2284 /* all the pending buffers are now ready for output */
2285 if (nv_status == NV_ENC_SUCCESS) {
2286 while (av_fifo_size(ctx->output_surface_queue) > 0) {
2287 av_fifo_generic_read(ctx->output_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2288 av_fifo_generic_write(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2295 int ff_nvenc_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
2297 NvencSurface *tmp_out_surf;
2300 NvencContext *ctx = avctx->priv_data;
2302 AVFrame *frame = ctx->frame;
2304 if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
2305 return AVERROR(EINVAL);
2307 if (!frame->buf[0]) {
2308 res = ff_encode_get_frame(avctx, frame);
2309 if (res < 0 && res != AVERROR_EOF)
2313 res = nvenc_send_frame(avctx, frame);
2315 if (res != AVERROR(EAGAIN))
2318 av_frame_unref(frame);
2320 if (output_ready(avctx, avctx->internal->draining)) {
2321 av_fifo_generic_read(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2323 res = nvenc_push_context(avctx);
2327 res = process_output_surface(avctx, pkt, tmp_out_surf);
2329 res2 = nvenc_pop_context(avctx);
2336 av_fifo_generic_write(ctx->unused_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2337 } else if (avctx->internal->draining) {
2340 return AVERROR(EAGAIN);
2346 av_cold void ff_nvenc_encode_flush(AVCodecContext *avctx)
2348 NvencContext *ctx = avctx->priv_data;
2350 nvenc_send_frame(avctx, NULL);
2351 av_fifo_reset(ctx->timestamp_list);