2 * H.264/HEVC hardware encoding using nvidia nvenc
3 * Copyright (c) 2016 Timo Rothenpieler <timo@rothenpieler.org>
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 #include "libavutil/hwcontext_cuda.h"
27 #include "libavutil/hwcontext.h"
28 #include "libavutil/cuda_check.h"
29 #include "libavutil/imgutils.h"
30 #include "libavutil/avassert.h"
31 #include "libavutil/mem.h"
32 #include "libavutil/pixdesc.h"
35 #include "packet_internal.h"
37 #define CHECK_CU(x) FF_CUDA_CHECK_DL(avctx, dl_fn->cuda_dl, x)
39 #define NVENC_CAP 0x30
40 #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR || \
41 rc == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ || \
42 rc == NV_ENC_PARAMS_RC_CBR_HQ)
44 const enum AVPixelFormat ff_nvenc_pix_fmts[] = {
49 AV_PIX_FMT_P016, // Truncated to 10bits
50 AV_PIX_FMT_YUV444P16, // Truncated to 10bits
60 const AVCodecHWConfigInternal *ff_nvenc_hw_configs[] = {
61 HW_CONFIG_ENCODER_FRAMES(CUDA, CUDA),
62 HW_CONFIG_ENCODER_DEVICE(NONE, CUDA),
64 HW_CONFIG_ENCODER_FRAMES(D3D11, D3D11VA),
65 HW_CONFIG_ENCODER_DEVICE(NONE, D3D11VA),
70 #define IS_10BIT(pix_fmt) (pix_fmt == AV_PIX_FMT_P010 || \
71 pix_fmt == AV_PIX_FMT_P016 || \
72 pix_fmt == AV_PIX_FMT_YUV444P16)
74 #define IS_YUV444(pix_fmt) (pix_fmt == AV_PIX_FMT_YUV444P || \
75 pix_fmt == AV_PIX_FMT_YUV444P16)
82 { NV_ENC_SUCCESS, 0, "success" },
83 { NV_ENC_ERR_NO_ENCODE_DEVICE, AVERROR(ENOENT), "no encode device" },
84 { NV_ENC_ERR_UNSUPPORTED_DEVICE, AVERROR(ENOSYS), "unsupported device" },
85 { NV_ENC_ERR_INVALID_ENCODERDEVICE, AVERROR(EINVAL), "invalid encoder device" },
86 { NV_ENC_ERR_INVALID_DEVICE, AVERROR(EINVAL), "invalid device" },
87 { NV_ENC_ERR_DEVICE_NOT_EXIST, AVERROR(EIO), "device does not exist" },
88 { NV_ENC_ERR_INVALID_PTR, AVERROR(EFAULT), "invalid ptr" },
89 { NV_ENC_ERR_INVALID_EVENT, AVERROR(EINVAL), "invalid event" },
90 { NV_ENC_ERR_INVALID_PARAM, AVERROR(EINVAL), "invalid param" },
91 { NV_ENC_ERR_INVALID_CALL, AVERROR(EINVAL), "invalid call" },
92 { NV_ENC_ERR_OUT_OF_MEMORY, AVERROR(ENOMEM), "out of memory" },
93 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED, AVERROR(EINVAL), "encoder not initialized" },
94 { NV_ENC_ERR_UNSUPPORTED_PARAM, AVERROR(ENOSYS), "unsupported param" },
95 { NV_ENC_ERR_LOCK_BUSY, AVERROR(EAGAIN), "lock busy" },
96 { NV_ENC_ERR_NOT_ENOUGH_BUFFER, AVERROR_BUFFER_TOO_SMALL, "not enough buffer"},
97 { NV_ENC_ERR_INVALID_VERSION, AVERROR(EINVAL), "invalid version" },
98 { NV_ENC_ERR_MAP_FAILED, AVERROR(EIO), "map failed" },
99 { NV_ENC_ERR_NEED_MORE_INPUT, AVERROR(EAGAIN), "need more input" },
100 { NV_ENC_ERR_ENCODER_BUSY, AVERROR(EAGAIN), "encoder busy" },
101 { NV_ENC_ERR_EVENT_NOT_REGISTERD, AVERROR(EBADF), "event not registered" },
102 { NV_ENC_ERR_GENERIC, AVERROR_UNKNOWN, "generic error" },
103 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY, AVERROR(EINVAL), "incompatible client key" },
104 { NV_ENC_ERR_UNIMPLEMENTED, AVERROR(ENOSYS), "unimplemented" },
105 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO), "resource register failed" },
106 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED, AVERROR(EBADF), "resource not registered" },
107 { NV_ENC_ERR_RESOURCE_NOT_MAPPED, AVERROR(EBADF), "resource not mapped" },
110 static int nvenc_map_error(NVENCSTATUS err, const char **desc)
113 for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
114 if (nvenc_errors[i].nverr == err) {
116 *desc = nvenc_errors[i].desc;
117 return nvenc_errors[i].averr;
121 *desc = "unknown error";
122 return AVERROR_UNKNOWN;
125 static int nvenc_print_error(AVCodecContext *avctx, NVENCSTATUS err,
126 const char *error_string)
129 const char *details = "(no details)";
130 int ret = nvenc_map_error(err, &desc);
132 #ifdef NVENC_HAVE_GETLASTERRORSTRING
133 NvencContext *ctx = avctx->priv_data;
134 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
136 if (p_nvenc && ctx->nvencoder)
137 details = p_nvenc->nvEncGetLastErrorString(ctx->nvencoder);
140 av_log(avctx, AV_LOG_ERROR, "%s: %s (%d): %s\n", error_string, desc, err, details);
145 static void nvenc_print_driver_requirement(AVCodecContext *avctx, int level)
147 #if NVENCAPI_CHECK_VERSION(9, 2)
148 const char *minver = "(unknown)";
149 #elif NVENCAPI_CHECK_VERSION(9, 1)
150 # if defined(_WIN32) || defined(__CYGWIN__)
151 const char *minver = "436.15";
153 const char *minver = "435.21";
155 #elif NVENCAPI_CHECK_VERSION(9, 0)
156 # if defined(_WIN32) || defined(__CYGWIN__)
157 const char *minver = "418.81";
159 const char *minver = "418.30";
161 #elif NVENCAPI_CHECK_VERSION(8, 2)
162 # if defined(_WIN32) || defined(__CYGWIN__)
163 const char *minver = "397.93";
165 const char *minver = "396.24";
167 #elif NVENCAPI_CHECK_VERSION(8, 1)
168 # if defined(_WIN32) || defined(__CYGWIN__)
169 const char *minver = "390.77";
171 const char *minver = "390.25";
174 # if defined(_WIN32) || defined(__CYGWIN__)
175 const char *minver = "378.66";
177 const char *minver = "378.13";
180 av_log(avctx, level, "The minimum required Nvidia driver for nvenc is %s or newer\n", minver);
183 static av_cold int nvenc_load_libraries(AVCodecContext *avctx)
185 NvencContext *ctx = avctx->priv_data;
186 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
188 uint32_t nvenc_max_ver;
191 ret = cuda_load_functions(&dl_fn->cuda_dl, avctx);
195 ret = nvenc_load_functions(&dl_fn->nvenc_dl, avctx);
197 nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
201 err = dl_fn->nvenc_dl->NvEncodeAPIGetMaxSupportedVersion(&nvenc_max_ver);
202 if (err != NV_ENC_SUCCESS)
203 return nvenc_print_error(avctx, err, "Failed to query nvenc max version");
205 av_log(avctx, AV_LOG_VERBOSE, "Loaded Nvenc version %d.%d\n", nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
207 if ((NVENCAPI_MAJOR_VERSION << 4 | NVENCAPI_MINOR_VERSION) > nvenc_max_ver) {
208 av_log(avctx, AV_LOG_ERROR, "Driver does not support the required nvenc API version. "
209 "Required: %d.%d Found: %d.%d\n",
210 NVENCAPI_MAJOR_VERSION, NVENCAPI_MINOR_VERSION,
211 nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
212 nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
213 return AVERROR(ENOSYS);
216 dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
218 err = dl_fn->nvenc_dl->NvEncodeAPICreateInstance(&dl_fn->nvenc_funcs);
219 if (err != NV_ENC_SUCCESS)
220 return nvenc_print_error(avctx, err, "Failed to create nvenc instance");
222 av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
227 static int nvenc_push_context(AVCodecContext *avctx)
229 NvencContext *ctx = avctx->priv_data;
230 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
232 if (ctx->d3d11_device)
235 return CHECK_CU(dl_fn->cuda_dl->cuCtxPushCurrent(ctx->cu_context));
238 static int nvenc_pop_context(AVCodecContext *avctx)
240 NvencContext *ctx = avctx->priv_data;
241 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
244 if (ctx->d3d11_device)
247 return CHECK_CU(dl_fn->cuda_dl->cuCtxPopCurrent(&dummy));
250 static av_cold int nvenc_open_session(AVCodecContext *avctx)
252 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
253 NvencContext *ctx = avctx->priv_data;
254 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
257 params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
258 params.apiVersion = NVENCAPI_VERSION;
259 if (ctx->d3d11_device) {
260 params.device = ctx->d3d11_device;
261 params.deviceType = NV_ENC_DEVICE_TYPE_DIRECTX;
263 params.device = ctx->cu_context;
264 params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
267 ret = p_nvenc->nvEncOpenEncodeSessionEx(¶ms, &ctx->nvencoder);
268 if (ret != NV_ENC_SUCCESS) {
269 ctx->nvencoder = NULL;
270 return nvenc_print_error(avctx, ret, "OpenEncodeSessionEx failed");
276 static int nvenc_check_codec_support(AVCodecContext *avctx)
278 NvencContext *ctx = avctx->priv_data;
279 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
280 int i, ret, count = 0;
283 ret = p_nvenc->nvEncGetEncodeGUIDCount(ctx->nvencoder, &count);
285 if (ret != NV_ENC_SUCCESS || !count)
286 return AVERROR(ENOSYS);
288 guids = av_malloc(count * sizeof(GUID));
290 return AVERROR(ENOMEM);
292 ret = p_nvenc->nvEncGetEncodeGUIDs(ctx->nvencoder, guids, count, &count);
293 if (ret != NV_ENC_SUCCESS) {
294 ret = AVERROR(ENOSYS);
298 ret = AVERROR(ENOSYS);
299 for (i = 0; i < count; i++) {
300 if (!memcmp(&guids[i], &ctx->init_encode_params.encodeGUID, sizeof(*guids))) {
312 static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
314 NvencContext *ctx = avctx->priv_data;
315 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
316 NV_ENC_CAPS_PARAM params = { 0 };
319 params.version = NV_ENC_CAPS_PARAM_VER;
320 params.capsToQuery = cap;
322 ret = p_nvenc->nvEncGetEncodeCaps(ctx->nvencoder, ctx->init_encode_params.encodeGUID, ¶ms, &val);
324 if (ret == NV_ENC_SUCCESS)
329 static int nvenc_check_capabilities(AVCodecContext *avctx)
331 NvencContext *ctx = avctx->priv_data;
334 ret = nvenc_check_codec_support(avctx);
336 av_log(avctx, AV_LOG_WARNING, "Codec not supported\n");
340 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
341 if (IS_YUV444(ctx->data_pix_fmt) && ret <= 0) {
342 av_log(avctx, AV_LOG_WARNING, "YUV444P not supported\n");
343 return AVERROR(ENOSYS);
346 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOSSLESS_ENCODE);
347 if (ctx->preset >= PRESET_LOSSLESS_DEFAULT && ret <= 0) {
348 av_log(avctx, AV_LOG_WARNING, "Lossless encoding not supported\n");
349 return AVERROR(ENOSYS);
352 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
353 if (ret < avctx->width) {
354 av_log(avctx, AV_LOG_WARNING, "Width %d exceeds %d\n",
356 return AVERROR(ENOSYS);
359 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
360 if (ret < avctx->height) {
361 av_log(avctx, AV_LOG_WARNING, "Height %d exceeds %d\n",
363 return AVERROR(ENOSYS);
366 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
367 if (ret < avctx->max_b_frames) {
368 av_log(avctx, AV_LOG_WARNING, "Max B-frames %d exceed %d\n",
369 avctx->max_b_frames, ret);
371 return AVERROR(ENOSYS);
374 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_FIELD_ENCODING);
375 if (ret < 1 && avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
376 av_log(avctx, AV_LOG_WARNING,
377 "Interlaced encoding is not supported. Supported level: %d\n",
379 return AVERROR(ENOSYS);
382 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_10BIT_ENCODE);
383 if (IS_10BIT(ctx->data_pix_fmt) && ret <= 0) {
384 av_log(avctx, AV_LOG_WARNING, "10 bit encode not supported\n");
385 return AVERROR(ENOSYS);
388 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOOKAHEAD);
389 if (ctx->rc_lookahead > 0 && ret <= 0) {
390 av_log(avctx, AV_LOG_WARNING, "RC lookahead not supported\n");
391 return AVERROR(ENOSYS);
394 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_TEMPORAL_AQ);
395 if (ctx->temporal_aq > 0 && ret <= 0) {
396 av_log(avctx, AV_LOG_WARNING, "Temporal AQ not supported\n");
397 return AVERROR(ENOSYS);
400 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_WEIGHTED_PREDICTION);
401 if (ctx->weighted_pred > 0 && ret <= 0) {
402 av_log (avctx, AV_LOG_WARNING, "Weighted Prediction not supported\n");
403 return AVERROR(ENOSYS);
406 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_CABAC);
407 if (ctx->coder == NV_ENC_H264_ENTROPY_CODING_MODE_CABAC && ret <= 0) {
408 av_log(avctx, AV_LOG_WARNING, "CABAC entropy coding not supported\n");
409 return AVERROR(ENOSYS);
412 #ifdef NVENC_HAVE_BFRAME_REF_MODE
413 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_BFRAME_REF_MODE);
414 if (ctx->b_ref_mode == NV_ENC_BFRAME_REF_MODE_EACH && ret != 1) {
415 av_log(avctx, AV_LOG_WARNING, "Each B frame as reference is not supported\n");
416 return AVERROR(ENOSYS);
417 } else if (ctx->b_ref_mode != NV_ENC_BFRAME_REF_MODE_DISABLED && ret == 0) {
418 av_log(avctx, AV_LOG_WARNING, "B frames as references are not supported\n");
419 return AVERROR(ENOSYS);
422 if (ctx->b_ref_mode != 0) {
423 av_log(avctx, AV_LOG_WARNING, "B frames as references need SDK 8.1 at build time\n");
424 return AVERROR(ENOSYS);
428 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
429 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_MULTIPLE_REF_FRAMES);
430 if(avctx->refs != NV_ENC_NUM_REF_FRAMES_AUTOSELECT && ret <= 0) {
431 av_log(avctx, AV_LOG_WARNING, "Multiple reference frames are not supported by the device\n");
432 return AVERROR(ENOSYS);
435 if(avctx->refs != 0) {
436 av_log(avctx, AV_LOG_WARNING, "Multiple reference frames need SDK 9.1 at build time\n");
437 return AVERROR(ENOSYS);
441 ctx->support_dyn_bitrate = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_DYN_BITRATE_CHANGE);
446 static av_cold int nvenc_check_device(AVCodecContext *avctx, int idx)
448 NvencContext *ctx = avctx->priv_data;
449 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
450 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
451 char name[128] = { 0};
452 int major, minor, ret;
454 int loglevel = AV_LOG_VERBOSE;
456 if (ctx->device == LIST_DEVICES)
457 loglevel = AV_LOG_INFO;
459 ret = CHECK_CU(dl_fn->cuda_dl->cuDeviceGet(&cu_device, idx));
463 ret = CHECK_CU(dl_fn->cuda_dl->cuDeviceGetName(name, sizeof(name), cu_device));
467 ret = CHECK_CU(dl_fn->cuda_dl->cuDeviceComputeCapability(&major, &minor, cu_device));
471 av_log(avctx, loglevel, "[ GPU #%d - < %s > has Compute SM %d.%d ]\n", idx, name, major, minor);
472 if (((major << 4) | minor) < NVENC_CAP) {
473 av_log(avctx, loglevel, "does not support NVENC\n");
477 if (ctx->device != idx && ctx->device != ANY_DEVICE)
480 ret = CHECK_CU(dl_fn->cuda_dl->cuCtxCreate(&ctx->cu_context_internal, 0, cu_device));
484 ctx->cu_context = ctx->cu_context_internal;
485 ctx->cu_stream = NULL;
487 if ((ret = nvenc_pop_context(avctx)) < 0)
490 if ((ret = nvenc_open_session(avctx)) < 0)
493 if ((ret = nvenc_check_capabilities(avctx)) < 0)
496 av_log(avctx, loglevel, "supports NVENC\n");
498 dl_fn->nvenc_device_count++;
500 if (ctx->device == idx || ctx->device == ANY_DEVICE)
504 if ((ret = nvenc_push_context(avctx)) < 0)
507 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
508 ctx->nvencoder = NULL;
510 if ((ret = nvenc_pop_context(avctx)) < 0)
514 CHECK_CU(dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal));
515 ctx->cu_context_internal = NULL;
518 return AVERROR(ENOSYS);
521 static av_cold int nvenc_setup_device(AVCodecContext *avctx)
523 NvencContext *ctx = avctx->priv_data;
524 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
526 switch (avctx->codec->id) {
527 case AV_CODEC_ID_H264:
528 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
530 case AV_CODEC_ID_HEVC:
531 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
537 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11 || avctx->hw_frames_ctx || avctx->hw_device_ctx) {
538 AVHWFramesContext *frames_ctx;
539 AVHWDeviceContext *hwdev_ctx;
540 AVCUDADeviceContext *cuda_device_hwctx = NULL;
542 AVD3D11VADeviceContext *d3d11_device_hwctx = NULL;
546 if (avctx->hw_frames_ctx) {
547 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
548 if (frames_ctx->format == AV_PIX_FMT_CUDA)
549 cuda_device_hwctx = frames_ctx->device_ctx->hwctx;
551 else if (frames_ctx->format == AV_PIX_FMT_D3D11)
552 d3d11_device_hwctx = frames_ctx->device_ctx->hwctx;
555 return AVERROR(EINVAL);
556 } else if (avctx->hw_device_ctx) {
557 hwdev_ctx = (AVHWDeviceContext*)avctx->hw_device_ctx->data;
558 if (hwdev_ctx->type == AV_HWDEVICE_TYPE_CUDA)
559 cuda_device_hwctx = hwdev_ctx->hwctx;
561 else if (hwdev_ctx->type == AV_HWDEVICE_TYPE_D3D11VA)
562 d3d11_device_hwctx = hwdev_ctx->hwctx;
565 return AVERROR(EINVAL);
567 return AVERROR(EINVAL);
570 if (cuda_device_hwctx) {
571 ctx->cu_context = cuda_device_hwctx->cuda_ctx;
572 ctx->cu_stream = cuda_device_hwctx->stream;
575 else if (d3d11_device_hwctx) {
576 ctx->d3d11_device = d3d11_device_hwctx->device;
577 ID3D11Device_AddRef(ctx->d3d11_device);
581 ret = nvenc_open_session(avctx);
585 ret = nvenc_check_capabilities(avctx);
587 av_log(avctx, AV_LOG_FATAL, "Provided device doesn't support required NVENC features\n");
591 int i, nb_devices = 0;
593 if (CHECK_CU(dl_fn->cuda_dl->cuInit(0)) < 0)
594 return AVERROR_UNKNOWN;
596 if (CHECK_CU(dl_fn->cuda_dl->cuDeviceGetCount(&nb_devices)) < 0)
597 return AVERROR_UNKNOWN;
600 av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
601 return AVERROR_EXTERNAL;
604 av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", nb_devices);
606 dl_fn->nvenc_device_count = 0;
607 for (i = 0; i < nb_devices; ++i) {
608 if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
612 if (ctx->device == LIST_DEVICES)
615 if (!dl_fn->nvenc_device_count) {
616 av_log(avctx, AV_LOG_FATAL, "No capable devices found\n");
617 return AVERROR_EXTERNAL;
620 av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->device, nb_devices);
621 return AVERROR(EINVAL);
627 typedef struct GUIDTuple {
632 #define PRESET_ALIAS(alias, name, ...) \
633 [PRESET_ ## alias] = { NV_ENC_PRESET_ ## name ## _GUID, __VA_ARGS__ }
635 #define PRESET(name, ...) PRESET_ALIAS(name, name, __VA_ARGS__)
637 static void nvenc_map_preset(NvencContext *ctx)
639 GUIDTuple presets[] = {
644 PRESET_ALIAS(SLOW, HQ, NVENC_TWO_PASSES),
645 PRESET_ALIAS(MEDIUM, HQ, NVENC_ONE_PASS),
646 PRESET_ALIAS(FAST, HP, NVENC_ONE_PASS),
647 PRESET(LOW_LATENCY_DEFAULT, NVENC_LOWLATENCY),
648 PRESET(LOW_LATENCY_HP, NVENC_LOWLATENCY),
649 PRESET(LOW_LATENCY_HQ, NVENC_LOWLATENCY),
650 PRESET(LOSSLESS_DEFAULT, NVENC_LOSSLESS),
651 PRESET(LOSSLESS_HP, NVENC_LOSSLESS),
654 GUIDTuple *t = &presets[ctx->preset];
656 ctx->init_encode_params.presetGUID = t->guid;
657 ctx->flags = t->flags;
663 static av_cold void set_constqp(AVCodecContext *avctx)
665 NvencContext *ctx = avctx->priv_data;
666 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
668 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
670 if (ctx->init_qp_p >= 0) {
671 rc->constQP.qpInterP = ctx->init_qp_p;
672 if (ctx->init_qp_i >= 0 && ctx->init_qp_b >= 0) {
673 rc->constQP.qpIntra = ctx->init_qp_i;
674 rc->constQP.qpInterB = ctx->init_qp_b;
675 } else if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
676 rc->constQP.qpIntra = av_clip(
677 rc->constQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
678 rc->constQP.qpInterB = av_clip(
679 rc->constQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
681 rc->constQP.qpIntra = rc->constQP.qpInterP;
682 rc->constQP.qpInterB = rc->constQP.qpInterP;
684 } else if (ctx->cqp >= 0) {
685 rc->constQP.qpInterP = rc->constQP.qpInterB = rc->constQP.qpIntra = ctx->cqp;
686 if (avctx->b_quant_factor != 0.0)
687 rc->constQP.qpInterB = av_clip(ctx->cqp * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
688 if (avctx->i_quant_factor != 0.0)
689 rc->constQP.qpIntra = av_clip(ctx->cqp * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
696 static av_cold void set_vbr(AVCodecContext *avctx)
698 NvencContext *ctx = avctx->priv_data;
699 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
702 if (avctx->qmin >= 0 && avctx->qmax >= 0) {
706 rc->minQP.qpInterB = avctx->qmin;
707 rc->minQP.qpInterP = avctx->qmin;
708 rc->minQP.qpIntra = avctx->qmin;
710 rc->maxQP.qpInterB = avctx->qmax;
711 rc->maxQP.qpInterP = avctx->qmax;
712 rc->maxQP.qpIntra = avctx->qmax;
714 qp_inter_p = (avctx->qmax + 3 * avctx->qmin) / 4; // biased towards Qmin
715 } else if (avctx->qmin >= 0) {
718 rc->minQP.qpInterB = avctx->qmin;
719 rc->minQP.qpInterP = avctx->qmin;
720 rc->minQP.qpIntra = avctx->qmin;
722 qp_inter_p = avctx->qmin;
724 qp_inter_p = 26; // default to 26
727 rc->enableInitialRCQP = 1;
729 if (ctx->init_qp_p < 0) {
730 rc->initialRCQP.qpInterP = qp_inter_p;
732 rc->initialRCQP.qpInterP = ctx->init_qp_p;
735 if (ctx->init_qp_i < 0) {
736 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
737 rc->initialRCQP.qpIntra = av_clip(
738 rc->initialRCQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
740 rc->initialRCQP.qpIntra = rc->initialRCQP.qpInterP;
743 rc->initialRCQP.qpIntra = ctx->init_qp_i;
746 if (ctx->init_qp_b < 0) {
747 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
748 rc->initialRCQP.qpInterB = av_clip(
749 rc->initialRCQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
751 rc->initialRCQP.qpInterB = rc->initialRCQP.qpInterP;
754 rc->initialRCQP.qpInterB = ctx->init_qp_b;
758 static av_cold void set_lossless(AVCodecContext *avctx)
760 NvencContext *ctx = avctx->priv_data;
761 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
763 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
764 rc->constQP.qpInterB = 0;
765 rc->constQP.qpInterP = 0;
766 rc->constQP.qpIntra = 0;
772 static void nvenc_override_rate_control(AVCodecContext *avctx)
774 NvencContext *ctx = avctx->priv_data;
775 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
778 case NV_ENC_PARAMS_RC_CONSTQP:
781 case NV_ENC_PARAMS_RC_VBR_MINQP:
782 if (avctx->qmin < 0) {
783 av_log(avctx, AV_LOG_WARNING,
784 "The variable bitrate rate-control requires "
785 "the 'qmin' option set.\n");
790 case NV_ENC_PARAMS_RC_VBR_HQ:
791 case NV_ENC_PARAMS_RC_VBR:
794 case NV_ENC_PARAMS_RC_CBR:
795 case NV_ENC_PARAMS_RC_CBR_HQ:
796 case NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ:
800 rc->rateControlMode = ctx->rc;
803 static av_cold int nvenc_recalc_surfaces(AVCodecContext *avctx)
805 NvencContext *ctx = avctx->priv_data;
806 // default minimum of 4 surfaces
807 // multiply by 2 for number of NVENCs on gpu (hardcode to 2)
808 // another multiply by 2 to avoid blocking next PBB group
809 int nb_surfaces = FFMAX(4, ctx->encode_config.frameIntervalP * 2 * 2);
812 if (ctx->rc_lookahead > 0) {
813 // +1 is to account for lkd_bound calculation later
814 // +4 is to allow sufficient pipelining with lookahead
815 nb_surfaces = FFMAX(1, FFMAX(nb_surfaces, ctx->rc_lookahead + ctx->encode_config.frameIntervalP + 1 + 4));
816 if (nb_surfaces > ctx->nb_surfaces && ctx->nb_surfaces > 0)
818 av_log(avctx, AV_LOG_WARNING,
819 "Defined rc_lookahead requires more surfaces, "
820 "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
822 ctx->nb_surfaces = FFMAX(nb_surfaces, ctx->nb_surfaces);
824 if (ctx->encode_config.frameIntervalP > 1 && ctx->nb_surfaces < nb_surfaces && ctx->nb_surfaces > 0)
826 av_log(avctx, AV_LOG_WARNING,
827 "Defined b-frame requires more surfaces, "
828 "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
829 ctx->nb_surfaces = FFMAX(ctx->nb_surfaces, nb_surfaces);
831 else if (ctx->nb_surfaces <= 0)
832 ctx->nb_surfaces = nb_surfaces;
833 // otherwise use user specified value
836 ctx->nb_surfaces = FFMAX(1, FFMIN(MAX_REGISTERED_FRAMES, ctx->nb_surfaces));
837 ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
842 static av_cold void nvenc_setup_rate_control(AVCodecContext *avctx)
844 NvencContext *ctx = avctx->priv_data;
846 if (avctx->global_quality > 0)
847 av_log(avctx, AV_LOG_WARNING, "Using global_quality with nvenc is deprecated. Use qp instead.\n");
849 if (ctx->cqp < 0 && avctx->global_quality > 0)
850 ctx->cqp = avctx->global_quality;
852 if (avctx->bit_rate > 0) {
853 ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
854 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
855 ctx->encode_config.rcParams.maxBitRate = ctx->encode_config.rcParams.averageBitRate;
858 if (avctx->rc_max_rate > 0)
859 ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
862 if (ctx->flags & NVENC_ONE_PASS)
864 if (ctx->flags & NVENC_TWO_PASSES)
867 if (ctx->twopass < 0)
868 ctx->twopass = (ctx->flags & NVENC_LOWLATENCY) != 0;
872 ctx->rc = NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ;
874 ctx->rc = NV_ENC_PARAMS_RC_CBR;
876 } else if (ctx->cqp >= 0) {
877 ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
878 } else if (ctx->twopass) {
879 ctx->rc = NV_ENC_PARAMS_RC_VBR_HQ;
880 } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
881 ctx->rc = NV_ENC_PARAMS_RC_VBR_MINQP;
885 if (ctx->rc >= 0 && ctx->rc & RC_MODE_DEPRECATED) {
886 av_log(avctx, AV_LOG_WARNING, "Specified rc mode is deprecated.\n");
887 av_log(avctx, AV_LOG_WARNING, "\tll_2pass_quality -> cbr_ld_hq\n");
888 av_log(avctx, AV_LOG_WARNING, "\tll_2pass_size -> cbr_hq\n");
889 av_log(avctx, AV_LOG_WARNING, "\tvbr_2pass -> vbr_hq\n");
890 av_log(avctx, AV_LOG_WARNING, "\tvbr_minqp -> (no replacement)\n");
892 ctx->rc &= ~RC_MODE_DEPRECATED;
895 if (ctx->flags & NVENC_LOSSLESS) {
897 } else if (ctx->rc >= 0) {
898 nvenc_override_rate_control(avctx);
900 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
904 if (avctx->rc_buffer_size > 0) {
905 ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
906 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
907 avctx->rc_buffer_size = ctx->encode_config.rcParams.vbvBufferSize = 2 * ctx->encode_config.rcParams.averageBitRate;
911 ctx->encode_config.rcParams.enableAQ = 1;
912 ctx->encode_config.rcParams.aqStrength = ctx->aq_strength;
913 av_log(avctx, AV_LOG_VERBOSE, "AQ enabled.\n");
916 if (ctx->temporal_aq) {
917 ctx->encode_config.rcParams.enableTemporalAQ = 1;
918 av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ enabled.\n");
921 if (ctx->rc_lookahead > 0) {
922 int lkd_bound = FFMIN(ctx->nb_surfaces, ctx->async_depth) -
923 ctx->encode_config.frameIntervalP - 4;
926 av_log(avctx, AV_LOG_WARNING,
927 "Lookahead not enabled. Increase buffer delay (-delay).\n");
929 ctx->encode_config.rcParams.enableLookahead = 1;
930 ctx->encode_config.rcParams.lookaheadDepth = av_clip(ctx->rc_lookahead, 0, lkd_bound);
931 ctx->encode_config.rcParams.disableIadapt = ctx->no_scenecut;
932 ctx->encode_config.rcParams.disableBadapt = !ctx->b_adapt;
933 av_log(avctx, AV_LOG_VERBOSE,
934 "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",
935 ctx->encode_config.rcParams.lookaheadDepth,
936 ctx->encode_config.rcParams.disableIadapt ? "disabled" : "enabled",
937 ctx->encode_config.rcParams.disableBadapt ? "disabled" : "enabled");
941 if (ctx->strict_gop) {
942 ctx->encode_config.rcParams.strictGOPTarget = 1;
943 av_log(avctx, AV_LOG_VERBOSE, "Strict GOP target enabled.\n");
947 ctx->encode_config.rcParams.enableNonRefP = 1;
949 if (ctx->zerolatency)
950 ctx->encode_config.rcParams.zeroReorderDelay = 1;
953 //convert from float to fixed point 8.8
954 int tmp_quality = (int)(ctx->quality * 256.0f);
955 ctx->encode_config.rcParams.targetQuality = (uint8_t)(tmp_quality >> 8);
956 ctx->encode_config.rcParams.targetQualityLSB = (uint8_t)(tmp_quality & 0xff);
958 av_log(avctx, AV_LOG_VERBOSE, "CQ(%d) mode enabled.\n", tmp_quality);
960 //CQ mode shall discard avg bitrate & honor max bitrate;
961 ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate = 0;
962 ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
966 static av_cold int nvenc_setup_h264_config(AVCodecContext *avctx)
968 NvencContext *ctx = avctx->priv_data;
969 NV_ENC_CONFIG *cc = &ctx->encode_config;
970 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
971 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
973 vui->colourMatrix = avctx->colorspace;
974 vui->colourPrimaries = avctx->color_primaries;
975 vui->transferCharacteristics = avctx->color_trc;
976 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
977 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
979 vui->colourDescriptionPresentFlag =
980 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
982 vui->videoSignalTypePresentFlag =
983 (vui->colourDescriptionPresentFlag
984 || vui->videoFormat != 5
985 || vui->videoFullRangeFlag != 0);
988 h264->sliceModeData = 1;
990 h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
991 h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
992 h264->outputAUD = ctx->aud;
994 if (ctx->dpb_size >= 0) {
995 /* 0 means "let the hardware decide" */
996 h264->maxNumRefFrames = ctx->dpb_size;
998 if (avctx->gop_size >= 0) {
999 h264->idrPeriod = cc->gopLength;
1002 if (IS_CBR(cc->rcParams.rateControlMode)) {
1003 h264->outputBufferingPeriodSEI = 1;
1006 h264->outputPictureTimingSEI = 1;
1008 if (cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ ||
1009 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_HQ ||
1010 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_VBR_HQ) {
1011 h264->adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
1012 h264->fmoMode = NV_ENC_H264_FMO_DISABLE;
1015 if (ctx->flags & NVENC_LOSSLESS) {
1016 h264->qpPrimeYZeroTransformBypassFlag = 1;
1018 switch(ctx->profile) {
1019 case NV_ENC_H264_PROFILE_BASELINE:
1020 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
1021 avctx->profile = FF_PROFILE_H264_BASELINE;
1023 case NV_ENC_H264_PROFILE_MAIN:
1024 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
1025 avctx->profile = FF_PROFILE_H264_MAIN;
1027 case NV_ENC_H264_PROFILE_HIGH:
1028 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
1029 avctx->profile = FF_PROFILE_H264_HIGH;
1031 case NV_ENC_H264_PROFILE_HIGH_444P:
1032 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1033 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
1038 // force setting profile as high444p if input is AV_PIX_FMT_YUV444P
1039 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P) {
1040 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1041 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
1044 h264->chromaFormatIDC = avctx->profile == FF_PROFILE_H264_HIGH_444_PREDICTIVE ? 3 : 1;
1046 h264->level = ctx->level;
1048 if (ctx->coder >= 0)
1049 h264->entropyCodingMode = ctx->coder;
1051 #ifdef NVENC_HAVE_BFRAME_REF_MODE
1052 h264->useBFramesAsRef = ctx->b_ref_mode;
1055 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
1056 h264->numRefL0 = avctx->refs;
1057 h264->numRefL1 = avctx->refs;
1063 static av_cold int nvenc_setup_hevc_config(AVCodecContext *avctx)
1065 NvencContext *ctx = avctx->priv_data;
1066 NV_ENC_CONFIG *cc = &ctx->encode_config;
1067 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
1068 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
1070 vui->colourMatrix = avctx->colorspace;
1071 vui->colourPrimaries = avctx->color_primaries;
1072 vui->transferCharacteristics = avctx->color_trc;
1073 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
1074 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
1076 vui->colourDescriptionPresentFlag =
1077 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
1079 vui->videoSignalTypePresentFlag =
1080 (vui->colourDescriptionPresentFlag
1081 || vui->videoFormat != 5
1082 || vui->videoFullRangeFlag != 0);
1084 hevc->sliceMode = 3;
1085 hevc->sliceModeData = 1;
1087 hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
1088 hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
1089 hevc->outputAUD = ctx->aud;
1091 if (ctx->dpb_size >= 0) {
1092 /* 0 means "let the hardware decide" */
1093 hevc->maxNumRefFramesInDPB = ctx->dpb_size;
1095 if (avctx->gop_size >= 0) {
1096 hevc->idrPeriod = cc->gopLength;
1099 if (IS_CBR(cc->rcParams.rateControlMode)) {
1100 hevc->outputBufferingPeriodSEI = 1;
1103 hevc->outputPictureTimingSEI = 1;
1105 switch (ctx->profile) {
1106 case NV_ENC_HEVC_PROFILE_MAIN:
1107 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
1108 avctx->profile = FF_PROFILE_HEVC_MAIN;
1110 case NV_ENC_HEVC_PROFILE_MAIN_10:
1111 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1112 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
1114 case NV_ENC_HEVC_PROFILE_REXT:
1115 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1116 avctx->profile = FF_PROFILE_HEVC_REXT;
1120 // force setting profile as main10 if input is 10 bit
1121 if (IS_10BIT(ctx->data_pix_fmt)) {
1122 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1123 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
1126 // force setting profile as rext if input is yuv444
1127 if (IS_YUV444(ctx->data_pix_fmt)) {
1128 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1129 avctx->profile = FF_PROFILE_HEVC_REXT;
1132 hevc->chromaFormatIDC = IS_YUV444(ctx->data_pix_fmt) ? 3 : 1;
1134 hevc->pixelBitDepthMinus8 = IS_10BIT(ctx->data_pix_fmt) ? 2 : 0;
1136 hevc->level = ctx->level;
1138 hevc->tier = ctx->tier;
1140 #ifdef NVENC_HAVE_HEVC_BFRAME_REF_MODE
1141 hevc->useBFramesAsRef = ctx->b_ref_mode;
1144 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
1145 hevc->numRefL0 = avctx->refs;
1146 hevc->numRefL1 = avctx->refs;
1152 static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx)
1154 switch (avctx->codec->id) {
1155 case AV_CODEC_ID_H264:
1156 return nvenc_setup_h264_config(avctx);
1157 case AV_CODEC_ID_HEVC:
1158 return nvenc_setup_hevc_config(avctx);
1159 /* Earlier switch/case will return if unknown codec is passed. */
1165 static void compute_dar(AVCodecContext *avctx, int *dw, int *dh) {
1171 if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0) {
1172 sw *= avctx->sample_aspect_ratio.num;
1173 sh *= avctx->sample_aspect_ratio.den;
1176 av_reduce(dw, dh, sw, sh, 1024 * 1024);
1179 static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
1181 NvencContext *ctx = avctx->priv_data;
1182 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1183 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1185 NV_ENC_PRESET_CONFIG preset_config = { 0 };
1186 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
1187 AVCPBProperties *cpb_props;
1191 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1192 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
1194 ctx->init_encode_params.encodeHeight = avctx->height;
1195 ctx->init_encode_params.encodeWidth = avctx->width;
1197 ctx->init_encode_params.encodeConfig = &ctx->encode_config;
1199 nvenc_map_preset(ctx);
1201 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
1202 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
1204 nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder,
1205 ctx->init_encode_params.encodeGUID,
1206 ctx->init_encode_params.presetGUID,
1208 if (nv_status != NV_ENC_SUCCESS)
1209 return nvenc_print_error(avctx, nv_status, "Cannot get the preset configuration");
1211 memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
1213 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1215 compute_dar(avctx, &dw, &dh);
1216 ctx->init_encode_params.darHeight = dh;
1217 ctx->init_encode_params.darWidth = dw;
1219 if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {
1220 ctx->init_encode_params.frameRateNum = avctx->framerate.num;
1221 ctx->init_encode_params.frameRateDen = avctx->framerate.den;
1223 ctx->init_encode_params.frameRateNum = avctx->time_base.den;
1224 ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
1227 ctx->init_encode_params.enableEncodeAsync = 0;
1228 ctx->init_encode_params.enablePTD = 1;
1230 if (ctx->weighted_pred == 1)
1231 ctx->init_encode_params.enableWeightedPrediction = 1;
1233 if (ctx->bluray_compat) {
1235 ctx->dpb_size = FFMIN(FFMAX(avctx->refs, 0), 6);
1236 avctx->max_b_frames = FFMIN(avctx->max_b_frames, 3);
1237 switch (avctx->codec->id) {
1238 case AV_CODEC_ID_H264:
1239 /* maximum level depends on used resolution */
1241 case AV_CODEC_ID_HEVC:
1242 ctx->level = NV_ENC_LEVEL_HEVC_51;
1243 ctx->tier = NV_ENC_TIER_HEVC_HIGH;
1248 if (avctx->gop_size > 0) {
1249 if (avctx->max_b_frames >= 0) {
1250 /* 0 is intra-only, 1 is I/P only, 2 is one B-Frame, 3 two B-frames, and so on. */
1251 ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
1254 ctx->encode_config.gopLength = avctx->gop_size;
1255 } else if (avctx->gop_size == 0) {
1256 ctx->encode_config.frameIntervalP = 0;
1257 ctx->encode_config.gopLength = 1;
1260 nvenc_recalc_surfaces(avctx);
1262 nvenc_setup_rate_control(avctx);
1264 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1265 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
1267 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
1270 res = nvenc_setup_codec_config(avctx);
1274 res = nvenc_push_context(avctx);
1278 nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
1279 if (nv_status != NV_ENC_SUCCESS) {
1280 nvenc_pop_context(avctx);
1281 return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
1284 #ifdef NVENC_HAVE_CUSTREAM_PTR
1285 if (ctx->cu_context) {
1286 nv_status = p_nvenc->nvEncSetIOCudaStreams(ctx->nvencoder, &ctx->cu_stream, &ctx->cu_stream);
1287 if (nv_status != NV_ENC_SUCCESS) {
1288 nvenc_pop_context(avctx);
1289 return nvenc_print_error(avctx, nv_status, "SetIOCudaStreams failed");
1294 res = nvenc_pop_context(avctx);
1298 if (ctx->encode_config.frameIntervalP > 1)
1299 avctx->has_b_frames = 2;
1301 if (ctx->encode_config.rcParams.averageBitRate > 0)
1302 avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
1304 cpb_props = ff_add_cpb_side_data(avctx);
1306 return AVERROR(ENOMEM);
1307 cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
1308 cpb_props->avg_bitrate = avctx->bit_rate;
1309 cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
1314 static NV_ENC_BUFFER_FORMAT nvenc_map_buffer_format(enum AVPixelFormat pix_fmt)
1317 case AV_PIX_FMT_YUV420P:
1318 return NV_ENC_BUFFER_FORMAT_YV12_PL;
1319 case AV_PIX_FMT_NV12:
1320 return NV_ENC_BUFFER_FORMAT_NV12_PL;
1321 case AV_PIX_FMT_P010:
1322 case AV_PIX_FMT_P016:
1323 return NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1324 case AV_PIX_FMT_YUV444P:
1325 return NV_ENC_BUFFER_FORMAT_YUV444_PL;
1326 case AV_PIX_FMT_YUV444P16:
1327 return NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1328 case AV_PIX_FMT_0RGB32:
1329 return NV_ENC_BUFFER_FORMAT_ARGB;
1330 case AV_PIX_FMT_0BGR32:
1331 return NV_ENC_BUFFER_FORMAT_ABGR;
1333 return NV_ENC_BUFFER_FORMAT_UNDEFINED;
1337 static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
1339 NvencContext *ctx = avctx->priv_data;
1340 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1341 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1342 NvencSurface* tmp_surface = &ctx->surfaces[idx];
1344 NVENCSTATUS nv_status;
1345 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
1346 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1348 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1349 ctx->surfaces[idx].in_ref = av_frame_alloc();
1350 if (!ctx->surfaces[idx].in_ref)
1351 return AVERROR(ENOMEM);
1353 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1355 ctx->surfaces[idx].format = nvenc_map_buffer_format(ctx->data_pix_fmt);
1356 if (ctx->surfaces[idx].format == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1357 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1358 av_get_pix_fmt_name(ctx->data_pix_fmt));
1359 return AVERROR(EINVAL);
1362 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1363 allocSurf.width = avctx->width;
1364 allocSurf.height = avctx->height;
1365 allocSurf.bufferFmt = ctx->surfaces[idx].format;
1367 nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
1368 if (nv_status != NV_ENC_SUCCESS) {
1369 return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
1372 ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
1373 ctx->surfaces[idx].width = allocSurf.width;
1374 ctx->surfaces[idx].height = allocSurf.height;
1377 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
1378 if (nv_status != NV_ENC_SUCCESS) {
1379 int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
1380 if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
1381 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
1382 av_frame_free(&ctx->surfaces[idx].in_ref);
1386 ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1387 ctx->surfaces[idx].size = allocOut.size;
1389 av_fifo_generic_write(ctx->unused_surface_queue, &tmp_surface, sizeof(tmp_surface), NULL);
1394 static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx)
1396 NvencContext *ctx = avctx->priv_data;
1397 int i, res = 0, res2;
1399 ctx->surfaces = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->surfaces));
1401 return AVERROR(ENOMEM);
1403 ctx->timestamp_list = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
1404 if (!ctx->timestamp_list)
1405 return AVERROR(ENOMEM);
1407 ctx->unused_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1408 if (!ctx->unused_surface_queue)
1409 return AVERROR(ENOMEM);
1411 ctx->output_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1412 if (!ctx->output_surface_queue)
1413 return AVERROR(ENOMEM);
1414 ctx->output_surface_ready_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1415 if (!ctx->output_surface_ready_queue)
1416 return AVERROR(ENOMEM);
1418 res = nvenc_push_context(avctx);
1422 for (i = 0; i < ctx->nb_surfaces; i++) {
1423 if ((res = nvenc_alloc_surface(avctx, i)) < 0)
1428 res2 = nvenc_pop_context(avctx);
1435 static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
1437 NvencContext *ctx = avctx->priv_data;
1438 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1439 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1441 NVENCSTATUS nv_status;
1442 uint32_t outSize = 0;
1443 char tmpHeader[256];
1444 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1445 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1447 payload.spsppsBuffer = tmpHeader;
1448 payload.inBufferSize = sizeof(tmpHeader);
1449 payload.outSPSPPSPayloadSize = &outSize;
1451 nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
1452 if (nv_status != NV_ENC_SUCCESS) {
1453 return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
1456 avctx->extradata_size = outSize;
1457 avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
1459 if (!avctx->extradata) {
1460 return AVERROR(ENOMEM);
1463 memcpy(avctx->extradata, tmpHeader, outSize);
1468 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
1470 NvencContext *ctx = avctx->priv_data;
1471 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1472 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1475 /* the encoder has to be flushed before it can be closed */
1476 if (ctx->nvencoder) {
1477 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
1478 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
1480 res = nvenc_push_context(avctx);
1484 p_nvenc->nvEncEncodePicture(ctx->nvencoder, ¶ms);
1487 av_fifo_freep(&ctx->timestamp_list);
1488 av_fifo_freep(&ctx->output_surface_ready_queue);
1489 av_fifo_freep(&ctx->output_surface_queue);
1490 av_fifo_freep(&ctx->unused_surface_queue);
1492 if (ctx->surfaces && (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11)) {
1493 for (i = 0; i < ctx->nb_registered_frames; i++) {
1494 if (ctx->registered_frames[i].mapped)
1495 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[i].in_map.mappedResource);
1496 if (ctx->registered_frames[i].regptr)
1497 p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1499 ctx->nb_registered_frames = 0;
1502 if (ctx->surfaces) {
1503 for (i = 0; i < ctx->nb_surfaces; ++i) {
1504 if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
1505 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
1506 av_frame_free(&ctx->surfaces[i].in_ref);
1507 p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
1510 av_freep(&ctx->surfaces);
1511 ctx->nb_surfaces = 0;
1513 av_frame_free(&ctx->frame);
1515 if (ctx->nvencoder) {
1516 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1518 res = nvenc_pop_context(avctx);
1522 ctx->nvencoder = NULL;
1524 if (ctx->cu_context_internal)
1525 CHECK_CU(dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal));
1526 ctx->cu_context = ctx->cu_context_internal = NULL;
1529 if (ctx->d3d11_device) {
1530 ID3D11Device_Release(ctx->d3d11_device);
1531 ctx->d3d11_device = NULL;
1535 nvenc_free_functions(&dl_fn->nvenc_dl);
1536 cuda_free_functions(&dl_fn->cuda_dl);
1538 dl_fn->nvenc_device_count = 0;
1540 av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
1545 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
1547 NvencContext *ctx = avctx->priv_data;
1550 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1551 AVHWFramesContext *frames_ctx;
1552 if (!avctx->hw_frames_ctx) {
1553 av_log(avctx, AV_LOG_ERROR,
1554 "hw_frames_ctx must be set when using GPU frames as input\n");
1555 return AVERROR(EINVAL);
1557 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1558 if (frames_ctx->format != avctx->pix_fmt) {
1559 av_log(avctx, AV_LOG_ERROR,
1560 "hw_frames_ctx must match the GPU frame type\n");
1561 return AVERROR(EINVAL);
1563 ctx->data_pix_fmt = frames_ctx->sw_format;
1565 ctx->data_pix_fmt = avctx->pix_fmt;
1568 ctx->frame = av_frame_alloc();
1570 return AVERROR(ENOMEM);
1572 if ((ret = nvenc_load_libraries(avctx)) < 0)
1575 if ((ret = nvenc_setup_device(avctx)) < 0)
1578 if ((ret = nvenc_setup_encoder(avctx)) < 0)
1581 if ((ret = nvenc_setup_surfaces(avctx)) < 0)
1584 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1585 if ((ret = nvenc_setup_extradata(avctx)) < 0)
1592 static NvencSurface *get_free_frame(NvencContext *ctx)
1594 NvencSurface *tmp_surf;
1596 if (!(av_fifo_size(ctx->unused_surface_queue) > 0))
1600 av_fifo_generic_read(ctx->unused_surface_queue, &tmp_surf, sizeof(tmp_surf), NULL);
1604 static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *nv_surface,
1605 NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params, const AVFrame *frame)
1607 int dst_linesize[4] = {
1608 lock_buffer_params->pitch,
1609 lock_buffer_params->pitch,
1610 lock_buffer_params->pitch,
1611 lock_buffer_params->pitch
1613 uint8_t *dst_data[4];
1616 if (frame->format == AV_PIX_FMT_YUV420P)
1617 dst_linesize[1] = dst_linesize[2] >>= 1;
1619 ret = av_image_fill_pointers(dst_data, frame->format, nv_surface->height,
1620 lock_buffer_params->bufferDataPtr, dst_linesize);
1624 if (frame->format == AV_PIX_FMT_YUV420P)
1625 FFSWAP(uint8_t*, dst_data[1], dst_data[2]);
1627 av_image_copy(dst_data, dst_linesize,
1628 (const uint8_t**)frame->data, frame->linesize, frame->format,
1629 avctx->width, avctx->height);
1634 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1636 NvencContext *ctx = avctx->priv_data;
1637 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1638 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1639 NVENCSTATUS nv_status;
1643 if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1644 for (first_round = 1; first_round >= 0; first_round--) {
1645 for (i = 0; i < ctx->nb_registered_frames; i++) {
1646 if (!ctx->registered_frames[i].mapped) {
1647 if (ctx->registered_frames[i].regptr) {
1650 nv_status = p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1651 if (nv_status != NV_ENC_SUCCESS)
1652 return nvenc_print_error(avctx, nv_status, "Failed unregistering unused input resource");
1653 ctx->registered_frames[i].ptr = NULL;
1654 ctx->registered_frames[i].regptr = NULL;
1661 return ctx->nb_registered_frames++;
1664 av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1665 return AVERROR(ENOMEM);
1668 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1670 NvencContext *ctx = avctx->priv_data;
1671 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1672 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1674 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frame->hw_frames_ctx->data;
1675 NV_ENC_REGISTER_RESOURCE reg;
1678 for (i = 0; i < ctx->nb_registered_frames; i++) {
1679 if (avctx->pix_fmt == AV_PIX_FMT_CUDA && ctx->registered_frames[i].ptr == frame->data[0])
1681 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])
1685 idx = nvenc_find_free_reg_resource(avctx);
1689 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1690 reg.width = frames_ctx->width;
1691 reg.height = frames_ctx->height;
1692 reg.pitch = frame->linesize[0];
1693 reg.resourceToRegister = frame->data[0];
1695 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1696 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1698 else if (avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1699 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX;
1700 reg.subResourceIndex = (intptr_t)frame->data[1];
1703 reg.bufferFormat = nvenc_map_buffer_format(frames_ctx->sw_format);
1704 if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1705 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1706 av_get_pix_fmt_name(frames_ctx->sw_format));
1707 return AVERROR(EINVAL);
1710 ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, ®);
1711 if (ret != NV_ENC_SUCCESS) {
1712 nvenc_print_error(avctx, ret, "Error registering an input resource");
1713 return AVERROR_UNKNOWN;
1716 ctx->registered_frames[idx].ptr = frame->data[0];
1717 ctx->registered_frames[idx].ptr_index = reg.subResourceIndex;
1718 ctx->registered_frames[idx].regptr = reg.registeredResource;
1722 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1723 NvencSurface *nvenc_frame)
1725 NvencContext *ctx = avctx->priv_data;
1726 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1727 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1730 NVENCSTATUS nv_status;
1732 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1733 int reg_idx = nvenc_register_frame(avctx, frame);
1735 av_log(avctx, AV_LOG_ERROR, "Could not register an input HW frame\n");
1739 res = av_frame_ref(nvenc_frame->in_ref, frame);
1743 if (!ctx->registered_frames[reg_idx].mapped) {
1744 ctx->registered_frames[reg_idx].in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1745 ctx->registered_frames[reg_idx].in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1746 nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &ctx->registered_frames[reg_idx].in_map);
1747 if (nv_status != NV_ENC_SUCCESS) {
1748 av_frame_unref(nvenc_frame->in_ref);
1749 return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
1753 ctx->registered_frames[reg_idx].mapped += 1;
1755 nvenc_frame->reg_idx = reg_idx;
1756 nvenc_frame->input_surface = ctx->registered_frames[reg_idx].in_map.mappedResource;
1757 nvenc_frame->format = ctx->registered_frames[reg_idx].in_map.mappedBufferFmt;
1758 nvenc_frame->pitch = frame->linesize[0];
1762 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1764 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1765 lockBufferParams.inputBuffer = nvenc_frame->input_surface;
1767 nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
1768 if (nv_status != NV_ENC_SUCCESS) {
1769 return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
1772 nvenc_frame->pitch = lockBufferParams.pitch;
1773 res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
1775 nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
1776 if (nv_status != NV_ENC_SUCCESS) {
1777 return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
1784 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1785 NV_ENC_PIC_PARAMS *params,
1786 NV_ENC_SEI_PAYLOAD *sei_data,
1789 NvencContext *ctx = avctx->priv_data;
1791 switch (avctx->codec->id) {
1792 case AV_CODEC_ID_H264:
1793 params->codecPicParams.h264PicParams.sliceMode =
1794 ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1795 params->codecPicParams.h264PicParams.sliceModeData =
1796 ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1797 if (sei_count > 0) {
1798 params->codecPicParams.h264PicParams.seiPayloadArray = sei_data;
1799 params->codecPicParams.h264PicParams.seiPayloadArrayCnt = sei_count;
1803 case AV_CODEC_ID_HEVC:
1804 params->codecPicParams.hevcPicParams.sliceMode =
1805 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1806 params->codecPicParams.hevcPicParams.sliceModeData =
1807 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1808 if (sei_count > 0) {
1809 params->codecPicParams.hevcPicParams.seiPayloadArray = sei_data;
1810 params->codecPicParams.hevcPicParams.seiPayloadArrayCnt = sei_count;
1817 static inline void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
1819 av_fifo_generic_write(queue, ×tamp, sizeof(timestamp), NULL);
1822 static inline int64_t timestamp_queue_dequeue(AVFifoBuffer* queue)
1824 int64_t timestamp = AV_NOPTS_VALUE;
1825 if (av_fifo_size(queue) > 0)
1826 av_fifo_generic_read(queue, ×tamp, sizeof(timestamp), NULL);
1831 static int nvenc_set_timestamp(AVCodecContext *avctx,
1832 NV_ENC_LOCK_BITSTREAM *params,
1835 NvencContext *ctx = avctx->priv_data;
1837 pkt->pts = params->outputTimeStamp;
1838 pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
1840 pkt->dts -= FFMAX(avctx->max_b_frames, 0) * FFMIN(avctx->ticks_per_frame, 1);
1845 static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
1847 NvencContext *ctx = avctx->priv_data;
1848 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1849 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1851 uint32_t slice_mode_data;
1852 uint32_t *slice_offsets = NULL;
1853 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1854 NVENCSTATUS nv_status;
1857 enum AVPictureType pict_type;
1859 switch (avctx->codec->id) {
1860 case AV_CODEC_ID_H264:
1861 slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1863 case AV_CODEC_ID_H265:
1864 slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1867 av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
1868 res = AVERROR(EINVAL);
1871 slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
1873 if (!slice_offsets) {
1874 res = AVERROR(ENOMEM);
1878 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1880 lock_params.doNotWait = 0;
1881 lock_params.outputBitstream = tmpoutsurf->output_surface;
1882 lock_params.sliceOffsets = slice_offsets;
1884 nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
1885 if (nv_status != NV_ENC_SUCCESS) {
1886 res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
1890 res = av_new_packet(pkt, lock_params.bitstreamSizeInBytes);
1893 p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1897 memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1899 nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1900 if (nv_status != NV_ENC_SUCCESS) {
1901 res = nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
1906 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1907 ctx->registered_frames[tmpoutsurf->reg_idx].mapped -= 1;
1908 if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped == 0) {
1909 nv_status = p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[tmpoutsurf->reg_idx].in_map.mappedResource);
1910 if (nv_status != NV_ENC_SUCCESS) {
1911 res = nvenc_print_error(avctx, nv_status, "Failed unmapping input resource");
1914 } else if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped < 0) {
1919 av_frame_unref(tmpoutsurf->in_ref);
1921 tmpoutsurf->input_surface = NULL;
1924 switch (lock_params.pictureType) {
1925 case NV_ENC_PIC_TYPE_IDR:
1926 pkt->flags |= AV_PKT_FLAG_KEY;
1927 case NV_ENC_PIC_TYPE_I:
1928 pict_type = AV_PICTURE_TYPE_I;
1930 case NV_ENC_PIC_TYPE_P:
1931 pict_type = AV_PICTURE_TYPE_P;
1933 case NV_ENC_PIC_TYPE_B:
1934 pict_type = AV_PICTURE_TYPE_B;
1936 case NV_ENC_PIC_TYPE_BI:
1937 pict_type = AV_PICTURE_TYPE_BI;
1940 av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
1941 av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
1942 res = AVERROR_EXTERNAL;
1946 #if FF_API_CODED_FRAME
1947 FF_DISABLE_DEPRECATION_WARNINGS
1948 avctx->coded_frame->pict_type = pict_type;
1949 FF_ENABLE_DEPRECATION_WARNINGS
1952 ff_side_data_set_encoder_stats(pkt,
1953 (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
1955 res = nvenc_set_timestamp(avctx, &lock_params, pkt);
1959 av_free(slice_offsets);
1964 timestamp_queue_dequeue(ctx->timestamp_list);
1967 av_free(slice_offsets);
1972 static int output_ready(AVCodecContext *avctx, int flush)
1974 NvencContext *ctx = avctx->priv_data;
1975 int nb_ready, nb_pending;
1977 nb_ready = av_fifo_size(ctx->output_surface_ready_queue) / sizeof(NvencSurface*);
1978 nb_pending = av_fifo_size(ctx->output_surface_queue) / sizeof(NvencSurface*);
1980 return nb_ready > 0;
1981 return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
1984 static void reconfig_encoder(AVCodecContext *avctx, const AVFrame *frame)
1986 NvencContext *ctx = avctx->priv_data;
1987 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
1990 NV_ENC_RECONFIGURE_PARAMS params = { 0 };
1991 int needs_reconfig = 0;
1992 int needs_encode_config = 0;
1993 int reconfig_bitrate = 0, reconfig_dar = 0;
1996 params.version = NV_ENC_RECONFIGURE_PARAMS_VER;
1997 params.reInitEncodeParams = ctx->init_encode_params;
1999 compute_dar(avctx, &dw, &dh);
2000 if (dw != ctx->init_encode_params.darWidth || dh != ctx->init_encode_params.darHeight) {
2001 av_log(avctx, AV_LOG_VERBOSE,
2002 "aspect ratio change (DAR): %d:%d -> %d:%d\n",
2003 ctx->init_encode_params.darWidth,
2004 ctx->init_encode_params.darHeight, dw, dh);
2006 params.reInitEncodeParams.darHeight = dh;
2007 params.reInitEncodeParams.darWidth = dw;
2013 if (ctx->rc != NV_ENC_PARAMS_RC_CONSTQP && ctx->support_dyn_bitrate) {
2014 if (avctx->bit_rate > 0 && params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate != avctx->bit_rate) {
2015 av_log(avctx, AV_LOG_VERBOSE,
2016 "avg bitrate change: %d -> %d\n",
2017 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate,
2018 (uint32_t)avctx->bit_rate);
2020 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate = avctx->bit_rate;
2021 reconfig_bitrate = 1;
2024 if (avctx->rc_max_rate > 0 && ctx->encode_config.rcParams.maxBitRate != avctx->rc_max_rate) {
2025 av_log(avctx, AV_LOG_VERBOSE,
2026 "max bitrate change: %d -> %d\n",
2027 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate,
2028 (uint32_t)avctx->rc_max_rate);
2030 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate = avctx->rc_max_rate;
2031 reconfig_bitrate = 1;
2034 if (avctx->rc_buffer_size > 0 && ctx->encode_config.rcParams.vbvBufferSize != avctx->rc_buffer_size) {
2035 av_log(avctx, AV_LOG_VERBOSE,
2036 "vbv buffer size change: %d -> %d\n",
2037 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize,
2038 avctx->rc_buffer_size);
2040 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize = avctx->rc_buffer_size;
2041 reconfig_bitrate = 1;
2044 if (reconfig_bitrate) {
2045 params.resetEncoder = 1;
2046 params.forceIDR = 1;
2048 needs_encode_config = 1;
2053 if (!needs_encode_config)
2054 params.reInitEncodeParams.encodeConfig = NULL;
2056 if (needs_reconfig) {
2057 ret = p_nvenc->nvEncReconfigureEncoder(ctx->nvencoder, ¶ms);
2058 if (ret != NV_ENC_SUCCESS) {
2059 nvenc_print_error(avctx, ret, "failed to reconfigure nvenc");
2062 ctx->init_encode_params.darHeight = dh;
2063 ctx->init_encode_params.darWidth = dw;
2066 if (reconfig_bitrate) {
2067 ctx->encode_config.rcParams.averageBitRate = params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate;
2068 ctx->encode_config.rcParams.maxBitRate = params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate;
2069 ctx->encode_config.rcParams.vbvBufferSize = params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize;
2076 static int nvenc_send_frame(AVCodecContext *avctx, const AVFrame *frame)
2078 NVENCSTATUS nv_status;
2079 NvencSurface *tmp_out_surf, *in_surf;
2081 NV_ENC_SEI_PAYLOAD sei_data[8];
2085 NvencContext *ctx = avctx->priv_data;
2086 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
2087 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
2089 NV_ENC_PIC_PARAMS pic_params = { 0 };
2090 pic_params.version = NV_ENC_PIC_PARAMS_VER;
2092 if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
2093 return AVERROR(EINVAL);
2095 if (frame && frame->buf[0]) {
2096 in_surf = get_free_frame(ctx);
2098 return AVERROR(EAGAIN);
2100 res = nvenc_push_context(avctx);
2104 reconfig_encoder(avctx, frame);
2106 res = nvenc_upload_frame(avctx, frame, in_surf);
2108 res2 = nvenc_pop_context(avctx);
2115 pic_params.inputBuffer = in_surf->input_surface;
2116 pic_params.bufferFmt = in_surf->format;
2117 pic_params.inputWidth = in_surf->width;
2118 pic_params.inputHeight = in_surf->height;
2119 pic_params.inputPitch = in_surf->pitch;
2120 pic_params.outputBitstream = in_surf->output_surface;
2122 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
2123 if (frame->top_field_first)
2124 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
2126 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
2128 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
2131 if (ctx->forced_idr >= 0 && frame->pict_type == AV_PICTURE_TYPE_I) {
2132 pic_params.encodePicFlags =
2133 ctx->forced_idr ? NV_ENC_PIC_FLAG_FORCEIDR : NV_ENC_PIC_FLAG_FORCEINTRA;
2135 pic_params.encodePicFlags = 0;
2138 pic_params.inputTimeStamp = frame->pts;
2140 if (ctx->a53_cc && av_frame_get_side_data(frame, AV_FRAME_DATA_A53_CC)) {
2141 void *a53_data = NULL;
2142 size_t a53_size = 0;
2144 if (ff_alloc_a53_sei(frame, 0, (void**)&a53_data, &a53_size) < 0) {
2145 av_log(ctx, AV_LOG_ERROR, "Not enough memory for closed captions, skipping\n");
2149 sei_data[sei_count].payloadSize = (uint32_t)a53_size;
2150 sei_data[sei_count].payloadType = 4;
2151 sei_data[sei_count].payload = (uint8_t*)a53_data;
2156 nvenc_codec_specific_pic_params(avctx, &pic_params, sei_data, sei_count);
2158 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
2161 res = nvenc_push_context(avctx);
2165 nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
2167 for ( i = 0; i < sei_count; i++)
2168 av_freep(&sei_data[i].payload);
2170 res = nvenc_pop_context(avctx);
2174 if (nv_status != NV_ENC_SUCCESS &&
2175 nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
2176 return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
2178 if (frame && frame->buf[0]) {
2179 av_fifo_generic_write(ctx->output_surface_queue, &in_surf, sizeof(in_surf), NULL);
2180 timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
2183 /* all the pending buffers are now ready for output */
2184 if (nv_status == NV_ENC_SUCCESS) {
2185 while (av_fifo_size(ctx->output_surface_queue) > 0) {
2186 av_fifo_generic_read(ctx->output_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2187 av_fifo_generic_write(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2194 int ff_nvenc_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
2196 NvencSurface *tmp_out_surf;
2199 NvencContext *ctx = avctx->priv_data;
2201 AVFrame *frame = ctx->frame;
2203 if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
2204 return AVERROR(EINVAL);
2206 if (!frame->buf[0]) {
2207 res = ff_encode_get_frame(avctx, frame);
2208 if (res < 0 && res != AVERROR_EOF)
2212 res = nvenc_send_frame(avctx, frame);
2214 if (res != AVERROR(EAGAIN))
2217 av_frame_unref(frame);
2219 if (output_ready(avctx, avctx->internal->draining)) {
2220 av_fifo_generic_read(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2222 res = nvenc_push_context(avctx);
2226 res = process_output_surface(avctx, pkt, tmp_out_surf);
2228 res2 = nvenc_pop_context(avctx);
2235 av_fifo_generic_write(ctx->unused_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2236 } else if (avctx->internal->draining) {
2239 return AVERROR(EAGAIN);
2245 av_cold void ff_nvenc_encode_flush(AVCodecContext *avctx)
2247 NvencContext *ctx = avctx->priv_data;
2249 nvenc_send_frame(avctx, NULL);
2250 av_fifo_reset(ctx->timestamp_list);