2 * H.264/HEVC hardware encoding using nvidia nvenc
3 * Copyright (c) 2016 Timo Rothenpieler <timo@rothenpieler.org>
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 #include "libavutil/hwcontext_cuda.h"
27 #include "libavutil/hwcontext.h"
28 #include "libavutil/cuda_check.h"
29 #include "libavutil/imgutils.h"
30 #include "libavutil/avassert.h"
31 #include "libavutil/mem.h"
32 #include "libavutil/pixdesc.h"
35 #define CHECK_CU(x) FF_CUDA_CHECK_DL(avctx, dl_fn->cuda_dl, x)
37 #define NVENC_CAP 0x30
38 #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR || \
39 rc == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ || \
40 rc == NV_ENC_PARAMS_RC_CBR_HQ)
42 const enum AVPixelFormat ff_nvenc_pix_fmts[] = {
47 AV_PIX_FMT_P016, // Truncated to 10bits
48 AV_PIX_FMT_YUV444P16, // Truncated to 10bits
58 #define IS_10BIT(pix_fmt) (pix_fmt == AV_PIX_FMT_P010 || \
59 pix_fmt == AV_PIX_FMT_P016 || \
60 pix_fmt == AV_PIX_FMT_YUV444P16)
62 #define IS_YUV444(pix_fmt) (pix_fmt == AV_PIX_FMT_YUV444P || \
63 pix_fmt == AV_PIX_FMT_YUV444P16)
70 { NV_ENC_SUCCESS, 0, "success" },
71 { NV_ENC_ERR_NO_ENCODE_DEVICE, AVERROR(ENOENT), "no encode device" },
72 { NV_ENC_ERR_UNSUPPORTED_DEVICE, AVERROR(ENOSYS), "unsupported device" },
73 { NV_ENC_ERR_INVALID_ENCODERDEVICE, AVERROR(EINVAL), "invalid encoder device" },
74 { NV_ENC_ERR_INVALID_DEVICE, AVERROR(EINVAL), "invalid device" },
75 { NV_ENC_ERR_DEVICE_NOT_EXIST, AVERROR(EIO), "device does not exist" },
76 { NV_ENC_ERR_INVALID_PTR, AVERROR(EFAULT), "invalid ptr" },
77 { NV_ENC_ERR_INVALID_EVENT, AVERROR(EINVAL), "invalid event" },
78 { NV_ENC_ERR_INVALID_PARAM, AVERROR(EINVAL), "invalid param" },
79 { NV_ENC_ERR_INVALID_CALL, AVERROR(EINVAL), "invalid call" },
80 { NV_ENC_ERR_OUT_OF_MEMORY, AVERROR(ENOMEM), "out of memory" },
81 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED, AVERROR(EINVAL), "encoder not initialized" },
82 { NV_ENC_ERR_UNSUPPORTED_PARAM, AVERROR(ENOSYS), "unsupported param" },
83 { NV_ENC_ERR_LOCK_BUSY, AVERROR(EAGAIN), "lock busy" },
84 { NV_ENC_ERR_NOT_ENOUGH_BUFFER, AVERROR_BUFFER_TOO_SMALL, "not enough buffer"},
85 { NV_ENC_ERR_INVALID_VERSION, AVERROR(EINVAL), "invalid version" },
86 { NV_ENC_ERR_MAP_FAILED, AVERROR(EIO), "map failed" },
87 { NV_ENC_ERR_NEED_MORE_INPUT, AVERROR(EAGAIN), "need more input" },
88 { NV_ENC_ERR_ENCODER_BUSY, AVERROR(EAGAIN), "encoder busy" },
89 { NV_ENC_ERR_EVENT_NOT_REGISTERD, AVERROR(EBADF), "event not registered" },
90 { NV_ENC_ERR_GENERIC, AVERROR_UNKNOWN, "generic error" },
91 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY, AVERROR(EINVAL), "incompatible client key" },
92 { NV_ENC_ERR_UNIMPLEMENTED, AVERROR(ENOSYS), "unimplemented" },
93 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO), "resource register failed" },
94 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED, AVERROR(EBADF), "resource not registered" },
95 { NV_ENC_ERR_RESOURCE_NOT_MAPPED, AVERROR(EBADF), "resource not mapped" },
98 static int nvenc_map_error(NVENCSTATUS err, const char **desc)
101 for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
102 if (nvenc_errors[i].nverr == err) {
104 *desc = nvenc_errors[i].desc;
105 return nvenc_errors[i].averr;
109 *desc = "unknown error";
110 return AVERROR_UNKNOWN;
113 static int nvenc_print_error(AVCodecContext *avctx, NVENCSTATUS err,
114 const char *error_string)
117 const char *details = "(no details)";
118 int ret = nvenc_map_error(err, &desc);
120 #ifdef NVENC_HAVE_GETLASTERRORSTRING
121 NvencContext *ctx = avctx->priv_data;
122 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
124 if (p_nvenc && ctx->nvencoder)
125 details = p_nvenc->nvEncGetLastErrorString(ctx->nvencoder);
128 av_log(avctx, AV_LOG_ERROR, "%s: %s (%d): %s\n", error_string, desc, err, details);
133 static void nvenc_print_driver_requirement(AVCodecContext *avctx, int level)
135 #if NVENCAPI_CHECK_VERSION(9, 2)
136 const char *minver = "(unknown)";
137 #elif NVENCAPI_CHECK_VERSION(9, 1)
138 # if defined(_WIN32) || defined(__CYGWIN__)
139 const char *minver = "436.15";
141 const char *minver = "435.21";
143 #elif NVENCAPI_CHECK_VERSION(9, 0)
144 # if defined(_WIN32) || defined(__CYGWIN__)
145 const char *minver = "418.81";
147 const char *minver = "418.30";
149 #elif NVENCAPI_CHECK_VERSION(8, 2)
150 # if defined(_WIN32) || defined(__CYGWIN__)
151 const char *minver = "397.93";
153 const char *minver = "396.24";
155 #elif NVENCAPI_CHECK_VERSION(8, 1)
156 # if defined(_WIN32) || defined(__CYGWIN__)
157 const char *minver = "390.77";
159 const char *minver = "390.25";
162 # if defined(_WIN32) || defined(__CYGWIN__)
163 const char *minver = "378.66";
165 const char *minver = "378.13";
168 av_log(avctx, level, "The minimum required Nvidia driver for nvenc is %s or newer\n", minver);
171 static av_cold int nvenc_load_libraries(AVCodecContext *avctx)
173 NvencContext *ctx = avctx->priv_data;
174 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
176 uint32_t nvenc_max_ver;
179 ret = cuda_load_functions(&dl_fn->cuda_dl, avctx);
183 ret = nvenc_load_functions(&dl_fn->nvenc_dl, avctx);
185 nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
189 err = dl_fn->nvenc_dl->NvEncodeAPIGetMaxSupportedVersion(&nvenc_max_ver);
190 if (err != NV_ENC_SUCCESS)
191 return nvenc_print_error(avctx, err, "Failed to query nvenc max version");
193 av_log(avctx, AV_LOG_VERBOSE, "Loaded Nvenc version %d.%d\n", nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
195 if ((NVENCAPI_MAJOR_VERSION << 4 | NVENCAPI_MINOR_VERSION) > nvenc_max_ver) {
196 av_log(avctx, AV_LOG_ERROR, "Driver does not support the required nvenc API version. "
197 "Required: %d.%d Found: %d.%d\n",
198 NVENCAPI_MAJOR_VERSION, NVENCAPI_MINOR_VERSION,
199 nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
200 nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
201 return AVERROR(ENOSYS);
204 dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
206 err = dl_fn->nvenc_dl->NvEncodeAPICreateInstance(&dl_fn->nvenc_funcs);
207 if (err != NV_ENC_SUCCESS)
208 return nvenc_print_error(avctx, err, "Failed to create nvenc instance");
210 av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
215 static int nvenc_push_context(AVCodecContext *avctx)
217 NvencContext *ctx = avctx->priv_data;
218 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
220 if (ctx->d3d11_device)
223 return CHECK_CU(dl_fn->cuda_dl->cuCtxPushCurrent(ctx->cu_context));
226 static int nvenc_pop_context(AVCodecContext *avctx)
228 NvencContext *ctx = avctx->priv_data;
229 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
232 if (ctx->d3d11_device)
235 return CHECK_CU(dl_fn->cuda_dl->cuCtxPopCurrent(&dummy));
238 static av_cold int nvenc_open_session(AVCodecContext *avctx)
240 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
241 NvencContext *ctx = avctx->priv_data;
242 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
245 params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
246 params.apiVersion = NVENCAPI_VERSION;
247 if (ctx->d3d11_device) {
248 params.device = ctx->d3d11_device;
249 params.deviceType = NV_ENC_DEVICE_TYPE_DIRECTX;
251 params.device = ctx->cu_context;
252 params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
255 ret = p_nvenc->nvEncOpenEncodeSessionEx(¶ms, &ctx->nvencoder);
256 if (ret != NV_ENC_SUCCESS) {
257 ctx->nvencoder = NULL;
258 return nvenc_print_error(avctx, ret, "OpenEncodeSessionEx failed");
264 static int nvenc_check_codec_support(AVCodecContext *avctx)
266 NvencContext *ctx = avctx->priv_data;
267 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
268 int i, ret, count = 0;
271 ret = p_nvenc->nvEncGetEncodeGUIDCount(ctx->nvencoder, &count);
273 if (ret != NV_ENC_SUCCESS || !count)
274 return AVERROR(ENOSYS);
276 guids = av_malloc(count * sizeof(GUID));
278 return AVERROR(ENOMEM);
280 ret = p_nvenc->nvEncGetEncodeGUIDs(ctx->nvencoder, guids, count, &count);
281 if (ret != NV_ENC_SUCCESS) {
282 ret = AVERROR(ENOSYS);
286 ret = AVERROR(ENOSYS);
287 for (i = 0; i < count; i++) {
288 if (!memcmp(&guids[i], &ctx->init_encode_params.encodeGUID, sizeof(*guids))) {
300 static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
302 NvencContext *ctx = avctx->priv_data;
303 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
304 NV_ENC_CAPS_PARAM params = { 0 };
307 params.version = NV_ENC_CAPS_PARAM_VER;
308 params.capsToQuery = cap;
310 ret = p_nvenc->nvEncGetEncodeCaps(ctx->nvencoder, ctx->init_encode_params.encodeGUID, ¶ms, &val);
312 if (ret == NV_ENC_SUCCESS)
317 static int nvenc_check_capabilities(AVCodecContext *avctx)
319 NvencContext *ctx = avctx->priv_data;
322 ret = nvenc_check_codec_support(avctx);
324 av_log(avctx, AV_LOG_WARNING, "Codec not supported\n");
328 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
329 if (IS_YUV444(ctx->data_pix_fmt) && ret <= 0) {
330 av_log(avctx, AV_LOG_WARNING, "YUV444P not supported\n");
331 return AVERROR(ENOSYS);
334 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOSSLESS_ENCODE);
335 if (ctx->preset >= PRESET_LOSSLESS_DEFAULT && ret <= 0) {
336 av_log(avctx, AV_LOG_WARNING, "Lossless encoding not supported\n");
337 return AVERROR(ENOSYS);
340 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
341 if (ret < avctx->width) {
342 av_log(avctx, AV_LOG_WARNING, "Width %d exceeds %d\n",
344 return AVERROR(ENOSYS);
347 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
348 if (ret < avctx->height) {
349 av_log(avctx, AV_LOG_WARNING, "Height %d exceeds %d\n",
351 return AVERROR(ENOSYS);
354 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
355 if (ret < avctx->max_b_frames) {
356 av_log(avctx, AV_LOG_WARNING, "Max B-frames %d exceed %d\n",
357 avctx->max_b_frames, ret);
359 return AVERROR(ENOSYS);
362 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_FIELD_ENCODING);
363 if (ret < 1 && avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
364 av_log(avctx, AV_LOG_WARNING,
365 "Interlaced encoding is not supported. Supported level: %d\n",
367 return AVERROR(ENOSYS);
370 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_10BIT_ENCODE);
371 if (IS_10BIT(ctx->data_pix_fmt) && ret <= 0) {
372 av_log(avctx, AV_LOG_WARNING, "10 bit encode not supported\n");
373 return AVERROR(ENOSYS);
376 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOOKAHEAD);
377 if (ctx->rc_lookahead > 0 && ret <= 0) {
378 av_log(avctx, AV_LOG_WARNING, "RC lookahead not supported\n");
379 return AVERROR(ENOSYS);
382 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_TEMPORAL_AQ);
383 if (ctx->temporal_aq > 0 && ret <= 0) {
384 av_log(avctx, AV_LOG_WARNING, "Temporal AQ not supported\n");
385 return AVERROR(ENOSYS);
388 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_WEIGHTED_PREDICTION);
389 if (ctx->weighted_pred > 0 && ret <= 0) {
390 av_log (avctx, AV_LOG_WARNING, "Weighted Prediction not supported\n");
391 return AVERROR(ENOSYS);
394 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_CABAC);
395 if (ctx->coder == NV_ENC_H264_ENTROPY_CODING_MODE_CABAC && ret <= 0) {
396 av_log(avctx, AV_LOG_WARNING, "CABAC entropy coding not supported\n");
397 return AVERROR(ENOSYS);
400 #ifdef NVENC_HAVE_BFRAME_REF_MODE
401 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_BFRAME_REF_MODE);
402 if (ctx->b_ref_mode == NV_ENC_BFRAME_REF_MODE_EACH && ret != 1) {
403 av_log(avctx, AV_LOG_WARNING, "Each B frame as reference is not supported\n");
404 return AVERROR(ENOSYS);
405 } else if (ctx->b_ref_mode != NV_ENC_BFRAME_REF_MODE_DISABLED && ret == 0) {
406 av_log(avctx, AV_LOG_WARNING, "B frames as references are not supported\n");
407 return AVERROR(ENOSYS);
410 if (ctx->b_ref_mode != 0) {
411 av_log(avctx, AV_LOG_WARNING, "B frames as references need SDK 8.1 at build time\n");
412 return AVERROR(ENOSYS);
416 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
417 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_MULTIPLE_REF_FRAMES);
418 if(avctx->refs != NV_ENC_NUM_REF_FRAMES_AUTOSELECT && ret <= 0) {
419 av_log(avctx, AV_LOG_WARNING, "Multiple reference frames are not supported by the device\n");
420 return AVERROR(ENOSYS);
423 if(avctx->refs != 0) {
424 av_log(avctx, AV_LOG_WARNING, "Multiple reference frames need SDK 9.1 at build time\n");
425 return AVERROR(ENOSYS);
429 ctx->support_dyn_bitrate = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_DYN_BITRATE_CHANGE);
434 static av_cold int nvenc_check_device(AVCodecContext *avctx, int idx)
436 NvencContext *ctx = avctx->priv_data;
437 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
438 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
439 char name[128] = { 0};
440 int major, minor, ret;
442 int loglevel = AV_LOG_VERBOSE;
444 if (ctx->device == LIST_DEVICES)
445 loglevel = AV_LOG_INFO;
447 ret = CHECK_CU(dl_fn->cuda_dl->cuDeviceGet(&cu_device, idx));
451 ret = CHECK_CU(dl_fn->cuda_dl->cuDeviceGetName(name, sizeof(name), cu_device));
455 ret = CHECK_CU(dl_fn->cuda_dl->cuDeviceComputeCapability(&major, &minor, cu_device));
459 av_log(avctx, loglevel, "[ GPU #%d - < %s > has Compute SM %d.%d ]\n", idx, name, major, minor);
460 if (((major << 4) | minor) < NVENC_CAP) {
461 av_log(avctx, loglevel, "does not support NVENC\n");
465 if (ctx->device != idx && ctx->device != ANY_DEVICE)
468 ret = CHECK_CU(dl_fn->cuda_dl->cuCtxCreate(&ctx->cu_context_internal, 0, cu_device));
472 ctx->cu_context = ctx->cu_context_internal;
473 ctx->cu_stream = NULL;
475 if ((ret = nvenc_pop_context(avctx)) < 0)
478 if ((ret = nvenc_open_session(avctx)) < 0)
481 if ((ret = nvenc_check_capabilities(avctx)) < 0)
484 av_log(avctx, loglevel, "supports NVENC\n");
486 dl_fn->nvenc_device_count++;
488 if (ctx->device == idx || ctx->device == ANY_DEVICE)
492 if ((ret = nvenc_push_context(avctx)) < 0)
495 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
496 ctx->nvencoder = NULL;
498 if ((ret = nvenc_pop_context(avctx)) < 0)
502 CHECK_CU(dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal));
503 ctx->cu_context_internal = NULL;
506 return AVERROR(ENOSYS);
509 static av_cold int nvenc_setup_device(AVCodecContext *avctx)
511 NvencContext *ctx = avctx->priv_data;
512 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
514 switch (avctx->codec->id) {
515 case AV_CODEC_ID_H264:
516 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
518 case AV_CODEC_ID_HEVC:
519 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
525 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11 || avctx->hw_frames_ctx || avctx->hw_device_ctx) {
526 AVHWFramesContext *frames_ctx;
527 AVHWDeviceContext *hwdev_ctx;
528 AVCUDADeviceContext *cuda_device_hwctx = NULL;
530 AVD3D11VADeviceContext *d3d11_device_hwctx = NULL;
534 if (avctx->hw_frames_ctx) {
535 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
536 if (frames_ctx->format == AV_PIX_FMT_CUDA)
537 cuda_device_hwctx = frames_ctx->device_ctx->hwctx;
539 else if (frames_ctx->format == AV_PIX_FMT_D3D11)
540 d3d11_device_hwctx = frames_ctx->device_ctx->hwctx;
543 return AVERROR(EINVAL);
544 } else if (avctx->hw_device_ctx) {
545 hwdev_ctx = (AVHWDeviceContext*)avctx->hw_device_ctx->data;
546 if (hwdev_ctx->type == AV_HWDEVICE_TYPE_CUDA)
547 cuda_device_hwctx = hwdev_ctx->hwctx;
549 else if (hwdev_ctx->type == AV_HWDEVICE_TYPE_D3D11VA)
550 d3d11_device_hwctx = hwdev_ctx->hwctx;
553 return AVERROR(EINVAL);
555 return AVERROR(EINVAL);
558 if (cuda_device_hwctx) {
559 ctx->cu_context = cuda_device_hwctx->cuda_ctx;
560 ctx->cu_stream = cuda_device_hwctx->stream;
563 else if (d3d11_device_hwctx) {
564 ctx->d3d11_device = d3d11_device_hwctx->device;
565 ID3D11Device_AddRef(ctx->d3d11_device);
569 ret = nvenc_open_session(avctx);
573 ret = nvenc_check_capabilities(avctx);
575 av_log(avctx, AV_LOG_FATAL, "Provided device doesn't support required NVENC features\n");
579 int i, nb_devices = 0;
581 if (CHECK_CU(dl_fn->cuda_dl->cuInit(0)) < 0)
582 return AVERROR_UNKNOWN;
584 if (CHECK_CU(dl_fn->cuda_dl->cuDeviceGetCount(&nb_devices)) < 0)
585 return AVERROR_UNKNOWN;
588 av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
589 return AVERROR_EXTERNAL;
592 av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", nb_devices);
594 dl_fn->nvenc_device_count = 0;
595 for (i = 0; i < nb_devices; ++i) {
596 if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
600 if (ctx->device == LIST_DEVICES)
603 if (!dl_fn->nvenc_device_count) {
604 av_log(avctx, AV_LOG_FATAL, "No capable devices found\n");
605 return AVERROR_EXTERNAL;
608 av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->device, nb_devices);
609 return AVERROR(EINVAL);
615 typedef struct GUIDTuple {
620 #define PRESET_ALIAS(alias, name, ...) \
621 [PRESET_ ## alias] = { NV_ENC_PRESET_ ## name ## _GUID, __VA_ARGS__ }
623 #define PRESET(name, ...) PRESET_ALIAS(name, name, __VA_ARGS__)
625 static void nvenc_map_preset(NvencContext *ctx)
627 GUIDTuple presets[] = {
632 PRESET_ALIAS(SLOW, HQ, NVENC_TWO_PASSES),
633 PRESET_ALIAS(MEDIUM, HQ, NVENC_ONE_PASS),
634 PRESET_ALIAS(FAST, HP, NVENC_ONE_PASS),
635 PRESET(LOW_LATENCY_DEFAULT, NVENC_LOWLATENCY),
636 PRESET(LOW_LATENCY_HP, NVENC_LOWLATENCY),
637 PRESET(LOW_LATENCY_HQ, NVENC_LOWLATENCY),
638 PRESET(LOSSLESS_DEFAULT, NVENC_LOSSLESS),
639 PRESET(LOSSLESS_HP, NVENC_LOSSLESS),
642 GUIDTuple *t = &presets[ctx->preset];
644 ctx->init_encode_params.presetGUID = t->guid;
645 ctx->flags = t->flags;
651 static av_cold void set_constqp(AVCodecContext *avctx)
653 NvencContext *ctx = avctx->priv_data;
654 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
656 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
658 if (ctx->init_qp_p >= 0) {
659 rc->constQP.qpInterP = ctx->init_qp_p;
660 if (ctx->init_qp_i >= 0 && ctx->init_qp_b >= 0) {
661 rc->constQP.qpIntra = ctx->init_qp_i;
662 rc->constQP.qpInterB = ctx->init_qp_b;
663 } else if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
664 rc->constQP.qpIntra = av_clip(
665 rc->constQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
666 rc->constQP.qpInterB = av_clip(
667 rc->constQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
669 rc->constQP.qpIntra = rc->constQP.qpInterP;
670 rc->constQP.qpInterB = rc->constQP.qpInterP;
672 } else if (ctx->cqp >= 0) {
673 rc->constQP.qpInterP = rc->constQP.qpInterB = rc->constQP.qpIntra = ctx->cqp;
674 if (avctx->b_quant_factor != 0.0)
675 rc->constQP.qpInterB = av_clip(ctx->cqp * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
676 if (avctx->i_quant_factor != 0.0)
677 rc->constQP.qpIntra = av_clip(ctx->cqp * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
684 static av_cold void set_vbr(AVCodecContext *avctx)
686 NvencContext *ctx = avctx->priv_data;
687 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
690 if (avctx->qmin >= 0 && avctx->qmax >= 0) {
694 rc->minQP.qpInterB = avctx->qmin;
695 rc->minQP.qpInterP = avctx->qmin;
696 rc->minQP.qpIntra = avctx->qmin;
698 rc->maxQP.qpInterB = avctx->qmax;
699 rc->maxQP.qpInterP = avctx->qmax;
700 rc->maxQP.qpIntra = avctx->qmax;
702 qp_inter_p = (avctx->qmax + 3 * avctx->qmin) / 4; // biased towards Qmin
703 } else if (avctx->qmin >= 0) {
706 rc->minQP.qpInterB = avctx->qmin;
707 rc->minQP.qpInterP = avctx->qmin;
708 rc->minQP.qpIntra = avctx->qmin;
710 qp_inter_p = avctx->qmin;
712 qp_inter_p = 26; // default to 26
715 rc->enableInitialRCQP = 1;
717 if (ctx->init_qp_p < 0) {
718 rc->initialRCQP.qpInterP = qp_inter_p;
720 rc->initialRCQP.qpInterP = ctx->init_qp_p;
723 if (ctx->init_qp_i < 0) {
724 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
725 rc->initialRCQP.qpIntra = av_clip(
726 rc->initialRCQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
728 rc->initialRCQP.qpIntra = rc->initialRCQP.qpInterP;
731 rc->initialRCQP.qpIntra = ctx->init_qp_i;
734 if (ctx->init_qp_b < 0) {
735 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
736 rc->initialRCQP.qpInterB = av_clip(
737 rc->initialRCQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
739 rc->initialRCQP.qpInterB = rc->initialRCQP.qpInterP;
742 rc->initialRCQP.qpInterB = ctx->init_qp_b;
746 static av_cold void set_lossless(AVCodecContext *avctx)
748 NvencContext *ctx = avctx->priv_data;
749 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
751 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
752 rc->constQP.qpInterB = 0;
753 rc->constQP.qpInterP = 0;
754 rc->constQP.qpIntra = 0;
760 static void nvenc_override_rate_control(AVCodecContext *avctx)
762 NvencContext *ctx = avctx->priv_data;
763 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
766 case NV_ENC_PARAMS_RC_CONSTQP:
769 case NV_ENC_PARAMS_RC_VBR_MINQP:
770 if (avctx->qmin < 0) {
771 av_log(avctx, AV_LOG_WARNING,
772 "The variable bitrate rate-control requires "
773 "the 'qmin' option set.\n");
778 case NV_ENC_PARAMS_RC_VBR_HQ:
779 case NV_ENC_PARAMS_RC_VBR:
782 case NV_ENC_PARAMS_RC_CBR:
783 case NV_ENC_PARAMS_RC_CBR_HQ:
784 case NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ:
788 rc->rateControlMode = ctx->rc;
791 static av_cold int nvenc_recalc_surfaces(AVCodecContext *avctx)
793 NvencContext *ctx = avctx->priv_data;
794 // default minimum of 4 surfaces
795 // multiply by 2 for number of NVENCs on gpu (hardcode to 2)
796 // another multiply by 2 to avoid blocking next PBB group
797 int nb_surfaces = FFMAX(4, ctx->encode_config.frameIntervalP * 2 * 2);
800 if (ctx->rc_lookahead > 0) {
801 // +1 is to account for lkd_bound calculation later
802 // +4 is to allow sufficient pipelining with lookahead
803 nb_surfaces = FFMAX(1, FFMAX(nb_surfaces, ctx->rc_lookahead + ctx->encode_config.frameIntervalP + 1 + 4));
804 if (nb_surfaces > ctx->nb_surfaces && ctx->nb_surfaces > 0)
806 av_log(avctx, AV_LOG_WARNING,
807 "Defined rc_lookahead requires more surfaces, "
808 "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
810 ctx->nb_surfaces = FFMAX(nb_surfaces, ctx->nb_surfaces);
812 if (ctx->encode_config.frameIntervalP > 1 && ctx->nb_surfaces < nb_surfaces && ctx->nb_surfaces > 0)
814 av_log(avctx, AV_LOG_WARNING,
815 "Defined b-frame requires more surfaces, "
816 "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
817 ctx->nb_surfaces = FFMAX(ctx->nb_surfaces, nb_surfaces);
819 else if (ctx->nb_surfaces <= 0)
820 ctx->nb_surfaces = nb_surfaces;
821 // otherwise use user specified value
824 ctx->nb_surfaces = FFMAX(1, FFMIN(MAX_REGISTERED_FRAMES, ctx->nb_surfaces));
825 ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
830 static av_cold void nvenc_setup_rate_control(AVCodecContext *avctx)
832 NvencContext *ctx = avctx->priv_data;
834 if (avctx->global_quality > 0)
835 av_log(avctx, AV_LOG_WARNING, "Using global_quality with nvenc is deprecated. Use qp instead.\n");
837 if (ctx->cqp < 0 && avctx->global_quality > 0)
838 ctx->cqp = avctx->global_quality;
840 if (avctx->bit_rate > 0) {
841 ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
842 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
843 ctx->encode_config.rcParams.maxBitRate = ctx->encode_config.rcParams.averageBitRate;
846 if (avctx->rc_max_rate > 0)
847 ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
850 if (ctx->flags & NVENC_ONE_PASS)
852 if (ctx->flags & NVENC_TWO_PASSES)
855 if (ctx->twopass < 0)
856 ctx->twopass = (ctx->flags & NVENC_LOWLATENCY) != 0;
860 ctx->rc = NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ;
862 ctx->rc = NV_ENC_PARAMS_RC_CBR;
864 } else if (ctx->cqp >= 0) {
865 ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
866 } else if (ctx->twopass) {
867 ctx->rc = NV_ENC_PARAMS_RC_VBR_HQ;
868 } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
869 ctx->rc = NV_ENC_PARAMS_RC_VBR_MINQP;
873 if (ctx->rc >= 0 && ctx->rc & RC_MODE_DEPRECATED) {
874 av_log(avctx, AV_LOG_WARNING, "Specified rc mode is deprecated.\n");
875 av_log(avctx, AV_LOG_WARNING, "\tll_2pass_quality -> cbr_ld_hq\n");
876 av_log(avctx, AV_LOG_WARNING, "\tll_2pass_size -> cbr_hq\n");
877 av_log(avctx, AV_LOG_WARNING, "\tvbr_2pass -> vbr_hq\n");
878 av_log(avctx, AV_LOG_WARNING, "\tvbr_minqp -> (no replacement)\n");
880 ctx->rc &= ~RC_MODE_DEPRECATED;
883 if (ctx->flags & NVENC_LOSSLESS) {
885 } else if (ctx->rc >= 0) {
886 nvenc_override_rate_control(avctx);
888 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
892 if (avctx->rc_buffer_size > 0) {
893 ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
894 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
895 avctx->rc_buffer_size = ctx->encode_config.rcParams.vbvBufferSize = 2 * ctx->encode_config.rcParams.averageBitRate;
899 ctx->encode_config.rcParams.enableAQ = 1;
900 ctx->encode_config.rcParams.aqStrength = ctx->aq_strength;
901 av_log(avctx, AV_LOG_VERBOSE, "AQ enabled.\n");
904 if (ctx->temporal_aq) {
905 ctx->encode_config.rcParams.enableTemporalAQ = 1;
906 av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ enabled.\n");
909 if (ctx->rc_lookahead > 0) {
910 int lkd_bound = FFMIN(ctx->nb_surfaces, ctx->async_depth) -
911 ctx->encode_config.frameIntervalP - 4;
914 av_log(avctx, AV_LOG_WARNING,
915 "Lookahead not enabled. Increase buffer delay (-delay).\n");
917 ctx->encode_config.rcParams.enableLookahead = 1;
918 ctx->encode_config.rcParams.lookaheadDepth = av_clip(ctx->rc_lookahead, 0, lkd_bound);
919 ctx->encode_config.rcParams.disableIadapt = ctx->no_scenecut;
920 ctx->encode_config.rcParams.disableBadapt = !ctx->b_adapt;
921 av_log(avctx, AV_LOG_VERBOSE,
922 "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",
923 ctx->encode_config.rcParams.lookaheadDepth,
924 ctx->encode_config.rcParams.disableIadapt ? "disabled" : "enabled",
925 ctx->encode_config.rcParams.disableBadapt ? "disabled" : "enabled");
929 if (ctx->strict_gop) {
930 ctx->encode_config.rcParams.strictGOPTarget = 1;
931 av_log(avctx, AV_LOG_VERBOSE, "Strict GOP target enabled.\n");
935 ctx->encode_config.rcParams.enableNonRefP = 1;
937 if (ctx->zerolatency)
938 ctx->encode_config.rcParams.zeroReorderDelay = 1;
942 //convert from float to fixed point 8.8
943 int tmp_quality = (int)(ctx->quality * 256.0f);
944 ctx->encode_config.rcParams.targetQuality = (uint8_t)(tmp_quality >> 8);
945 ctx->encode_config.rcParams.targetQualityLSB = (uint8_t)(tmp_quality & 0xff);
949 static av_cold int nvenc_setup_h264_config(AVCodecContext *avctx)
951 NvencContext *ctx = avctx->priv_data;
952 NV_ENC_CONFIG *cc = &ctx->encode_config;
953 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
954 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
956 vui->colourMatrix = avctx->colorspace;
957 vui->colourPrimaries = avctx->color_primaries;
958 vui->transferCharacteristics = avctx->color_trc;
959 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
960 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
962 vui->colourDescriptionPresentFlag =
963 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
965 vui->videoSignalTypePresentFlag =
966 (vui->colourDescriptionPresentFlag
967 || vui->videoFormat != 5
968 || vui->videoFullRangeFlag != 0);
971 h264->sliceModeData = 1;
973 h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
974 h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
975 h264->outputAUD = ctx->aud;
977 if (ctx->dpb_size >= 0) {
978 /* 0 means "let the hardware decide" */
979 h264->maxNumRefFrames = ctx->dpb_size;
981 if (avctx->gop_size >= 0) {
982 h264->idrPeriod = cc->gopLength;
985 if (IS_CBR(cc->rcParams.rateControlMode)) {
986 h264->outputBufferingPeriodSEI = 1;
989 h264->outputPictureTimingSEI = 1;
991 if (cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ ||
992 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_HQ ||
993 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_VBR_HQ) {
994 h264->adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
995 h264->fmoMode = NV_ENC_H264_FMO_DISABLE;
998 if (ctx->flags & NVENC_LOSSLESS) {
999 h264->qpPrimeYZeroTransformBypassFlag = 1;
1001 switch(ctx->profile) {
1002 case NV_ENC_H264_PROFILE_BASELINE:
1003 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
1004 avctx->profile = FF_PROFILE_H264_BASELINE;
1006 case NV_ENC_H264_PROFILE_MAIN:
1007 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
1008 avctx->profile = FF_PROFILE_H264_MAIN;
1010 case NV_ENC_H264_PROFILE_HIGH:
1011 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
1012 avctx->profile = FF_PROFILE_H264_HIGH;
1014 case NV_ENC_H264_PROFILE_HIGH_444P:
1015 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1016 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
1021 // force setting profile as high444p if input is AV_PIX_FMT_YUV444P
1022 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P) {
1023 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1024 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
1027 h264->chromaFormatIDC = avctx->profile == FF_PROFILE_H264_HIGH_444_PREDICTIVE ? 3 : 1;
1029 h264->level = ctx->level;
1031 if (ctx->coder >= 0)
1032 h264->entropyCodingMode = ctx->coder;
1034 #ifdef NVENC_HAVE_BFRAME_REF_MODE
1035 h264->useBFramesAsRef = ctx->b_ref_mode;
1038 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
1039 h264->numRefL0 = avctx->refs;
1040 h264->numRefL1 = avctx->refs;
1046 static av_cold int nvenc_setup_hevc_config(AVCodecContext *avctx)
1048 NvencContext *ctx = avctx->priv_data;
1049 NV_ENC_CONFIG *cc = &ctx->encode_config;
1050 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
1051 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
1053 vui->colourMatrix = avctx->colorspace;
1054 vui->colourPrimaries = avctx->color_primaries;
1055 vui->transferCharacteristics = avctx->color_trc;
1056 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
1057 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
1059 vui->colourDescriptionPresentFlag =
1060 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
1062 vui->videoSignalTypePresentFlag =
1063 (vui->colourDescriptionPresentFlag
1064 || vui->videoFormat != 5
1065 || vui->videoFullRangeFlag != 0);
1067 hevc->sliceMode = 3;
1068 hevc->sliceModeData = 1;
1070 hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
1071 hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
1072 hevc->outputAUD = ctx->aud;
1074 if (ctx->dpb_size >= 0) {
1075 /* 0 means "let the hardware decide" */
1076 hevc->maxNumRefFramesInDPB = ctx->dpb_size;
1078 if (avctx->gop_size >= 0) {
1079 hevc->idrPeriod = cc->gopLength;
1082 if (IS_CBR(cc->rcParams.rateControlMode)) {
1083 hevc->outputBufferingPeriodSEI = 1;
1086 hevc->outputPictureTimingSEI = 1;
1088 switch (ctx->profile) {
1089 case NV_ENC_HEVC_PROFILE_MAIN:
1090 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
1091 avctx->profile = FF_PROFILE_HEVC_MAIN;
1093 case NV_ENC_HEVC_PROFILE_MAIN_10:
1094 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1095 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
1097 case NV_ENC_HEVC_PROFILE_REXT:
1098 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1099 avctx->profile = FF_PROFILE_HEVC_REXT;
1103 // force setting profile as main10 if input is 10 bit
1104 if (IS_10BIT(ctx->data_pix_fmt)) {
1105 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1106 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
1109 // force setting profile as rext if input is yuv444
1110 if (IS_YUV444(ctx->data_pix_fmt)) {
1111 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1112 avctx->profile = FF_PROFILE_HEVC_REXT;
1115 hevc->chromaFormatIDC = IS_YUV444(ctx->data_pix_fmt) ? 3 : 1;
1117 hevc->pixelBitDepthMinus8 = IS_10BIT(ctx->data_pix_fmt) ? 2 : 0;
1119 hevc->level = ctx->level;
1121 hevc->tier = ctx->tier;
1123 #ifdef NVENC_HAVE_HEVC_BFRAME_REF_MODE
1124 hevc->useBFramesAsRef = ctx->b_ref_mode;
1127 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
1128 hevc->numRefL0 = avctx->refs;
1129 hevc->numRefL1 = avctx->refs;
1135 static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx)
1137 switch (avctx->codec->id) {
1138 case AV_CODEC_ID_H264:
1139 return nvenc_setup_h264_config(avctx);
1140 case AV_CODEC_ID_HEVC:
1141 return nvenc_setup_hevc_config(avctx);
1142 /* Earlier switch/case will return if unknown codec is passed. */
1148 static void compute_dar(AVCodecContext *avctx, int *dw, int *dh) {
1154 if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0) {
1155 sw *= avctx->sample_aspect_ratio.num;
1156 sh *= avctx->sample_aspect_ratio.den;
1159 av_reduce(dw, dh, sw, sh, 1024 * 1024);
1162 static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
1164 NvencContext *ctx = avctx->priv_data;
1165 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1166 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1168 NV_ENC_PRESET_CONFIG preset_config = { 0 };
1169 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
1170 AVCPBProperties *cpb_props;
1174 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1175 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
1177 ctx->init_encode_params.encodeHeight = avctx->height;
1178 ctx->init_encode_params.encodeWidth = avctx->width;
1180 ctx->init_encode_params.encodeConfig = &ctx->encode_config;
1182 nvenc_map_preset(ctx);
1184 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
1185 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
1187 nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder,
1188 ctx->init_encode_params.encodeGUID,
1189 ctx->init_encode_params.presetGUID,
1191 if (nv_status != NV_ENC_SUCCESS)
1192 return nvenc_print_error(avctx, nv_status, "Cannot get the preset configuration");
1194 memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
1196 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1198 compute_dar(avctx, &dw, &dh);
1199 ctx->init_encode_params.darHeight = dh;
1200 ctx->init_encode_params.darWidth = dw;
1202 ctx->init_encode_params.frameRateNum = avctx->time_base.den;
1203 ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
1205 ctx->init_encode_params.enableEncodeAsync = 0;
1206 ctx->init_encode_params.enablePTD = 1;
1208 if (ctx->weighted_pred == 1)
1209 ctx->init_encode_params.enableWeightedPrediction = 1;
1211 if (ctx->bluray_compat) {
1213 ctx->dpb_size = FFMIN(FFMAX(avctx->refs, 0), 6);
1214 avctx->max_b_frames = FFMIN(avctx->max_b_frames, 3);
1215 switch (avctx->codec->id) {
1216 case AV_CODEC_ID_H264:
1217 /* maximum level depends on used resolution */
1219 case AV_CODEC_ID_HEVC:
1220 ctx->level = NV_ENC_LEVEL_HEVC_51;
1221 ctx->tier = NV_ENC_TIER_HEVC_HIGH;
1226 if (avctx->gop_size > 0) {
1227 if (avctx->max_b_frames >= 0) {
1228 /* 0 is intra-only, 1 is I/P only, 2 is one B-Frame, 3 two B-frames, and so on. */
1229 ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
1232 ctx->encode_config.gopLength = avctx->gop_size;
1233 } else if (avctx->gop_size == 0) {
1234 ctx->encode_config.frameIntervalP = 0;
1235 ctx->encode_config.gopLength = 1;
1238 ctx->initial_pts[0] = AV_NOPTS_VALUE;
1239 ctx->initial_pts[1] = AV_NOPTS_VALUE;
1241 nvenc_recalc_surfaces(avctx);
1243 nvenc_setup_rate_control(avctx);
1245 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1246 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
1248 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
1251 res = nvenc_setup_codec_config(avctx);
1255 res = nvenc_push_context(avctx);
1259 nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
1260 if (nv_status != NV_ENC_SUCCESS) {
1261 nvenc_pop_context(avctx);
1262 return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
1265 #ifdef NVENC_HAVE_CUSTREAM_PTR
1266 if (ctx->cu_context) {
1267 nv_status = p_nvenc->nvEncSetIOCudaStreams(ctx->nvencoder, &ctx->cu_stream, &ctx->cu_stream);
1268 if (nv_status != NV_ENC_SUCCESS) {
1269 nvenc_pop_context(avctx);
1270 return nvenc_print_error(avctx, nv_status, "SetIOCudaStreams failed");
1275 res = nvenc_pop_context(avctx);
1279 if (ctx->encode_config.frameIntervalP > 1)
1280 avctx->has_b_frames = 2;
1282 if (ctx->encode_config.rcParams.averageBitRate > 0)
1283 avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
1285 cpb_props = ff_add_cpb_side_data(avctx);
1287 return AVERROR(ENOMEM);
1288 cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
1289 cpb_props->avg_bitrate = avctx->bit_rate;
1290 cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
1295 static NV_ENC_BUFFER_FORMAT nvenc_map_buffer_format(enum AVPixelFormat pix_fmt)
1298 case AV_PIX_FMT_YUV420P:
1299 return NV_ENC_BUFFER_FORMAT_YV12_PL;
1300 case AV_PIX_FMT_NV12:
1301 return NV_ENC_BUFFER_FORMAT_NV12_PL;
1302 case AV_PIX_FMT_P010:
1303 case AV_PIX_FMT_P016:
1304 return NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1305 case AV_PIX_FMT_YUV444P:
1306 return NV_ENC_BUFFER_FORMAT_YUV444_PL;
1307 case AV_PIX_FMT_YUV444P16:
1308 return NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1309 case AV_PIX_FMT_0RGB32:
1310 return NV_ENC_BUFFER_FORMAT_ARGB;
1311 case AV_PIX_FMT_0BGR32:
1312 return NV_ENC_BUFFER_FORMAT_ABGR;
1314 return NV_ENC_BUFFER_FORMAT_UNDEFINED;
1318 static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
1320 NvencContext *ctx = avctx->priv_data;
1321 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1322 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1323 NvencSurface* tmp_surface = &ctx->surfaces[idx];
1325 NVENCSTATUS nv_status;
1326 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
1327 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1329 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1330 ctx->surfaces[idx].in_ref = av_frame_alloc();
1331 if (!ctx->surfaces[idx].in_ref)
1332 return AVERROR(ENOMEM);
1334 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1336 ctx->surfaces[idx].format = nvenc_map_buffer_format(ctx->data_pix_fmt);
1337 if (ctx->surfaces[idx].format == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1338 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1339 av_get_pix_fmt_name(ctx->data_pix_fmt));
1340 return AVERROR(EINVAL);
1343 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1344 allocSurf.width = avctx->width;
1345 allocSurf.height = avctx->height;
1346 allocSurf.bufferFmt = ctx->surfaces[idx].format;
1348 nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
1349 if (nv_status != NV_ENC_SUCCESS) {
1350 return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
1353 ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
1354 ctx->surfaces[idx].width = allocSurf.width;
1355 ctx->surfaces[idx].height = allocSurf.height;
1358 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
1359 if (nv_status != NV_ENC_SUCCESS) {
1360 int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
1361 if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
1362 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
1363 av_frame_free(&ctx->surfaces[idx].in_ref);
1367 ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1368 ctx->surfaces[idx].size = allocOut.size;
1370 av_fifo_generic_write(ctx->unused_surface_queue, &tmp_surface, sizeof(tmp_surface), NULL);
1375 static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx)
1377 NvencContext *ctx = avctx->priv_data;
1378 int i, res = 0, res2;
1380 ctx->surfaces = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->surfaces));
1382 return AVERROR(ENOMEM);
1384 ctx->timestamp_list = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
1385 if (!ctx->timestamp_list)
1386 return AVERROR(ENOMEM);
1388 ctx->unused_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1389 if (!ctx->unused_surface_queue)
1390 return AVERROR(ENOMEM);
1392 ctx->output_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1393 if (!ctx->output_surface_queue)
1394 return AVERROR(ENOMEM);
1395 ctx->output_surface_ready_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1396 if (!ctx->output_surface_ready_queue)
1397 return AVERROR(ENOMEM);
1399 res = nvenc_push_context(avctx);
1403 for (i = 0; i < ctx->nb_surfaces; i++) {
1404 if ((res = nvenc_alloc_surface(avctx, i)) < 0)
1409 res2 = nvenc_pop_context(avctx);
1416 static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
1418 NvencContext *ctx = avctx->priv_data;
1419 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1420 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1422 NVENCSTATUS nv_status;
1423 uint32_t outSize = 0;
1424 char tmpHeader[256];
1425 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1426 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1428 payload.spsppsBuffer = tmpHeader;
1429 payload.inBufferSize = sizeof(tmpHeader);
1430 payload.outSPSPPSPayloadSize = &outSize;
1432 nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
1433 if (nv_status != NV_ENC_SUCCESS) {
1434 return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
1437 avctx->extradata_size = outSize;
1438 avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
1440 if (!avctx->extradata) {
1441 return AVERROR(ENOMEM);
1444 memcpy(avctx->extradata, tmpHeader, outSize);
1449 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
1451 NvencContext *ctx = avctx->priv_data;
1452 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1453 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1456 /* the encoder has to be flushed before it can be closed */
1457 if (ctx->nvencoder) {
1458 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
1459 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
1461 res = nvenc_push_context(avctx);
1465 p_nvenc->nvEncEncodePicture(ctx->nvencoder, ¶ms);
1468 av_fifo_freep(&ctx->timestamp_list);
1469 av_fifo_freep(&ctx->output_surface_ready_queue);
1470 av_fifo_freep(&ctx->output_surface_queue);
1471 av_fifo_freep(&ctx->unused_surface_queue);
1473 if (ctx->surfaces && (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11)) {
1474 for (i = 0; i < ctx->nb_registered_frames; i++) {
1475 if (ctx->registered_frames[i].mapped)
1476 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[i].in_map.mappedResource);
1477 if (ctx->registered_frames[i].regptr)
1478 p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1480 ctx->nb_registered_frames = 0;
1483 if (ctx->surfaces) {
1484 for (i = 0; i < ctx->nb_surfaces; ++i) {
1485 if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
1486 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
1487 av_frame_free(&ctx->surfaces[i].in_ref);
1488 p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
1491 av_freep(&ctx->surfaces);
1492 ctx->nb_surfaces = 0;
1494 if (ctx->nvencoder) {
1495 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1497 res = nvenc_pop_context(avctx);
1501 ctx->nvencoder = NULL;
1503 if (ctx->cu_context_internal)
1504 CHECK_CU(dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal));
1505 ctx->cu_context = ctx->cu_context_internal = NULL;
1508 if (ctx->d3d11_device) {
1509 ID3D11Device_Release(ctx->d3d11_device);
1510 ctx->d3d11_device = NULL;
1514 nvenc_free_functions(&dl_fn->nvenc_dl);
1515 cuda_free_functions(&dl_fn->cuda_dl);
1517 dl_fn->nvenc_device_count = 0;
1519 av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
1524 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
1526 NvencContext *ctx = avctx->priv_data;
1529 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1530 AVHWFramesContext *frames_ctx;
1531 if (!avctx->hw_frames_ctx) {
1532 av_log(avctx, AV_LOG_ERROR,
1533 "hw_frames_ctx must be set when using GPU frames as input\n");
1534 return AVERROR(EINVAL);
1536 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1537 if (frames_ctx->format != avctx->pix_fmt) {
1538 av_log(avctx, AV_LOG_ERROR,
1539 "hw_frames_ctx must match the GPU frame type\n");
1540 return AVERROR(EINVAL);
1542 ctx->data_pix_fmt = frames_ctx->sw_format;
1544 ctx->data_pix_fmt = avctx->pix_fmt;
1547 if ((ret = nvenc_load_libraries(avctx)) < 0)
1550 if ((ret = nvenc_setup_device(avctx)) < 0)
1553 if ((ret = nvenc_setup_encoder(avctx)) < 0)
1556 if ((ret = nvenc_setup_surfaces(avctx)) < 0)
1559 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1560 if ((ret = nvenc_setup_extradata(avctx)) < 0)
1567 static NvencSurface *get_free_frame(NvencContext *ctx)
1569 NvencSurface *tmp_surf;
1571 if (!(av_fifo_size(ctx->unused_surface_queue) > 0))
1575 av_fifo_generic_read(ctx->unused_surface_queue, &tmp_surf, sizeof(tmp_surf), NULL);
1579 static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *nv_surface,
1580 NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params, const AVFrame *frame)
1582 int dst_linesize[4] = {
1583 lock_buffer_params->pitch,
1584 lock_buffer_params->pitch,
1585 lock_buffer_params->pitch,
1586 lock_buffer_params->pitch
1588 uint8_t *dst_data[4];
1591 if (frame->format == AV_PIX_FMT_YUV420P)
1592 dst_linesize[1] = dst_linesize[2] >>= 1;
1594 ret = av_image_fill_pointers(dst_data, frame->format, nv_surface->height,
1595 lock_buffer_params->bufferDataPtr, dst_linesize);
1599 if (frame->format == AV_PIX_FMT_YUV420P)
1600 FFSWAP(uint8_t*, dst_data[1], dst_data[2]);
1602 av_image_copy(dst_data, dst_linesize,
1603 (const uint8_t**)frame->data, frame->linesize, frame->format,
1604 avctx->width, avctx->height);
1609 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1611 NvencContext *ctx = avctx->priv_data;
1612 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1613 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1614 NVENCSTATUS nv_status;
1618 if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1619 for (first_round = 1; first_round >= 0; first_round--) {
1620 for (i = 0; i < ctx->nb_registered_frames; i++) {
1621 if (!ctx->registered_frames[i].mapped) {
1622 if (ctx->registered_frames[i].regptr) {
1625 nv_status = p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1626 if (nv_status != NV_ENC_SUCCESS)
1627 return nvenc_print_error(avctx, nv_status, "Failed unregistering unused input resource");
1628 ctx->registered_frames[i].ptr = NULL;
1629 ctx->registered_frames[i].regptr = NULL;
1636 return ctx->nb_registered_frames++;
1639 av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1640 return AVERROR(ENOMEM);
1643 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1645 NvencContext *ctx = avctx->priv_data;
1646 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1647 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1649 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frame->hw_frames_ctx->data;
1650 NV_ENC_REGISTER_RESOURCE reg;
1653 for (i = 0; i < ctx->nb_registered_frames; i++) {
1654 if (avctx->pix_fmt == AV_PIX_FMT_CUDA && ctx->registered_frames[i].ptr == frame->data[0])
1656 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])
1660 idx = nvenc_find_free_reg_resource(avctx);
1664 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1665 reg.width = frames_ctx->width;
1666 reg.height = frames_ctx->height;
1667 reg.pitch = frame->linesize[0];
1668 reg.resourceToRegister = frame->data[0];
1670 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1671 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1673 else if (avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1674 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX;
1675 reg.subResourceIndex = (intptr_t)frame->data[1];
1678 reg.bufferFormat = nvenc_map_buffer_format(frames_ctx->sw_format);
1679 if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1680 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1681 av_get_pix_fmt_name(frames_ctx->sw_format));
1682 return AVERROR(EINVAL);
1685 ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, ®);
1686 if (ret != NV_ENC_SUCCESS) {
1687 nvenc_print_error(avctx, ret, "Error registering an input resource");
1688 return AVERROR_UNKNOWN;
1691 ctx->registered_frames[idx].ptr = frame->data[0];
1692 ctx->registered_frames[idx].ptr_index = reg.subResourceIndex;
1693 ctx->registered_frames[idx].regptr = reg.registeredResource;
1697 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1698 NvencSurface *nvenc_frame)
1700 NvencContext *ctx = avctx->priv_data;
1701 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1702 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1705 NVENCSTATUS nv_status;
1707 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1708 int reg_idx = nvenc_register_frame(avctx, frame);
1710 av_log(avctx, AV_LOG_ERROR, "Could not register an input HW frame\n");
1714 res = av_frame_ref(nvenc_frame->in_ref, frame);
1718 if (!ctx->registered_frames[reg_idx].mapped) {
1719 ctx->registered_frames[reg_idx].in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1720 ctx->registered_frames[reg_idx].in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1721 nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &ctx->registered_frames[reg_idx].in_map);
1722 if (nv_status != NV_ENC_SUCCESS) {
1723 av_frame_unref(nvenc_frame->in_ref);
1724 return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
1728 ctx->registered_frames[reg_idx].mapped += 1;
1730 nvenc_frame->reg_idx = reg_idx;
1731 nvenc_frame->input_surface = ctx->registered_frames[reg_idx].in_map.mappedResource;
1732 nvenc_frame->format = ctx->registered_frames[reg_idx].in_map.mappedBufferFmt;
1733 nvenc_frame->pitch = frame->linesize[0];
1737 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1739 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1740 lockBufferParams.inputBuffer = nvenc_frame->input_surface;
1742 nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
1743 if (nv_status != NV_ENC_SUCCESS) {
1744 return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
1747 nvenc_frame->pitch = lockBufferParams.pitch;
1748 res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
1750 nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
1751 if (nv_status != NV_ENC_SUCCESS) {
1752 return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
1759 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1760 NV_ENC_PIC_PARAMS *params,
1761 NV_ENC_SEI_PAYLOAD *sei_data)
1763 NvencContext *ctx = avctx->priv_data;
1765 switch (avctx->codec->id) {
1766 case AV_CODEC_ID_H264:
1767 params->codecPicParams.h264PicParams.sliceMode =
1768 ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1769 params->codecPicParams.h264PicParams.sliceModeData =
1770 ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1772 params->codecPicParams.h264PicParams.seiPayloadArray = sei_data;
1773 params->codecPicParams.h264PicParams.seiPayloadArrayCnt = 1;
1777 case AV_CODEC_ID_HEVC:
1778 params->codecPicParams.hevcPicParams.sliceMode =
1779 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1780 params->codecPicParams.hevcPicParams.sliceModeData =
1781 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1783 params->codecPicParams.hevcPicParams.seiPayloadArray = sei_data;
1784 params->codecPicParams.hevcPicParams.seiPayloadArrayCnt = 1;
1791 static inline void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
1793 av_fifo_generic_write(queue, ×tamp, sizeof(timestamp), NULL);
1796 static inline int64_t timestamp_queue_dequeue(AVFifoBuffer* queue)
1798 int64_t timestamp = AV_NOPTS_VALUE;
1799 if (av_fifo_size(queue) > 0)
1800 av_fifo_generic_read(queue, ×tamp, sizeof(timestamp), NULL);
1805 static int nvenc_set_timestamp(AVCodecContext *avctx,
1806 NV_ENC_LOCK_BITSTREAM *params,
1809 NvencContext *ctx = avctx->priv_data;
1811 pkt->pts = params->outputTimeStamp;
1813 /* generate the first dts by linearly extrapolating the
1814 * first two pts values to the past */
1815 if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
1816 ctx->initial_pts[1] != AV_NOPTS_VALUE) {
1817 int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
1820 if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
1821 (ts0 > 0 && ts1 < INT64_MIN + ts0))
1822 return AVERROR(ERANGE);
1825 if ((delta < 0 && ts0 > INT64_MAX + delta) ||
1826 (delta > 0 && ts0 < INT64_MIN + delta))
1827 return AVERROR(ERANGE);
1828 pkt->dts = ts0 - delta;
1830 ctx->first_packet_output = 1;
1834 pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
1839 static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
1841 NvencContext *ctx = avctx->priv_data;
1842 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1843 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1845 uint32_t slice_mode_data;
1846 uint32_t *slice_offsets = NULL;
1847 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1848 NVENCSTATUS nv_status;
1851 enum AVPictureType pict_type;
1853 switch (avctx->codec->id) {
1854 case AV_CODEC_ID_H264:
1855 slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1857 case AV_CODEC_ID_H265:
1858 slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1861 av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
1862 res = AVERROR(EINVAL);
1865 slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
1867 if (!slice_offsets) {
1868 res = AVERROR(ENOMEM);
1872 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1874 lock_params.doNotWait = 0;
1875 lock_params.outputBitstream = tmpoutsurf->output_surface;
1876 lock_params.sliceOffsets = slice_offsets;
1878 nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
1879 if (nv_status != NV_ENC_SUCCESS) {
1880 res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
1885 ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes, lock_params.bitstreamSizeInBytes) :
1886 av_new_packet(pkt, lock_params.bitstreamSizeInBytes);
1889 p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1893 memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1895 nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1896 if (nv_status != NV_ENC_SUCCESS) {
1897 res = nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
1902 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1903 ctx->registered_frames[tmpoutsurf->reg_idx].mapped -= 1;
1904 if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped == 0) {
1905 nv_status = p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[tmpoutsurf->reg_idx].in_map.mappedResource);
1906 if (nv_status != NV_ENC_SUCCESS) {
1907 res = nvenc_print_error(avctx, nv_status, "Failed unmapping input resource");
1910 } else if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped < 0) {
1915 av_frame_unref(tmpoutsurf->in_ref);
1917 tmpoutsurf->input_surface = NULL;
1920 switch (lock_params.pictureType) {
1921 case NV_ENC_PIC_TYPE_IDR:
1922 pkt->flags |= AV_PKT_FLAG_KEY;
1923 case NV_ENC_PIC_TYPE_I:
1924 pict_type = AV_PICTURE_TYPE_I;
1926 case NV_ENC_PIC_TYPE_P:
1927 pict_type = AV_PICTURE_TYPE_P;
1929 case NV_ENC_PIC_TYPE_B:
1930 pict_type = AV_PICTURE_TYPE_B;
1932 case NV_ENC_PIC_TYPE_BI:
1933 pict_type = AV_PICTURE_TYPE_BI;
1936 av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
1937 av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
1938 res = AVERROR_EXTERNAL;
1942 #if FF_API_CODED_FRAME
1943 FF_DISABLE_DEPRECATION_WARNINGS
1944 avctx->coded_frame->pict_type = pict_type;
1945 FF_ENABLE_DEPRECATION_WARNINGS
1948 ff_side_data_set_encoder_stats(pkt,
1949 (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
1951 res = nvenc_set_timestamp(avctx, &lock_params, pkt);
1955 av_free(slice_offsets);
1960 timestamp_queue_dequeue(ctx->timestamp_list);
1963 av_free(slice_offsets);
1968 static int output_ready(AVCodecContext *avctx, int flush)
1970 NvencContext *ctx = avctx->priv_data;
1971 int nb_ready, nb_pending;
1973 /* when B-frames are enabled, we wait for two initial timestamps to
1974 * calculate the first dts */
1975 if (!flush && avctx->max_b_frames > 0 &&
1976 (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
1979 nb_ready = av_fifo_size(ctx->output_surface_ready_queue) / sizeof(NvencSurface*);
1980 nb_pending = av_fifo_size(ctx->output_surface_queue) / sizeof(NvencSurface*);
1982 return nb_ready > 0;
1983 return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
1986 static void reconfig_encoder(AVCodecContext *avctx, const AVFrame *frame)
1988 NvencContext *ctx = avctx->priv_data;
1989 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
1992 NV_ENC_RECONFIGURE_PARAMS params = { 0 };
1993 int needs_reconfig = 0;
1994 int needs_encode_config = 0;
1995 int reconfig_bitrate = 0, reconfig_dar = 0;
1998 params.version = NV_ENC_RECONFIGURE_PARAMS_VER;
1999 params.reInitEncodeParams = ctx->init_encode_params;
2001 compute_dar(avctx, &dw, &dh);
2002 if (dw != ctx->init_encode_params.darWidth || dh != ctx->init_encode_params.darHeight) {
2003 av_log(avctx, AV_LOG_VERBOSE,
2004 "aspect ratio change (DAR): %d:%d -> %d:%d\n",
2005 ctx->init_encode_params.darWidth,
2006 ctx->init_encode_params.darHeight, dw, dh);
2008 params.reInitEncodeParams.darHeight = dh;
2009 params.reInitEncodeParams.darWidth = dw;
2015 if (ctx->rc != NV_ENC_PARAMS_RC_CONSTQP && ctx->support_dyn_bitrate) {
2016 if (avctx->bit_rate > 0 && params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate != avctx->bit_rate) {
2017 av_log(avctx, AV_LOG_VERBOSE,
2018 "avg bitrate change: %d -> %d\n",
2019 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate,
2020 (uint32_t)avctx->bit_rate);
2022 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate = avctx->bit_rate;
2023 reconfig_bitrate = 1;
2026 if (avctx->rc_max_rate > 0 && ctx->encode_config.rcParams.maxBitRate != avctx->rc_max_rate) {
2027 av_log(avctx, AV_LOG_VERBOSE,
2028 "max bitrate change: %d -> %d\n",
2029 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate,
2030 (uint32_t)avctx->rc_max_rate);
2032 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate = avctx->rc_max_rate;
2033 reconfig_bitrate = 1;
2036 if (avctx->rc_buffer_size > 0 && ctx->encode_config.rcParams.vbvBufferSize != avctx->rc_buffer_size) {
2037 av_log(avctx, AV_LOG_VERBOSE,
2038 "vbv buffer size change: %d -> %d\n",
2039 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize,
2040 avctx->rc_buffer_size);
2042 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize = avctx->rc_buffer_size;
2043 reconfig_bitrate = 1;
2046 if (reconfig_bitrate) {
2047 params.resetEncoder = 1;
2048 params.forceIDR = 1;
2050 needs_encode_config = 1;
2055 if (!needs_encode_config)
2056 params.reInitEncodeParams.encodeConfig = NULL;
2058 if (needs_reconfig) {
2059 ret = p_nvenc->nvEncReconfigureEncoder(ctx->nvencoder, ¶ms);
2060 if (ret != NV_ENC_SUCCESS) {
2061 nvenc_print_error(avctx, ret, "failed to reconfigure nvenc");
2064 ctx->init_encode_params.darHeight = dh;
2065 ctx->init_encode_params.darWidth = dw;
2068 if (reconfig_bitrate) {
2069 ctx->encode_config.rcParams.averageBitRate = params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate;
2070 ctx->encode_config.rcParams.maxBitRate = params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate;
2071 ctx->encode_config.rcParams.vbvBufferSize = params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize;
2078 int ff_nvenc_send_frame(AVCodecContext *avctx, const AVFrame *frame)
2080 NVENCSTATUS nv_status;
2081 NvencSurface *tmp_out_surf, *in_surf;
2083 NV_ENC_SEI_PAYLOAD *sei_data = NULL;
2086 NvencContext *ctx = avctx->priv_data;
2087 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
2088 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
2090 NV_ENC_PIC_PARAMS pic_params = { 0 };
2091 pic_params.version = NV_ENC_PIC_PARAMS_VER;
2093 if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
2094 return AVERROR(EINVAL);
2096 if (ctx->encoder_flushing) {
2097 if (avctx->internal->draining)
2100 ctx->encoder_flushing = 0;
2101 ctx->first_packet_output = 0;
2102 ctx->initial_pts[0] = AV_NOPTS_VALUE;
2103 ctx->initial_pts[1] = AV_NOPTS_VALUE;
2104 av_fifo_reset(ctx->timestamp_list);
2108 in_surf = get_free_frame(ctx);
2110 return AVERROR(EAGAIN);
2112 res = nvenc_push_context(avctx);
2116 reconfig_encoder(avctx, frame);
2118 res = nvenc_upload_frame(avctx, frame, in_surf);
2120 res2 = nvenc_pop_context(avctx);
2127 pic_params.inputBuffer = in_surf->input_surface;
2128 pic_params.bufferFmt = in_surf->format;
2129 pic_params.inputWidth = in_surf->width;
2130 pic_params.inputHeight = in_surf->height;
2131 pic_params.inputPitch = in_surf->pitch;
2132 pic_params.outputBitstream = in_surf->output_surface;
2134 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
2135 if (frame->top_field_first)
2136 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
2138 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
2140 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
2143 if (ctx->forced_idr >= 0 && frame->pict_type == AV_PICTURE_TYPE_I) {
2144 pic_params.encodePicFlags =
2145 ctx->forced_idr ? NV_ENC_PIC_FLAG_FORCEIDR : NV_ENC_PIC_FLAG_FORCEINTRA;
2147 pic_params.encodePicFlags = 0;
2150 pic_params.inputTimeStamp = frame->pts;
2152 if (ctx->a53_cc && av_frame_get_side_data(frame, AV_FRAME_DATA_A53_CC)) {
2153 if (ff_alloc_a53_sei(frame, sizeof(NV_ENC_SEI_PAYLOAD), (void**)&sei_data, &sei_size) < 0) {
2154 av_log(ctx, AV_LOG_ERROR, "Not enough memory for closed captions, skipping\n");
2158 sei_data->payloadSize = (uint32_t)sei_size;
2159 sei_data->payloadType = 4;
2160 sei_data->payload = (uint8_t*)(sei_data + 1);
2164 nvenc_codec_specific_pic_params(avctx, &pic_params, sei_data);
2166 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
2167 ctx->encoder_flushing = 1;
2170 res = nvenc_push_context(avctx);
2174 nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
2177 res = nvenc_pop_context(avctx);
2181 if (nv_status != NV_ENC_SUCCESS &&
2182 nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
2183 return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
2186 av_fifo_generic_write(ctx->output_surface_queue, &in_surf, sizeof(in_surf), NULL);
2187 timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
2189 if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
2190 ctx->initial_pts[0] = frame->pts;
2191 else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
2192 ctx->initial_pts[1] = frame->pts;
2195 /* all the pending buffers are now ready for output */
2196 if (nv_status == NV_ENC_SUCCESS) {
2197 while (av_fifo_size(ctx->output_surface_queue) > 0) {
2198 av_fifo_generic_read(ctx->output_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2199 av_fifo_generic_write(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2206 int ff_nvenc_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
2208 NvencSurface *tmp_out_surf;
2211 NvencContext *ctx = avctx->priv_data;
2213 if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
2214 return AVERROR(EINVAL);
2216 if (output_ready(avctx, ctx->encoder_flushing)) {
2217 av_fifo_generic_read(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2219 res = nvenc_push_context(avctx);
2223 res = process_output_surface(avctx, pkt, tmp_out_surf);
2225 res2 = nvenc_pop_context(avctx);
2232 av_fifo_generic_write(ctx->unused_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2233 } else if (ctx->encoder_flushing) {
2236 return AVERROR(EAGAIN);
2242 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
2243 const AVFrame *frame, int *got_packet)
2245 NvencContext *ctx = avctx->priv_data;
2248 if (!ctx->encoder_flushing) {
2249 res = ff_nvenc_send_frame(avctx, frame);
2254 res = ff_nvenc_receive_packet(avctx, pkt);
2255 if (res == AVERROR(EAGAIN) || res == AVERROR_EOF) {
2257 } else if (res < 0) {
2266 av_cold void ff_nvenc_encode_flush(AVCodecContext *avctx)
2268 ff_nvenc_send_frame(avctx, NULL);