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 const enum AVPixelFormat ff_nvenc_pix_fmts[] = {
51 AV_PIX_FMT_P016, // Truncated to 10bits
52 AV_PIX_FMT_YUV444P16, // Truncated to 10bits
56 AV_PIX_FMT_GBRP16, // Truncated to 10bits
64 const AVCodecHWConfigInternal *const ff_nvenc_hw_configs[] = {
65 HW_CONFIG_ENCODER_FRAMES(CUDA, CUDA),
66 HW_CONFIG_ENCODER_DEVICE(NONE, CUDA),
68 HW_CONFIG_ENCODER_FRAMES(D3D11, D3D11VA),
69 HW_CONFIG_ENCODER_DEVICE(NONE, D3D11VA),
74 #define IS_10BIT(pix_fmt) (pix_fmt == AV_PIX_FMT_P010 || \
75 pix_fmt == AV_PIX_FMT_P016 || \
76 pix_fmt == AV_PIX_FMT_YUV444P16 || \
77 pix_fmt == AV_PIX_FMT_GBRP16)
79 #define IS_YUV444(pix_fmt) (pix_fmt == AV_PIX_FMT_YUV444P || \
80 pix_fmt == AV_PIX_FMT_YUV444P16 || \
81 pix_fmt == AV_PIX_FMT_GBRP || \
82 pix_fmt == AV_PIX_FMT_GBRP16)
84 #define IS_GBRP(pix_fmt) (pix_fmt == AV_PIX_FMT_GBRP || \
85 pix_fmt == AV_PIX_FMT_GBRP16)
92 { NV_ENC_SUCCESS, 0, "success" },
93 { NV_ENC_ERR_NO_ENCODE_DEVICE, AVERROR(ENOENT), "no encode device" },
94 { NV_ENC_ERR_UNSUPPORTED_DEVICE, AVERROR(ENOSYS), "unsupported device" },
95 { NV_ENC_ERR_INVALID_ENCODERDEVICE, AVERROR(EINVAL), "invalid encoder device" },
96 { NV_ENC_ERR_INVALID_DEVICE, AVERROR(EINVAL), "invalid device" },
97 { NV_ENC_ERR_DEVICE_NOT_EXIST, AVERROR(EIO), "device does not exist" },
98 { NV_ENC_ERR_INVALID_PTR, AVERROR(EFAULT), "invalid ptr" },
99 { NV_ENC_ERR_INVALID_EVENT, AVERROR(EINVAL), "invalid event" },
100 { NV_ENC_ERR_INVALID_PARAM, AVERROR(EINVAL), "invalid param" },
101 { NV_ENC_ERR_INVALID_CALL, AVERROR(EINVAL), "invalid call" },
102 { NV_ENC_ERR_OUT_OF_MEMORY, AVERROR(ENOMEM), "out of memory" },
103 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED, AVERROR(EINVAL), "encoder not initialized" },
104 { NV_ENC_ERR_UNSUPPORTED_PARAM, AVERROR(ENOSYS), "unsupported param" },
105 { NV_ENC_ERR_LOCK_BUSY, AVERROR(EAGAIN), "lock busy" },
106 { NV_ENC_ERR_NOT_ENOUGH_BUFFER, AVERROR_BUFFER_TOO_SMALL, "not enough buffer"},
107 { NV_ENC_ERR_INVALID_VERSION, AVERROR(EINVAL), "invalid version" },
108 { NV_ENC_ERR_MAP_FAILED, AVERROR(EIO), "map failed" },
109 { NV_ENC_ERR_NEED_MORE_INPUT, AVERROR(EAGAIN), "need more input" },
110 { NV_ENC_ERR_ENCODER_BUSY, AVERROR(EAGAIN), "encoder busy" },
111 { NV_ENC_ERR_EVENT_NOT_REGISTERD, AVERROR(EBADF), "event not registered" },
112 { NV_ENC_ERR_GENERIC, AVERROR_UNKNOWN, "generic error" },
113 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY, AVERROR(EINVAL), "incompatible client key" },
114 { NV_ENC_ERR_UNIMPLEMENTED, AVERROR(ENOSYS), "unimplemented" },
115 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO), "resource register failed" },
116 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED, AVERROR(EBADF), "resource not registered" },
117 { NV_ENC_ERR_RESOURCE_NOT_MAPPED, AVERROR(EBADF), "resource not mapped" },
120 static int nvenc_map_error(NVENCSTATUS err, const char **desc)
123 for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
124 if (nvenc_errors[i].nverr == err) {
126 *desc = nvenc_errors[i].desc;
127 return nvenc_errors[i].averr;
131 *desc = "unknown error";
132 return AVERROR_UNKNOWN;
135 static int nvenc_print_error(AVCodecContext *avctx, NVENCSTATUS err,
136 const char *error_string)
139 const char *details = "(no details)";
140 int ret = nvenc_map_error(err, &desc);
142 #ifdef NVENC_HAVE_GETLASTERRORSTRING
143 NvencContext *ctx = avctx->priv_data;
144 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
146 if (p_nvenc && ctx->nvencoder)
147 details = p_nvenc->nvEncGetLastErrorString(ctx->nvencoder);
150 av_log(avctx, AV_LOG_ERROR, "%s: %s (%d): %s\n", error_string, desc, err, details);
155 typedef struct GUIDTuple {
160 #define PRESET_ALIAS(alias, name, ...) \
161 [PRESET_ ## alias] = { NV_ENC_PRESET_ ## name ## _GUID, __VA_ARGS__ }
163 #define PRESET(name, ...) PRESET_ALIAS(name, name, __VA_ARGS__)
165 static void nvenc_map_preset(NvencContext *ctx)
167 GUIDTuple presets[] = {
168 #ifdef NVENC_HAVE_NEW_PRESETS
176 PRESET_ALIAS(SLOW, P7, NVENC_TWO_PASSES),
177 PRESET_ALIAS(MEDIUM, P4, NVENC_ONE_PASS),
178 PRESET_ALIAS(FAST, P1, NVENC_ONE_PASS),
180 PRESET_ALIAS(DEFAULT, P4, NVENC_DEPRECATED_PRESET),
181 PRESET_ALIAS(HP, P1, NVENC_DEPRECATED_PRESET),
182 PRESET_ALIAS(HQ, P7, NVENC_DEPRECATED_PRESET),
183 PRESET_ALIAS(BD, P5, NVENC_DEPRECATED_PRESET),
184 PRESET_ALIAS(LOW_LATENCY_DEFAULT, P4, NVENC_DEPRECATED_PRESET | NVENC_LOWLATENCY),
185 PRESET_ALIAS(LOW_LATENCY_HP, P1, NVENC_DEPRECATED_PRESET | NVENC_LOWLATENCY),
186 PRESET_ALIAS(LOW_LATENCY_HQ, P7, NVENC_DEPRECATED_PRESET | NVENC_LOWLATENCY),
187 PRESET_ALIAS(LOSSLESS_DEFAULT, P4, NVENC_DEPRECATED_PRESET | NVENC_LOSSLESS),
188 PRESET_ALIAS(LOSSLESS_HP, P1, NVENC_DEPRECATED_PRESET | NVENC_LOSSLESS),
194 PRESET_ALIAS(SLOW, HQ, NVENC_TWO_PASSES),
195 PRESET_ALIAS(MEDIUM, HQ, NVENC_ONE_PASS),
196 PRESET_ALIAS(FAST, HP, NVENC_ONE_PASS),
197 PRESET(LOW_LATENCY_DEFAULT, NVENC_LOWLATENCY),
198 PRESET(LOW_LATENCY_HP, NVENC_LOWLATENCY),
199 PRESET(LOW_LATENCY_HQ, NVENC_LOWLATENCY),
200 PRESET(LOSSLESS_DEFAULT, NVENC_LOSSLESS),
201 PRESET(LOSSLESS_HP, NVENC_LOSSLESS),
205 GUIDTuple *t = &presets[ctx->preset];
207 ctx->init_encode_params.presetGUID = t->guid;
208 ctx->flags = t->flags;
210 #ifdef NVENC_HAVE_NEW_PRESETS
211 if (ctx->tuning_info == NV_ENC_TUNING_INFO_LOSSLESS)
212 ctx->flags |= NVENC_LOSSLESS;
219 static void nvenc_print_driver_requirement(AVCodecContext *avctx, int level)
221 #if NVENCAPI_CHECK_VERSION(11, 1)
222 const char *minver = "(unknown)";
223 #elif NVENCAPI_CHECK_VERSION(11, 0)
224 # if defined(_WIN32) || defined(__CYGWIN__)
225 const char *minver = "456.71";
227 const char *minver = "455.28";
229 #elif NVENCAPI_CHECK_VERSION(10, 0)
230 # if defined(_WIN32) || defined(__CYGWIN__)
231 const char *minver = "450.51";
233 const char *minver = "445.87";
235 #elif NVENCAPI_CHECK_VERSION(9, 1)
236 # if defined(_WIN32) || defined(__CYGWIN__)
237 const char *minver = "436.15";
239 const char *minver = "435.21";
241 #elif NVENCAPI_CHECK_VERSION(9, 0)
242 # if defined(_WIN32) || defined(__CYGWIN__)
243 const char *minver = "418.81";
245 const char *minver = "418.30";
247 #elif NVENCAPI_CHECK_VERSION(8, 2)
248 # if defined(_WIN32) || defined(__CYGWIN__)
249 const char *minver = "397.93";
251 const char *minver = "396.24";
253 #elif NVENCAPI_CHECK_VERSION(8, 1)
254 # if defined(_WIN32) || defined(__CYGWIN__)
255 const char *minver = "390.77";
257 const char *minver = "390.25";
260 # if defined(_WIN32) || defined(__CYGWIN__)
261 const char *minver = "378.66";
263 const char *minver = "378.13";
266 av_log(avctx, level, "The minimum required Nvidia driver for nvenc is %s or newer\n", minver);
269 static av_cold int nvenc_load_libraries(AVCodecContext *avctx)
271 NvencContext *ctx = avctx->priv_data;
272 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
274 uint32_t nvenc_max_ver;
277 ret = cuda_load_functions(&dl_fn->cuda_dl, avctx);
281 ret = nvenc_load_functions(&dl_fn->nvenc_dl, avctx);
283 nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
287 err = dl_fn->nvenc_dl->NvEncodeAPIGetMaxSupportedVersion(&nvenc_max_ver);
288 if (err != NV_ENC_SUCCESS)
289 return nvenc_print_error(avctx, err, "Failed to query nvenc max version");
291 av_log(avctx, AV_LOG_VERBOSE, "Loaded Nvenc version %d.%d\n", nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
293 if ((NVENCAPI_MAJOR_VERSION << 4 | NVENCAPI_MINOR_VERSION) > nvenc_max_ver) {
294 av_log(avctx, AV_LOG_ERROR, "Driver does not support the required nvenc API version. "
295 "Required: %d.%d Found: %d.%d\n",
296 NVENCAPI_MAJOR_VERSION, NVENCAPI_MINOR_VERSION,
297 nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
298 nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
299 return AVERROR(ENOSYS);
302 dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
304 err = dl_fn->nvenc_dl->NvEncodeAPICreateInstance(&dl_fn->nvenc_funcs);
305 if (err != NV_ENC_SUCCESS)
306 return nvenc_print_error(avctx, err, "Failed to create nvenc instance");
308 av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
313 static int nvenc_push_context(AVCodecContext *avctx)
315 NvencContext *ctx = avctx->priv_data;
316 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
318 if (ctx->d3d11_device)
321 return CHECK_CU(dl_fn->cuda_dl->cuCtxPushCurrent(ctx->cu_context));
324 static int nvenc_pop_context(AVCodecContext *avctx)
326 NvencContext *ctx = avctx->priv_data;
327 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
330 if (ctx->d3d11_device)
333 return CHECK_CU(dl_fn->cuda_dl->cuCtxPopCurrent(&dummy));
336 static av_cold int nvenc_open_session(AVCodecContext *avctx)
338 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
339 NvencContext *ctx = avctx->priv_data;
340 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
343 params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
344 params.apiVersion = NVENCAPI_VERSION;
345 if (ctx->d3d11_device) {
346 params.device = ctx->d3d11_device;
347 params.deviceType = NV_ENC_DEVICE_TYPE_DIRECTX;
349 params.device = ctx->cu_context;
350 params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
353 ret = p_nvenc->nvEncOpenEncodeSessionEx(¶ms, &ctx->nvencoder);
354 if (ret != NV_ENC_SUCCESS) {
355 ctx->nvencoder = NULL;
356 return nvenc_print_error(avctx, ret, "OpenEncodeSessionEx failed");
362 static int nvenc_check_codec_support(AVCodecContext *avctx)
364 NvencContext *ctx = avctx->priv_data;
365 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
366 int i, ret, count = 0;
369 ret = p_nvenc->nvEncGetEncodeGUIDCount(ctx->nvencoder, &count);
371 if (ret != NV_ENC_SUCCESS || !count)
372 return AVERROR(ENOSYS);
374 guids = av_malloc(count * sizeof(GUID));
376 return AVERROR(ENOMEM);
378 ret = p_nvenc->nvEncGetEncodeGUIDs(ctx->nvencoder, guids, count, &count);
379 if (ret != NV_ENC_SUCCESS) {
380 ret = AVERROR(ENOSYS);
384 ret = AVERROR(ENOSYS);
385 for (i = 0; i < count; i++) {
386 if (!memcmp(&guids[i], &ctx->init_encode_params.encodeGUID, sizeof(*guids))) {
398 static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
400 NvencContext *ctx = avctx->priv_data;
401 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
402 NV_ENC_CAPS_PARAM params = { 0 };
405 params.version = NV_ENC_CAPS_PARAM_VER;
406 params.capsToQuery = cap;
408 ret = p_nvenc->nvEncGetEncodeCaps(ctx->nvencoder, ctx->init_encode_params.encodeGUID, ¶ms, &val);
410 if (ret == NV_ENC_SUCCESS)
415 static int nvenc_check_capabilities(AVCodecContext *avctx)
417 NvencContext *ctx = avctx->priv_data;
420 ret = nvenc_check_codec_support(avctx);
422 av_log(avctx, AV_LOG_WARNING, "Codec not supported\n");
426 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
427 if (IS_YUV444(ctx->data_pix_fmt) && ret <= 0) {
428 av_log(avctx, AV_LOG_WARNING, "YUV444P not supported\n");
429 return AVERROR(ENOSYS);
432 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOSSLESS_ENCODE);
433 if (ctx->flags & NVENC_LOSSLESS && ret <= 0) {
434 av_log(avctx, AV_LOG_WARNING, "Lossless encoding not supported\n");
435 return AVERROR(ENOSYS);
438 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
439 if (ret < avctx->width) {
440 av_log(avctx, AV_LOG_WARNING, "Width %d exceeds %d\n",
442 return AVERROR(ENOSYS);
445 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
446 if (ret < avctx->height) {
447 av_log(avctx, AV_LOG_WARNING, "Height %d exceeds %d\n",
449 return AVERROR(ENOSYS);
452 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
453 if (ret < avctx->max_b_frames) {
454 av_log(avctx, AV_LOG_WARNING, "Max B-frames %d exceed %d\n",
455 avctx->max_b_frames, ret);
457 return AVERROR(ENOSYS);
460 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_FIELD_ENCODING);
461 if (ret < 1 && avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
462 av_log(avctx, AV_LOG_WARNING,
463 "Interlaced encoding is not supported. Supported level: %d\n",
465 return AVERROR(ENOSYS);
468 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_10BIT_ENCODE);
469 if (IS_10BIT(ctx->data_pix_fmt) && ret <= 0) {
470 av_log(avctx, AV_LOG_WARNING, "10 bit encode not supported\n");
471 return AVERROR(ENOSYS);
474 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOOKAHEAD);
475 if (ctx->rc_lookahead > 0 && ret <= 0) {
476 av_log(avctx, AV_LOG_WARNING, "RC lookahead not supported\n");
477 return AVERROR(ENOSYS);
480 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_TEMPORAL_AQ);
481 if (ctx->temporal_aq > 0 && ret <= 0) {
482 av_log(avctx, AV_LOG_WARNING, "Temporal AQ not supported\n");
483 return AVERROR(ENOSYS);
486 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_WEIGHTED_PREDICTION);
487 if (ctx->weighted_pred > 0 && ret <= 0) {
488 av_log (avctx, AV_LOG_WARNING, "Weighted Prediction not supported\n");
489 return AVERROR(ENOSYS);
492 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_CABAC);
493 if (ctx->coder == NV_ENC_H264_ENTROPY_CODING_MODE_CABAC && ret <= 0) {
494 av_log(avctx, AV_LOG_WARNING, "CABAC entropy coding not supported\n");
495 return AVERROR(ENOSYS);
498 #ifdef NVENC_HAVE_BFRAME_REF_MODE
499 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_BFRAME_REF_MODE);
500 if (ctx->b_ref_mode == NV_ENC_BFRAME_REF_MODE_EACH && ret != 1 && ret != 3) {
501 av_log(avctx, AV_LOG_WARNING, "Each B frame as reference is not supported\n");
502 return AVERROR(ENOSYS);
503 } else if (ctx->b_ref_mode != NV_ENC_BFRAME_REF_MODE_DISABLED && ret == 0) {
504 av_log(avctx, AV_LOG_WARNING, "B frames as references are not supported\n");
505 return AVERROR(ENOSYS);
508 if (ctx->b_ref_mode != 0) {
509 av_log(avctx, AV_LOG_WARNING, "B frames as references need SDK 8.1 at build time\n");
510 return AVERROR(ENOSYS);
514 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
515 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_MULTIPLE_REF_FRAMES);
516 if(avctx->refs != NV_ENC_NUM_REF_FRAMES_AUTOSELECT && ret <= 0) {
517 av_log(avctx, AV_LOG_WARNING, "Multiple reference frames are not supported by the device\n");
518 return AVERROR(ENOSYS);
521 if(avctx->refs != 0) {
522 av_log(avctx, AV_LOG_WARNING, "Multiple reference frames need SDK 9.1 at build time\n");
523 return AVERROR(ENOSYS);
527 ctx->support_dyn_bitrate = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_DYN_BITRATE_CHANGE);
532 static av_cold int nvenc_check_device(AVCodecContext *avctx, int idx)
534 NvencContext *ctx = avctx->priv_data;
535 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
536 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
537 char name[128] = { 0};
538 int major, minor, ret;
540 int loglevel = AV_LOG_VERBOSE;
542 if (ctx->device == LIST_DEVICES)
543 loglevel = AV_LOG_INFO;
545 ret = CHECK_CU(dl_fn->cuda_dl->cuDeviceGet(&cu_device, idx));
549 ret = CHECK_CU(dl_fn->cuda_dl->cuDeviceGetName(name, sizeof(name), cu_device));
553 ret = CHECK_CU(dl_fn->cuda_dl->cuDeviceComputeCapability(&major, &minor, cu_device));
557 av_log(avctx, loglevel, "[ GPU #%d - < %s > has Compute SM %d.%d ]\n", idx, name, major, minor);
558 if (((major << 4) | minor) < NVENC_CAP) {
559 av_log(avctx, loglevel, "does not support NVENC\n");
563 if (ctx->device != idx && ctx->device != ANY_DEVICE)
566 ret = CHECK_CU(dl_fn->cuda_dl->cuCtxCreate(&ctx->cu_context_internal, 0, cu_device));
570 ctx->cu_context = ctx->cu_context_internal;
571 ctx->cu_stream = NULL;
573 if ((ret = nvenc_pop_context(avctx)) < 0)
576 if ((ret = nvenc_open_session(avctx)) < 0)
579 if ((ret = nvenc_check_capabilities(avctx)) < 0)
582 av_log(avctx, loglevel, "supports NVENC\n");
584 dl_fn->nvenc_device_count++;
586 if (ctx->device == idx || ctx->device == ANY_DEVICE)
590 if ((ret = nvenc_push_context(avctx)) < 0)
593 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
594 ctx->nvencoder = NULL;
596 if ((ret = nvenc_pop_context(avctx)) < 0)
600 CHECK_CU(dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal));
601 ctx->cu_context_internal = NULL;
604 return AVERROR(ENOSYS);
607 static av_cold int nvenc_setup_device(AVCodecContext *avctx)
609 NvencContext *ctx = avctx->priv_data;
610 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
612 switch (avctx->codec->id) {
613 case AV_CODEC_ID_H264:
614 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
616 case AV_CODEC_ID_HEVC:
617 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
623 nvenc_map_preset(ctx);
625 if (ctx->flags & NVENC_DEPRECATED_PRESET)
626 av_log(avctx, AV_LOG_WARNING, "The selected preset is deprecated. Use p1 to p7 + -tune or fast/medium/slow.\n");
628 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11 || avctx->hw_frames_ctx || avctx->hw_device_ctx) {
629 AVHWFramesContext *frames_ctx;
630 AVHWDeviceContext *hwdev_ctx;
631 AVCUDADeviceContext *cuda_device_hwctx = NULL;
633 AVD3D11VADeviceContext *d3d11_device_hwctx = NULL;
637 if (avctx->hw_frames_ctx) {
638 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
639 if (frames_ctx->format == AV_PIX_FMT_CUDA)
640 cuda_device_hwctx = frames_ctx->device_ctx->hwctx;
642 else if (frames_ctx->format == AV_PIX_FMT_D3D11)
643 d3d11_device_hwctx = frames_ctx->device_ctx->hwctx;
646 return AVERROR(EINVAL);
647 } else if (avctx->hw_device_ctx) {
648 hwdev_ctx = (AVHWDeviceContext*)avctx->hw_device_ctx->data;
649 if (hwdev_ctx->type == AV_HWDEVICE_TYPE_CUDA)
650 cuda_device_hwctx = hwdev_ctx->hwctx;
652 else if (hwdev_ctx->type == AV_HWDEVICE_TYPE_D3D11VA)
653 d3d11_device_hwctx = hwdev_ctx->hwctx;
656 return AVERROR(EINVAL);
658 return AVERROR(EINVAL);
661 if (cuda_device_hwctx) {
662 ctx->cu_context = cuda_device_hwctx->cuda_ctx;
663 ctx->cu_stream = cuda_device_hwctx->stream;
666 else if (d3d11_device_hwctx) {
667 ctx->d3d11_device = d3d11_device_hwctx->device;
668 ID3D11Device_AddRef(ctx->d3d11_device);
672 ret = nvenc_open_session(avctx);
676 ret = nvenc_check_capabilities(avctx);
678 av_log(avctx, AV_LOG_FATAL, "Provided device doesn't support required NVENC features\n");
682 int i, nb_devices = 0;
684 if (CHECK_CU(dl_fn->cuda_dl->cuInit(0)) < 0)
685 return AVERROR_UNKNOWN;
687 if (CHECK_CU(dl_fn->cuda_dl->cuDeviceGetCount(&nb_devices)) < 0)
688 return AVERROR_UNKNOWN;
691 av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
692 return AVERROR_EXTERNAL;
695 av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", nb_devices);
697 dl_fn->nvenc_device_count = 0;
698 for (i = 0; i < nb_devices; ++i) {
699 if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
703 if (ctx->device == LIST_DEVICES)
706 if (!dl_fn->nvenc_device_count) {
707 av_log(avctx, AV_LOG_FATAL, "No capable devices found\n");
708 return AVERROR_EXTERNAL;
711 av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->device, nb_devices);
712 return AVERROR(EINVAL);
718 static av_cold void set_constqp(AVCodecContext *avctx)
720 NvencContext *ctx = avctx->priv_data;
721 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
723 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
725 if (ctx->init_qp_p >= 0) {
726 rc->constQP.qpInterP = ctx->init_qp_p;
727 if (ctx->init_qp_i >= 0 && ctx->init_qp_b >= 0) {
728 rc->constQP.qpIntra = ctx->init_qp_i;
729 rc->constQP.qpInterB = ctx->init_qp_b;
730 } else if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
731 rc->constQP.qpIntra = av_clip(
732 rc->constQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
733 rc->constQP.qpInterB = av_clip(
734 rc->constQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
736 rc->constQP.qpIntra = rc->constQP.qpInterP;
737 rc->constQP.qpInterB = rc->constQP.qpInterP;
739 } else if (ctx->cqp >= 0) {
740 rc->constQP.qpInterP = rc->constQP.qpInterB = rc->constQP.qpIntra = ctx->cqp;
741 if (avctx->b_quant_factor != 0.0)
742 rc->constQP.qpInterB = av_clip(ctx->cqp * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
743 if (avctx->i_quant_factor != 0.0)
744 rc->constQP.qpIntra = av_clip(ctx->cqp * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
751 static av_cold void set_vbr(AVCodecContext *avctx)
753 NvencContext *ctx = avctx->priv_data;
754 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
757 if (avctx->qmin >= 0 && avctx->qmax >= 0) {
761 rc->minQP.qpInterB = avctx->qmin;
762 rc->minQP.qpInterP = avctx->qmin;
763 rc->minQP.qpIntra = avctx->qmin;
765 rc->maxQP.qpInterB = avctx->qmax;
766 rc->maxQP.qpInterP = avctx->qmax;
767 rc->maxQP.qpIntra = avctx->qmax;
769 qp_inter_p = (avctx->qmax + 3 * avctx->qmin) / 4; // biased towards Qmin
770 } else if (avctx->qmin >= 0) {
773 rc->minQP.qpInterB = avctx->qmin;
774 rc->minQP.qpInterP = avctx->qmin;
775 rc->minQP.qpIntra = avctx->qmin;
777 qp_inter_p = avctx->qmin;
779 qp_inter_p = 26; // default to 26
782 rc->enableInitialRCQP = 1;
784 if (ctx->init_qp_p < 0) {
785 rc->initialRCQP.qpInterP = qp_inter_p;
787 rc->initialRCQP.qpInterP = ctx->init_qp_p;
790 if (ctx->init_qp_i < 0) {
791 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
792 rc->initialRCQP.qpIntra = av_clip(
793 rc->initialRCQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
795 rc->initialRCQP.qpIntra = rc->initialRCQP.qpInterP;
798 rc->initialRCQP.qpIntra = ctx->init_qp_i;
801 if (ctx->init_qp_b < 0) {
802 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
803 rc->initialRCQP.qpInterB = av_clip(
804 rc->initialRCQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
806 rc->initialRCQP.qpInterB = rc->initialRCQP.qpInterP;
809 rc->initialRCQP.qpInterB = ctx->init_qp_b;
813 static av_cold void set_lossless(AVCodecContext *avctx)
815 NvencContext *ctx = avctx->priv_data;
816 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
818 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
819 rc->constQP.qpInterB = 0;
820 rc->constQP.qpInterP = 0;
821 rc->constQP.qpIntra = 0;
827 static void nvenc_override_rate_control(AVCodecContext *avctx)
829 NvencContext *ctx = avctx->priv_data;
830 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
833 case NV_ENC_PARAMS_RC_CONSTQP:
836 case NV_ENC_PARAMS_RC_VBR_MINQP:
837 if (avctx->qmin < 0) {
838 av_log(avctx, AV_LOG_WARNING,
839 "The variable bitrate rate-control requires "
840 "the 'qmin' option set.\n");
845 case NV_ENC_PARAMS_RC_VBR_HQ:
846 case NV_ENC_PARAMS_RC_VBR:
849 case NV_ENC_PARAMS_RC_CBR:
850 case NV_ENC_PARAMS_RC_CBR_HQ:
851 case NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ:
855 rc->rateControlMode = ctx->rc;
858 static av_cold int nvenc_recalc_surfaces(AVCodecContext *avctx)
860 NvencContext *ctx = avctx->priv_data;
861 // default minimum of 4 surfaces
862 // multiply by 2 for number of NVENCs on gpu (hardcode to 2)
863 // another multiply by 2 to avoid blocking next PBB group
864 int nb_surfaces = FFMAX(4, ctx->encode_config.frameIntervalP * 2 * 2);
867 if (ctx->rc_lookahead > 0) {
868 // +1 is to account for lkd_bound calculation later
869 // +4 is to allow sufficient pipelining with lookahead
870 nb_surfaces = FFMAX(1, FFMAX(nb_surfaces, ctx->rc_lookahead + ctx->encode_config.frameIntervalP + 1 + 4));
871 if (nb_surfaces > ctx->nb_surfaces && ctx->nb_surfaces > 0)
873 av_log(avctx, AV_LOG_WARNING,
874 "Defined rc_lookahead requires more surfaces, "
875 "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
877 ctx->nb_surfaces = FFMAX(nb_surfaces, ctx->nb_surfaces);
879 if (ctx->encode_config.frameIntervalP > 1 && ctx->nb_surfaces < nb_surfaces && ctx->nb_surfaces > 0)
881 av_log(avctx, AV_LOG_WARNING,
882 "Defined b-frame requires more surfaces, "
883 "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
884 ctx->nb_surfaces = FFMAX(ctx->nb_surfaces, nb_surfaces);
886 else if (ctx->nb_surfaces <= 0)
887 ctx->nb_surfaces = nb_surfaces;
888 // otherwise use user specified value
891 ctx->nb_surfaces = FFMAX(1, FFMIN(MAX_REGISTERED_FRAMES, ctx->nb_surfaces));
892 ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
897 static av_cold void nvenc_setup_rate_control(AVCodecContext *avctx)
899 NvencContext *ctx = avctx->priv_data;
901 if (avctx->global_quality > 0)
902 av_log(avctx, AV_LOG_WARNING, "Using global_quality with nvenc is deprecated. Use qp instead.\n");
904 if (ctx->cqp < 0 && avctx->global_quality > 0)
905 ctx->cqp = avctx->global_quality;
907 if (avctx->bit_rate > 0) {
908 ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
909 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
910 ctx->encode_config.rcParams.maxBitRate = ctx->encode_config.rcParams.averageBitRate;
913 if (avctx->rc_max_rate > 0)
914 ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
916 #ifdef NVENC_HAVE_MULTIPASS
917 ctx->encode_config.rcParams.multiPass = ctx->multipass;
919 if (ctx->flags & NVENC_ONE_PASS)
920 ctx->encode_config.rcParams.multiPass = NV_ENC_MULTI_PASS_DISABLED;
921 if (ctx->flags & NVENC_TWO_PASSES || ctx->twopass > 0)
922 ctx->encode_config.rcParams.multiPass = NV_ENC_TWO_PASS_FULL_RESOLUTION;
926 ctx->rc = NV_ENC_PARAMS_RC_CBR;
927 } else if (ctx->cqp >= 0) {
928 ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
929 } else if (ctx->quality >= 0.0f) {
930 ctx->rc = NV_ENC_PARAMS_RC_VBR;
935 if (ctx->flags & NVENC_ONE_PASS)
937 if (ctx->flags & NVENC_TWO_PASSES)
940 if (ctx->twopass < 0)
941 ctx->twopass = (ctx->flags & NVENC_LOWLATENCY) != 0;
945 ctx->rc = NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ;
947 ctx->rc = NV_ENC_PARAMS_RC_CBR;
949 } else if (ctx->cqp >= 0) {
950 ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
951 } else if (ctx->twopass) {
952 ctx->rc = NV_ENC_PARAMS_RC_VBR_HQ;
953 } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
954 ctx->rc = NV_ENC_PARAMS_RC_VBR_MINQP;
959 if (ctx->rc >= 0 && ctx->rc & RC_MODE_DEPRECATED) {
960 av_log(avctx, AV_LOG_WARNING, "Specified rc mode is deprecated.\n");
961 av_log(avctx, AV_LOG_WARNING, "Use -rc constqp/cbr/vbr, -tune and -multipass instead.\n");
963 ctx->rc &= ~RC_MODE_DEPRECATED;
966 #ifdef NVENC_HAVE_LDKFS
968 ctx->encode_config.rcParams.lowDelayKeyFrameScale = ctx->ldkfs;
971 if (ctx->flags & NVENC_LOSSLESS) {
973 } else if (ctx->rc >= 0) {
974 nvenc_override_rate_control(avctx);
976 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
980 if (avctx->rc_buffer_size > 0) {
981 ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
982 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
983 avctx->rc_buffer_size = ctx->encode_config.rcParams.vbvBufferSize = 2 * ctx->encode_config.rcParams.averageBitRate;
987 ctx->encode_config.rcParams.enableAQ = 1;
988 ctx->encode_config.rcParams.aqStrength = ctx->aq_strength;
989 av_log(avctx, AV_LOG_VERBOSE, "AQ enabled.\n");
992 if (ctx->temporal_aq) {
993 ctx->encode_config.rcParams.enableTemporalAQ = 1;
994 av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ enabled.\n");
997 if (ctx->rc_lookahead > 0) {
998 int lkd_bound = FFMIN(ctx->nb_surfaces, ctx->async_depth) -
999 ctx->encode_config.frameIntervalP - 4;
1001 if (lkd_bound < 0) {
1002 av_log(avctx, AV_LOG_WARNING,
1003 "Lookahead not enabled. Increase buffer delay (-delay).\n");
1005 ctx->encode_config.rcParams.enableLookahead = 1;
1006 ctx->encode_config.rcParams.lookaheadDepth = av_clip(ctx->rc_lookahead, 0, lkd_bound);
1007 ctx->encode_config.rcParams.disableIadapt = ctx->no_scenecut;
1008 ctx->encode_config.rcParams.disableBadapt = !ctx->b_adapt;
1009 av_log(avctx, AV_LOG_VERBOSE,
1010 "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",
1011 ctx->encode_config.rcParams.lookaheadDepth,
1012 ctx->encode_config.rcParams.disableIadapt ? "disabled" : "enabled",
1013 ctx->encode_config.rcParams.disableBadapt ? "disabled" : "enabled");
1017 if (ctx->strict_gop) {
1018 ctx->encode_config.rcParams.strictGOPTarget = 1;
1019 av_log(avctx, AV_LOG_VERBOSE, "Strict GOP target enabled.\n");
1023 ctx->encode_config.rcParams.enableNonRefP = 1;
1025 if (ctx->zerolatency)
1026 ctx->encode_config.rcParams.zeroReorderDelay = 1;
1029 //convert from float to fixed point 8.8
1030 int tmp_quality = (int)(ctx->quality * 256.0f);
1031 ctx->encode_config.rcParams.targetQuality = (uint8_t)(tmp_quality >> 8);
1032 ctx->encode_config.rcParams.targetQualityLSB = (uint8_t)(tmp_quality & 0xff);
1034 av_log(avctx, AV_LOG_VERBOSE, "CQ(%d) mode enabled.\n", tmp_quality);
1036 //CQ mode shall discard avg bitrate & honor max bitrate;
1037 ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate = 0;
1038 ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
1042 static av_cold int nvenc_setup_h264_config(AVCodecContext *avctx)
1044 NvencContext *ctx = avctx->priv_data;
1045 NV_ENC_CONFIG *cc = &ctx->encode_config;
1046 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
1047 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
1049 vui->colourMatrix = IS_GBRP(ctx->data_pix_fmt) ? AVCOL_SPC_RGB : avctx->colorspace;
1050 vui->colourPrimaries = avctx->color_primaries;
1051 vui->transferCharacteristics = avctx->color_trc;
1052 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
1053 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
1055 vui->colourDescriptionPresentFlag =
1056 (vui->colourMatrix != 2 || vui->colourPrimaries != 2 || vui->transferCharacteristics != 2);
1058 vui->videoSignalTypePresentFlag =
1059 (vui->colourDescriptionPresentFlag
1060 || vui->videoFormat != 5
1061 || vui->videoFullRangeFlag != 0);
1063 h264->sliceMode = 3;
1064 h264->sliceModeData = 1;
1066 h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
1067 h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
1068 h264->outputAUD = ctx->aud;
1070 if (ctx->dpb_size >= 0) {
1071 /* 0 means "let the hardware decide" */
1072 h264->maxNumRefFrames = ctx->dpb_size;
1074 if (avctx->gop_size >= 0) {
1075 h264->idrPeriod = cc->gopLength;
1078 if (IS_CBR(cc->rcParams.rateControlMode)) {
1079 h264->outputBufferingPeriodSEI = 1;
1082 h264->outputPictureTimingSEI = 1;
1084 if (cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ ||
1085 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_HQ ||
1086 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_VBR_HQ) {
1087 h264->adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
1088 h264->fmoMode = NV_ENC_H264_FMO_DISABLE;
1091 if (ctx->flags & NVENC_LOSSLESS) {
1092 h264->qpPrimeYZeroTransformBypassFlag = 1;
1094 switch(ctx->profile) {
1095 case NV_ENC_H264_PROFILE_BASELINE:
1096 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
1097 avctx->profile = FF_PROFILE_H264_BASELINE;
1099 case NV_ENC_H264_PROFILE_MAIN:
1100 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
1101 avctx->profile = FF_PROFILE_H264_MAIN;
1103 case NV_ENC_H264_PROFILE_HIGH:
1104 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
1105 avctx->profile = FF_PROFILE_H264_HIGH;
1107 case NV_ENC_H264_PROFILE_HIGH_444P:
1108 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1109 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
1114 // force setting profile as high444p if input is AV_PIX_FMT_YUV444P
1115 if (IS_YUV444(ctx->data_pix_fmt)) {
1116 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1117 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
1120 h264->chromaFormatIDC = avctx->profile == FF_PROFILE_H264_HIGH_444_PREDICTIVE ? 3 : 1;
1122 h264->level = ctx->level;
1124 if (ctx->coder >= 0)
1125 h264->entropyCodingMode = ctx->coder;
1127 #ifdef NVENC_HAVE_BFRAME_REF_MODE
1128 h264->useBFramesAsRef = ctx->b_ref_mode;
1131 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
1132 h264->numRefL0 = avctx->refs;
1133 h264->numRefL1 = avctx->refs;
1139 static av_cold int nvenc_setup_hevc_config(AVCodecContext *avctx)
1141 NvencContext *ctx = avctx->priv_data;
1142 NV_ENC_CONFIG *cc = &ctx->encode_config;
1143 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
1144 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
1146 vui->colourMatrix = IS_GBRP(ctx->data_pix_fmt) ? AVCOL_SPC_RGB : avctx->colorspace;
1147 vui->colourPrimaries = avctx->color_primaries;
1148 vui->transferCharacteristics = avctx->color_trc;
1149 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
1150 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
1152 vui->colourDescriptionPresentFlag =
1153 (vui->colourMatrix != 2 || vui->colourPrimaries != 2 || vui->transferCharacteristics != 2);
1155 vui->videoSignalTypePresentFlag =
1156 (vui->colourDescriptionPresentFlag
1157 || vui->videoFormat != 5
1158 || vui->videoFullRangeFlag != 0);
1160 hevc->sliceMode = 3;
1161 hevc->sliceModeData = 1;
1163 hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
1164 hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
1165 hevc->outputAUD = ctx->aud;
1167 if (ctx->dpb_size >= 0) {
1168 /* 0 means "let the hardware decide" */
1169 hevc->maxNumRefFramesInDPB = ctx->dpb_size;
1171 if (avctx->gop_size >= 0) {
1172 hevc->idrPeriod = cc->gopLength;
1175 if (IS_CBR(cc->rcParams.rateControlMode)) {
1176 hevc->outputBufferingPeriodSEI = 1;
1179 hevc->outputPictureTimingSEI = 1;
1181 switch (ctx->profile) {
1182 case NV_ENC_HEVC_PROFILE_MAIN:
1183 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
1184 avctx->profile = FF_PROFILE_HEVC_MAIN;
1186 case NV_ENC_HEVC_PROFILE_MAIN_10:
1187 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1188 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
1190 case NV_ENC_HEVC_PROFILE_REXT:
1191 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1192 avctx->profile = FF_PROFILE_HEVC_REXT;
1196 // force setting profile as main10 if input is 10 bit
1197 if (IS_10BIT(ctx->data_pix_fmt)) {
1198 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1199 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
1202 // force setting profile as rext if input is yuv444
1203 if (IS_YUV444(ctx->data_pix_fmt)) {
1204 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1205 avctx->profile = FF_PROFILE_HEVC_REXT;
1208 hevc->chromaFormatIDC = IS_YUV444(ctx->data_pix_fmt) ? 3 : 1;
1210 hevc->pixelBitDepthMinus8 = IS_10BIT(ctx->data_pix_fmt) ? 2 : 0;
1212 hevc->level = ctx->level;
1214 hevc->tier = ctx->tier;
1216 #ifdef NVENC_HAVE_HEVC_BFRAME_REF_MODE
1217 hevc->useBFramesAsRef = ctx->b_ref_mode;
1220 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
1221 hevc->numRefL0 = avctx->refs;
1222 hevc->numRefL1 = avctx->refs;
1228 static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx)
1230 switch (avctx->codec->id) {
1231 case AV_CODEC_ID_H264:
1232 return nvenc_setup_h264_config(avctx);
1233 case AV_CODEC_ID_HEVC:
1234 return nvenc_setup_hevc_config(avctx);
1235 /* Earlier switch/case will return if unknown codec is passed. */
1241 static void compute_dar(AVCodecContext *avctx, int *dw, int *dh) {
1247 if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0) {
1248 sw *= avctx->sample_aspect_ratio.num;
1249 sh *= avctx->sample_aspect_ratio.den;
1252 av_reduce(dw, dh, sw, sh, 1024 * 1024);
1255 static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
1257 NvencContext *ctx = avctx->priv_data;
1258 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1259 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1261 NV_ENC_PRESET_CONFIG preset_config = { 0 };
1262 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
1263 AVCPBProperties *cpb_props;
1267 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1268 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
1270 ctx->init_encode_params.encodeHeight = avctx->height;
1271 ctx->init_encode_params.encodeWidth = avctx->width;
1273 ctx->init_encode_params.encodeConfig = &ctx->encode_config;
1275 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
1276 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
1278 #ifdef NVENC_HAVE_NEW_PRESETS
1279 ctx->init_encode_params.tuningInfo = ctx->tuning_info;
1281 if (ctx->flags & NVENC_LOSSLESS)
1282 ctx->init_encode_params.tuningInfo = NV_ENC_TUNING_INFO_LOSSLESS;
1283 else if (ctx->flags & NVENC_LOWLATENCY)
1284 ctx->init_encode_params.tuningInfo = NV_ENC_TUNING_INFO_LOW_LATENCY;
1286 nv_status = p_nvenc->nvEncGetEncodePresetConfigEx(ctx->nvencoder,
1287 ctx->init_encode_params.encodeGUID,
1288 ctx->init_encode_params.presetGUID,
1289 ctx->init_encode_params.tuningInfo,
1292 nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder,
1293 ctx->init_encode_params.encodeGUID,
1294 ctx->init_encode_params.presetGUID,
1297 if (nv_status != NV_ENC_SUCCESS)
1298 return nvenc_print_error(avctx, nv_status, "Cannot get the preset configuration");
1300 memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
1302 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1304 compute_dar(avctx, &dw, &dh);
1305 ctx->init_encode_params.darHeight = dh;
1306 ctx->init_encode_params.darWidth = dw;
1308 if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {
1309 ctx->init_encode_params.frameRateNum = avctx->framerate.num;
1310 ctx->init_encode_params.frameRateDen = avctx->framerate.den;
1312 ctx->init_encode_params.frameRateNum = avctx->time_base.den;
1313 ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
1316 ctx->init_encode_params.enableEncodeAsync = 0;
1317 ctx->init_encode_params.enablePTD = 1;
1319 #ifdef NVENC_HAVE_NEW_PRESETS
1320 /* If lookahead isn't set from CLI, use value from preset.
1321 * P6 & P7 presets may enable lookahead for better quality.
1323 if (ctx->rc_lookahead == 0 && ctx->encode_config.rcParams.enableLookahead)
1324 ctx->rc_lookahead = ctx->encode_config.rcParams.lookaheadDepth;
1327 if (ctx->weighted_pred == 1)
1328 ctx->init_encode_params.enableWeightedPrediction = 1;
1330 if (ctx->bluray_compat) {
1332 ctx->dpb_size = FFMIN(FFMAX(avctx->refs, 0), 6);
1333 avctx->max_b_frames = FFMIN(avctx->max_b_frames, 3);
1334 switch (avctx->codec->id) {
1335 case AV_CODEC_ID_H264:
1336 /* maximum level depends on used resolution */
1338 case AV_CODEC_ID_HEVC:
1339 ctx->level = NV_ENC_LEVEL_HEVC_51;
1340 ctx->tier = NV_ENC_TIER_HEVC_HIGH;
1345 if (avctx->gop_size > 0) {
1346 if (avctx->max_b_frames >= 0) {
1347 /* 0 is intra-only, 1 is I/P only, 2 is one B-Frame, 3 two B-frames, and so on. */
1348 ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
1351 ctx->encode_config.gopLength = avctx->gop_size;
1352 } else if (avctx->gop_size == 0) {
1353 ctx->encode_config.frameIntervalP = 0;
1354 ctx->encode_config.gopLength = 1;
1357 nvenc_recalc_surfaces(avctx);
1359 nvenc_setup_rate_control(avctx);
1361 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1362 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
1364 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
1367 res = nvenc_setup_codec_config(avctx);
1371 res = nvenc_push_context(avctx);
1375 nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
1376 if (nv_status != NV_ENC_SUCCESS) {
1377 nvenc_pop_context(avctx);
1378 return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
1381 #ifdef NVENC_HAVE_CUSTREAM_PTR
1382 if (ctx->cu_context) {
1383 nv_status = p_nvenc->nvEncSetIOCudaStreams(ctx->nvencoder, &ctx->cu_stream, &ctx->cu_stream);
1384 if (nv_status != NV_ENC_SUCCESS) {
1385 nvenc_pop_context(avctx);
1386 return nvenc_print_error(avctx, nv_status, "SetIOCudaStreams failed");
1391 res = nvenc_pop_context(avctx);
1395 if (ctx->encode_config.frameIntervalP > 1)
1396 avctx->has_b_frames = 2;
1398 if (ctx->encode_config.rcParams.averageBitRate > 0)
1399 avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
1401 cpb_props = ff_add_cpb_side_data(avctx);
1403 return AVERROR(ENOMEM);
1404 cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
1405 cpb_props->avg_bitrate = avctx->bit_rate;
1406 cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
1411 static NV_ENC_BUFFER_FORMAT nvenc_map_buffer_format(enum AVPixelFormat pix_fmt)
1414 case AV_PIX_FMT_YUV420P:
1415 return NV_ENC_BUFFER_FORMAT_YV12_PL;
1416 case AV_PIX_FMT_NV12:
1417 return NV_ENC_BUFFER_FORMAT_NV12_PL;
1418 case AV_PIX_FMT_P010:
1419 case AV_PIX_FMT_P016:
1420 return NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1421 case AV_PIX_FMT_GBRP:
1422 case AV_PIX_FMT_YUV444P:
1423 return NV_ENC_BUFFER_FORMAT_YUV444_PL;
1424 case AV_PIX_FMT_GBRP16:
1425 case AV_PIX_FMT_YUV444P16:
1426 return NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1427 case AV_PIX_FMT_0RGB32:
1428 return NV_ENC_BUFFER_FORMAT_ARGB;
1429 case AV_PIX_FMT_0BGR32:
1430 return NV_ENC_BUFFER_FORMAT_ABGR;
1432 return NV_ENC_BUFFER_FORMAT_UNDEFINED;
1436 static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
1438 NvencContext *ctx = avctx->priv_data;
1439 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1440 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1441 NvencSurface* tmp_surface = &ctx->surfaces[idx];
1443 NVENCSTATUS nv_status;
1444 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
1445 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1447 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1448 ctx->surfaces[idx].in_ref = av_frame_alloc();
1449 if (!ctx->surfaces[idx].in_ref)
1450 return AVERROR(ENOMEM);
1452 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1454 ctx->surfaces[idx].format = nvenc_map_buffer_format(ctx->data_pix_fmt);
1455 if (ctx->surfaces[idx].format == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1456 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1457 av_get_pix_fmt_name(ctx->data_pix_fmt));
1458 return AVERROR(EINVAL);
1461 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1462 allocSurf.width = avctx->width;
1463 allocSurf.height = avctx->height;
1464 allocSurf.bufferFmt = ctx->surfaces[idx].format;
1466 nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
1467 if (nv_status != NV_ENC_SUCCESS) {
1468 return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
1471 ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
1472 ctx->surfaces[idx].width = allocSurf.width;
1473 ctx->surfaces[idx].height = allocSurf.height;
1476 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
1477 if (nv_status != NV_ENC_SUCCESS) {
1478 int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
1479 if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
1480 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
1481 av_frame_free(&ctx->surfaces[idx].in_ref);
1485 ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1487 av_fifo_generic_write(ctx->unused_surface_queue, &tmp_surface, sizeof(tmp_surface), NULL);
1492 static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx)
1494 NvencContext *ctx = avctx->priv_data;
1495 int i, res = 0, res2;
1497 ctx->surfaces = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->surfaces));
1499 return AVERROR(ENOMEM);
1501 ctx->timestamp_list = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
1502 if (!ctx->timestamp_list)
1503 return AVERROR(ENOMEM);
1505 ctx->unused_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1506 if (!ctx->unused_surface_queue)
1507 return AVERROR(ENOMEM);
1509 ctx->output_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1510 if (!ctx->output_surface_queue)
1511 return AVERROR(ENOMEM);
1512 ctx->output_surface_ready_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1513 if (!ctx->output_surface_ready_queue)
1514 return AVERROR(ENOMEM);
1516 res = nvenc_push_context(avctx);
1520 for (i = 0; i < ctx->nb_surfaces; i++) {
1521 if ((res = nvenc_alloc_surface(avctx, i)) < 0)
1526 res2 = nvenc_pop_context(avctx);
1533 static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
1535 NvencContext *ctx = avctx->priv_data;
1536 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1537 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1539 NVENCSTATUS nv_status;
1540 uint32_t outSize = 0;
1541 char tmpHeader[256];
1542 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1543 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1545 payload.spsppsBuffer = tmpHeader;
1546 payload.inBufferSize = sizeof(tmpHeader);
1547 payload.outSPSPPSPayloadSize = &outSize;
1549 nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
1550 if (nv_status != NV_ENC_SUCCESS) {
1551 return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
1554 avctx->extradata_size = outSize;
1555 avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
1557 if (!avctx->extradata) {
1558 return AVERROR(ENOMEM);
1561 memcpy(avctx->extradata, tmpHeader, outSize);
1566 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
1568 NvencContext *ctx = avctx->priv_data;
1569 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1570 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1573 /* the encoder has to be flushed before it can be closed */
1574 if (ctx->nvencoder) {
1575 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
1576 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
1578 res = nvenc_push_context(avctx);
1582 p_nvenc->nvEncEncodePicture(ctx->nvencoder, ¶ms);
1585 av_fifo_freep(&ctx->timestamp_list);
1586 av_fifo_freep(&ctx->output_surface_ready_queue);
1587 av_fifo_freep(&ctx->output_surface_queue);
1588 av_fifo_freep(&ctx->unused_surface_queue);
1590 if (ctx->surfaces && (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11)) {
1591 for (i = 0; i < ctx->nb_registered_frames; i++) {
1592 if (ctx->registered_frames[i].mapped)
1593 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[i].in_map.mappedResource);
1594 if (ctx->registered_frames[i].regptr)
1595 p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1597 ctx->nb_registered_frames = 0;
1600 if (ctx->surfaces) {
1601 for (i = 0; i < ctx->nb_surfaces; ++i) {
1602 if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
1603 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
1604 av_frame_free(&ctx->surfaces[i].in_ref);
1605 p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
1608 av_freep(&ctx->surfaces);
1609 ctx->nb_surfaces = 0;
1611 av_frame_free(&ctx->frame);
1613 if (ctx->nvencoder) {
1614 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1616 res = nvenc_pop_context(avctx);
1620 ctx->nvencoder = NULL;
1622 if (ctx->cu_context_internal)
1623 CHECK_CU(dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal));
1624 ctx->cu_context = ctx->cu_context_internal = NULL;
1627 if (ctx->d3d11_device) {
1628 ID3D11Device_Release(ctx->d3d11_device);
1629 ctx->d3d11_device = NULL;
1633 nvenc_free_functions(&dl_fn->nvenc_dl);
1634 cuda_free_functions(&dl_fn->cuda_dl);
1636 dl_fn->nvenc_device_count = 0;
1638 av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
1643 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
1645 NvencContext *ctx = avctx->priv_data;
1648 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1649 AVHWFramesContext *frames_ctx;
1650 if (!avctx->hw_frames_ctx) {
1651 av_log(avctx, AV_LOG_ERROR,
1652 "hw_frames_ctx must be set when using GPU frames as input\n");
1653 return AVERROR(EINVAL);
1655 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1656 if (frames_ctx->format != avctx->pix_fmt) {
1657 av_log(avctx, AV_LOG_ERROR,
1658 "hw_frames_ctx must match the GPU frame type\n");
1659 return AVERROR(EINVAL);
1661 ctx->data_pix_fmt = frames_ctx->sw_format;
1663 ctx->data_pix_fmt = avctx->pix_fmt;
1666 ctx->frame = av_frame_alloc();
1668 return AVERROR(ENOMEM);
1670 if ((ret = nvenc_load_libraries(avctx)) < 0)
1673 if ((ret = nvenc_setup_device(avctx)) < 0)
1676 if ((ret = nvenc_setup_encoder(avctx)) < 0)
1679 if ((ret = nvenc_setup_surfaces(avctx)) < 0)
1682 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1683 if ((ret = nvenc_setup_extradata(avctx)) < 0)
1690 static NvencSurface *get_free_frame(NvencContext *ctx)
1692 NvencSurface *tmp_surf;
1694 if (!(av_fifo_size(ctx->unused_surface_queue) > 0))
1698 av_fifo_generic_read(ctx->unused_surface_queue, &tmp_surf, sizeof(tmp_surf), NULL);
1702 static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *nv_surface,
1703 NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params, const AVFrame *frame)
1705 int dst_linesize[4] = {
1706 lock_buffer_params->pitch,
1707 lock_buffer_params->pitch,
1708 lock_buffer_params->pitch,
1709 lock_buffer_params->pitch
1711 uint8_t *dst_data[4];
1714 if (frame->format == AV_PIX_FMT_YUV420P)
1715 dst_linesize[1] = dst_linesize[2] >>= 1;
1717 ret = av_image_fill_pointers(dst_data, frame->format, nv_surface->height,
1718 lock_buffer_params->bufferDataPtr, dst_linesize);
1722 if (frame->format == AV_PIX_FMT_YUV420P)
1723 FFSWAP(uint8_t*, dst_data[1], dst_data[2]);
1725 av_image_copy(dst_data, dst_linesize,
1726 (const uint8_t**)frame->data, frame->linesize, frame->format,
1727 avctx->width, avctx->height);
1732 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1734 NvencContext *ctx = avctx->priv_data;
1735 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1736 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1737 NVENCSTATUS nv_status;
1741 if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1742 for (first_round = 1; first_round >= 0; first_round--) {
1743 for (i = 0; i < ctx->nb_registered_frames; i++) {
1744 if (!ctx->registered_frames[i].mapped) {
1745 if (ctx->registered_frames[i].regptr) {
1748 nv_status = p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1749 if (nv_status != NV_ENC_SUCCESS)
1750 return nvenc_print_error(avctx, nv_status, "Failed unregistering unused input resource");
1751 ctx->registered_frames[i].ptr = NULL;
1752 ctx->registered_frames[i].regptr = NULL;
1759 return ctx->nb_registered_frames++;
1762 av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1763 return AVERROR(ENOMEM);
1766 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1768 NvencContext *ctx = avctx->priv_data;
1769 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1770 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1772 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frame->hw_frames_ctx->data;
1773 NV_ENC_REGISTER_RESOURCE reg;
1776 for (i = 0; i < ctx->nb_registered_frames; i++) {
1777 if (avctx->pix_fmt == AV_PIX_FMT_CUDA && ctx->registered_frames[i].ptr == frame->data[0])
1779 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])
1783 idx = nvenc_find_free_reg_resource(avctx);
1787 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1788 reg.width = frames_ctx->width;
1789 reg.height = frames_ctx->height;
1790 reg.pitch = frame->linesize[0];
1791 reg.resourceToRegister = frame->data[0];
1793 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1794 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1796 else if (avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1797 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX;
1798 reg.subResourceIndex = (intptr_t)frame->data[1];
1801 reg.bufferFormat = nvenc_map_buffer_format(frames_ctx->sw_format);
1802 if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1803 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1804 av_get_pix_fmt_name(frames_ctx->sw_format));
1805 return AVERROR(EINVAL);
1808 ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, ®);
1809 if (ret != NV_ENC_SUCCESS) {
1810 nvenc_print_error(avctx, ret, "Error registering an input resource");
1811 return AVERROR_UNKNOWN;
1814 ctx->registered_frames[idx].ptr = frame->data[0];
1815 ctx->registered_frames[idx].ptr_index = reg.subResourceIndex;
1816 ctx->registered_frames[idx].regptr = reg.registeredResource;
1820 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1821 NvencSurface *nvenc_frame)
1823 NvencContext *ctx = avctx->priv_data;
1824 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1825 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1828 NVENCSTATUS nv_status;
1830 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1831 int reg_idx = nvenc_register_frame(avctx, frame);
1833 av_log(avctx, AV_LOG_ERROR, "Could not register an input HW frame\n");
1837 res = av_frame_ref(nvenc_frame->in_ref, frame);
1841 if (!ctx->registered_frames[reg_idx].mapped) {
1842 ctx->registered_frames[reg_idx].in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1843 ctx->registered_frames[reg_idx].in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1844 nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &ctx->registered_frames[reg_idx].in_map);
1845 if (nv_status != NV_ENC_SUCCESS) {
1846 av_frame_unref(nvenc_frame->in_ref);
1847 return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
1851 ctx->registered_frames[reg_idx].mapped += 1;
1853 nvenc_frame->reg_idx = reg_idx;
1854 nvenc_frame->input_surface = ctx->registered_frames[reg_idx].in_map.mappedResource;
1855 nvenc_frame->format = ctx->registered_frames[reg_idx].in_map.mappedBufferFmt;
1856 nvenc_frame->pitch = frame->linesize[0];
1860 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1862 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1863 lockBufferParams.inputBuffer = nvenc_frame->input_surface;
1865 nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
1866 if (nv_status != NV_ENC_SUCCESS) {
1867 return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
1870 nvenc_frame->pitch = lockBufferParams.pitch;
1871 res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
1873 nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
1874 if (nv_status != NV_ENC_SUCCESS) {
1875 return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
1882 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1883 NV_ENC_PIC_PARAMS *params,
1884 NV_ENC_SEI_PAYLOAD *sei_data,
1887 NvencContext *ctx = avctx->priv_data;
1889 switch (avctx->codec->id) {
1890 case AV_CODEC_ID_H264:
1891 params->codecPicParams.h264PicParams.sliceMode =
1892 ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1893 params->codecPicParams.h264PicParams.sliceModeData =
1894 ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1895 if (sei_count > 0) {
1896 params->codecPicParams.h264PicParams.seiPayloadArray = sei_data;
1897 params->codecPicParams.h264PicParams.seiPayloadArrayCnt = sei_count;
1901 case AV_CODEC_ID_HEVC:
1902 params->codecPicParams.hevcPicParams.sliceMode =
1903 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1904 params->codecPicParams.hevcPicParams.sliceModeData =
1905 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1906 if (sei_count > 0) {
1907 params->codecPicParams.hevcPicParams.seiPayloadArray = sei_data;
1908 params->codecPicParams.hevcPicParams.seiPayloadArrayCnt = sei_count;
1915 static inline void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
1917 av_fifo_generic_write(queue, ×tamp, sizeof(timestamp), NULL);
1920 static inline int64_t timestamp_queue_dequeue(AVFifoBuffer* queue)
1922 int64_t timestamp = AV_NOPTS_VALUE;
1923 if (av_fifo_size(queue) > 0)
1924 av_fifo_generic_read(queue, ×tamp, sizeof(timestamp), NULL);
1929 static int nvenc_set_timestamp(AVCodecContext *avctx,
1930 NV_ENC_LOCK_BITSTREAM *params,
1933 NvencContext *ctx = avctx->priv_data;
1935 pkt->pts = params->outputTimeStamp;
1936 pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
1938 pkt->dts -= FFMAX(ctx->encode_config.frameIntervalP - 1, 0) * FFMAX(avctx->ticks_per_frame, 1);
1943 static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
1945 NvencContext *ctx = avctx->priv_data;
1946 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1947 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1949 uint32_t slice_mode_data;
1950 uint32_t *slice_offsets = NULL;
1951 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1952 NVENCSTATUS nv_status;
1955 enum AVPictureType pict_type;
1957 switch (avctx->codec->id) {
1958 case AV_CODEC_ID_H264:
1959 slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1961 case AV_CODEC_ID_H265:
1962 slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1965 av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
1966 res = AVERROR(EINVAL);
1969 slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
1971 if (!slice_offsets) {
1972 res = AVERROR(ENOMEM);
1976 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1978 lock_params.doNotWait = 0;
1979 lock_params.outputBitstream = tmpoutsurf->output_surface;
1980 lock_params.sliceOffsets = slice_offsets;
1982 nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
1983 if (nv_status != NV_ENC_SUCCESS) {
1984 res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
1988 res = ff_get_encode_buffer(avctx, pkt, lock_params.bitstreamSizeInBytes, 0);
1991 p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1995 memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1997 nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1998 if (nv_status != NV_ENC_SUCCESS) {
1999 res = nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
2004 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
2005 ctx->registered_frames[tmpoutsurf->reg_idx].mapped -= 1;
2006 if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped == 0) {
2007 nv_status = p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[tmpoutsurf->reg_idx].in_map.mappedResource);
2008 if (nv_status != NV_ENC_SUCCESS) {
2009 res = nvenc_print_error(avctx, nv_status, "Failed unmapping input resource");
2012 } else if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped < 0) {
2017 av_frame_unref(tmpoutsurf->in_ref);
2019 tmpoutsurf->input_surface = NULL;
2022 switch (lock_params.pictureType) {
2023 case NV_ENC_PIC_TYPE_IDR:
2024 pkt->flags |= AV_PKT_FLAG_KEY;
2025 case NV_ENC_PIC_TYPE_I:
2026 pict_type = AV_PICTURE_TYPE_I;
2028 case NV_ENC_PIC_TYPE_P:
2029 pict_type = AV_PICTURE_TYPE_P;
2031 case NV_ENC_PIC_TYPE_B:
2032 pict_type = AV_PICTURE_TYPE_B;
2034 case NV_ENC_PIC_TYPE_BI:
2035 pict_type = AV_PICTURE_TYPE_BI;
2038 av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
2039 av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
2040 res = AVERROR_EXTERNAL;
2044 ff_side_data_set_encoder_stats(pkt,
2045 (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
2047 res = nvenc_set_timestamp(avctx, &lock_params, pkt);
2051 av_free(slice_offsets);
2056 timestamp_queue_dequeue(ctx->timestamp_list);
2059 av_free(slice_offsets);
2064 static int output_ready(AVCodecContext *avctx, int flush)
2066 NvencContext *ctx = avctx->priv_data;
2067 int nb_ready, nb_pending;
2069 nb_ready = av_fifo_size(ctx->output_surface_ready_queue) / sizeof(NvencSurface*);
2070 nb_pending = av_fifo_size(ctx->output_surface_queue) / sizeof(NvencSurface*);
2072 return nb_ready > 0;
2073 return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
2076 static void reconfig_encoder(AVCodecContext *avctx, const AVFrame *frame)
2078 NvencContext *ctx = avctx->priv_data;
2079 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
2082 NV_ENC_RECONFIGURE_PARAMS params = { 0 };
2083 int needs_reconfig = 0;
2084 int needs_encode_config = 0;
2085 int reconfig_bitrate = 0, reconfig_dar = 0;
2088 params.version = NV_ENC_RECONFIGURE_PARAMS_VER;
2089 params.reInitEncodeParams = ctx->init_encode_params;
2091 compute_dar(avctx, &dw, &dh);
2092 if (dw != ctx->init_encode_params.darWidth || dh != ctx->init_encode_params.darHeight) {
2093 av_log(avctx, AV_LOG_VERBOSE,
2094 "aspect ratio change (DAR): %d:%d -> %d:%d\n",
2095 ctx->init_encode_params.darWidth,
2096 ctx->init_encode_params.darHeight, dw, dh);
2098 params.reInitEncodeParams.darHeight = dh;
2099 params.reInitEncodeParams.darWidth = dw;
2105 if (ctx->rc != NV_ENC_PARAMS_RC_CONSTQP && ctx->support_dyn_bitrate) {
2106 if (avctx->bit_rate > 0 && params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate != avctx->bit_rate) {
2107 av_log(avctx, AV_LOG_VERBOSE,
2108 "avg bitrate change: %d -> %d\n",
2109 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate,
2110 (uint32_t)avctx->bit_rate);
2112 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate = avctx->bit_rate;
2113 reconfig_bitrate = 1;
2116 if (avctx->rc_max_rate > 0 && ctx->encode_config.rcParams.maxBitRate != avctx->rc_max_rate) {
2117 av_log(avctx, AV_LOG_VERBOSE,
2118 "max bitrate change: %d -> %d\n",
2119 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate,
2120 (uint32_t)avctx->rc_max_rate);
2122 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate = avctx->rc_max_rate;
2123 reconfig_bitrate = 1;
2126 if (avctx->rc_buffer_size > 0 && ctx->encode_config.rcParams.vbvBufferSize != avctx->rc_buffer_size) {
2127 av_log(avctx, AV_LOG_VERBOSE,
2128 "vbv buffer size change: %d -> %d\n",
2129 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize,
2130 avctx->rc_buffer_size);
2132 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize = avctx->rc_buffer_size;
2133 reconfig_bitrate = 1;
2136 if (reconfig_bitrate) {
2137 params.resetEncoder = 1;
2138 params.forceIDR = 1;
2140 needs_encode_config = 1;
2145 if (!needs_encode_config)
2146 params.reInitEncodeParams.encodeConfig = NULL;
2148 if (needs_reconfig) {
2149 ret = p_nvenc->nvEncReconfigureEncoder(ctx->nvencoder, ¶ms);
2150 if (ret != NV_ENC_SUCCESS) {
2151 nvenc_print_error(avctx, ret, "failed to reconfigure nvenc");
2154 ctx->init_encode_params.darHeight = dh;
2155 ctx->init_encode_params.darWidth = dw;
2158 if (reconfig_bitrate) {
2159 ctx->encode_config.rcParams.averageBitRate = params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate;
2160 ctx->encode_config.rcParams.maxBitRate = params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate;
2161 ctx->encode_config.rcParams.vbvBufferSize = params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize;
2168 static int nvenc_send_frame(AVCodecContext *avctx, const AVFrame *frame)
2170 NVENCSTATUS nv_status;
2171 NvencSurface *tmp_out_surf, *in_surf;
2173 NV_ENC_SEI_PAYLOAD sei_data[8];
2177 NvencContext *ctx = avctx->priv_data;
2178 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
2179 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
2181 NV_ENC_PIC_PARAMS pic_params = { 0 };
2182 pic_params.version = NV_ENC_PIC_PARAMS_VER;
2184 if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
2185 return AVERROR(EINVAL);
2187 if (frame && frame->buf[0]) {
2188 in_surf = get_free_frame(ctx);
2190 return AVERROR(EAGAIN);
2192 res = nvenc_push_context(avctx);
2196 reconfig_encoder(avctx, frame);
2198 res = nvenc_upload_frame(avctx, frame, in_surf);
2200 res2 = nvenc_pop_context(avctx);
2207 pic_params.inputBuffer = in_surf->input_surface;
2208 pic_params.bufferFmt = in_surf->format;
2209 pic_params.inputWidth = in_surf->width;
2210 pic_params.inputHeight = in_surf->height;
2211 pic_params.inputPitch = in_surf->pitch;
2212 pic_params.outputBitstream = in_surf->output_surface;
2214 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
2215 if (frame->top_field_first)
2216 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
2218 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
2220 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
2223 if (ctx->forced_idr >= 0 && frame->pict_type == AV_PICTURE_TYPE_I) {
2224 pic_params.encodePicFlags =
2225 ctx->forced_idr ? NV_ENC_PIC_FLAG_FORCEIDR : NV_ENC_PIC_FLAG_FORCEINTRA;
2227 pic_params.encodePicFlags = 0;
2230 pic_params.inputTimeStamp = frame->pts;
2232 if (ctx->a53_cc && av_frame_get_side_data(frame, AV_FRAME_DATA_A53_CC)) {
2233 void *a53_data = NULL;
2234 size_t a53_size = 0;
2236 if (ff_alloc_a53_sei(frame, 0, (void**)&a53_data, &a53_size) < 0) {
2237 av_log(ctx, AV_LOG_ERROR, "Not enough memory for closed captions, skipping\n");
2241 sei_data[sei_count].payloadSize = (uint32_t)a53_size;
2242 sei_data[sei_count].payloadType = 4;
2243 sei_data[sei_count].payload = (uint8_t*)a53_data;
2248 if (ctx->s12m_tc && av_frame_get_side_data(frame, AV_FRAME_DATA_S12M_TIMECODE)) {
2249 void *tc_data = NULL;
2252 if (ff_alloc_timecode_sei(frame, avctx->framerate, 0, (void**)&tc_data, &tc_size) < 0) {
2253 av_log(ctx, AV_LOG_ERROR, "Not enough memory for timecode sei, skipping\n");
2257 sei_data[sei_count].payloadSize = (uint32_t)tc_size;
2258 sei_data[sei_count].payloadType = SEI_TYPE_TIME_CODE;
2259 sei_data[sei_count].payload = (uint8_t*)tc_data;
2264 nvenc_codec_specific_pic_params(avctx, &pic_params, sei_data, sei_count);
2266 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
2269 res = nvenc_push_context(avctx);
2273 nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
2275 for ( i = 0; i < sei_count; i++)
2276 av_freep(&sei_data[i].payload);
2278 res = nvenc_pop_context(avctx);
2282 if (nv_status != NV_ENC_SUCCESS &&
2283 nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
2284 return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
2286 if (frame && frame->buf[0]) {
2287 av_fifo_generic_write(ctx->output_surface_queue, &in_surf, sizeof(in_surf), NULL);
2288 timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
2291 /* all the pending buffers are now ready for output */
2292 if (nv_status == NV_ENC_SUCCESS) {
2293 while (av_fifo_size(ctx->output_surface_queue) > 0) {
2294 av_fifo_generic_read(ctx->output_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2295 av_fifo_generic_write(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2302 int ff_nvenc_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
2304 NvencSurface *tmp_out_surf;
2307 NvencContext *ctx = avctx->priv_data;
2309 AVFrame *frame = ctx->frame;
2311 if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
2312 return AVERROR(EINVAL);
2314 if (!frame->buf[0]) {
2315 res = ff_encode_get_frame(avctx, frame);
2316 if (res < 0 && res != AVERROR_EOF)
2320 res = nvenc_send_frame(avctx, frame);
2322 if (res != AVERROR(EAGAIN))
2325 av_frame_unref(frame);
2327 if (output_ready(avctx, avctx->internal->draining)) {
2328 av_fifo_generic_read(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2330 res = nvenc_push_context(avctx);
2334 res = process_output_surface(avctx, pkt, tmp_out_surf);
2336 res2 = nvenc_pop_context(avctx);
2343 av_fifo_generic_write(ctx->unused_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2344 } else if (avctx->internal->draining) {
2347 return AVERROR(EAGAIN);
2353 av_cold void ff_nvenc_encode_flush(AVCodecContext *avctx)
2355 NvencContext *ctx = avctx->priv_data;
2357 nvenc_send_frame(avctx, NULL);
2358 av_fifo_reset(ctx->timestamp_list);