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 const AVCodecHWConfigInternal *ff_nvenc_hw_configs[] = {
59 HW_CONFIG_ENCODER_FRAMES(CUDA, CUDA),
60 HW_CONFIG_ENCODER_DEVICE(NONE, CUDA),
62 HW_CONFIG_ENCODER_FRAMES(D3D11, D3D11VA),
63 HW_CONFIG_ENCODER_DEVICE(NONE, D3D11VA),
68 #define IS_10BIT(pix_fmt) (pix_fmt == AV_PIX_FMT_P010 || \
69 pix_fmt == AV_PIX_FMT_P016 || \
70 pix_fmt == AV_PIX_FMT_YUV444P16)
72 #define IS_YUV444(pix_fmt) (pix_fmt == AV_PIX_FMT_YUV444P || \
73 pix_fmt == AV_PIX_FMT_YUV444P16)
80 { NV_ENC_SUCCESS, 0, "success" },
81 { NV_ENC_ERR_NO_ENCODE_DEVICE, AVERROR(ENOENT), "no encode device" },
82 { NV_ENC_ERR_UNSUPPORTED_DEVICE, AVERROR(ENOSYS), "unsupported device" },
83 { NV_ENC_ERR_INVALID_ENCODERDEVICE, AVERROR(EINVAL), "invalid encoder device" },
84 { NV_ENC_ERR_INVALID_DEVICE, AVERROR(EINVAL), "invalid device" },
85 { NV_ENC_ERR_DEVICE_NOT_EXIST, AVERROR(EIO), "device does not exist" },
86 { NV_ENC_ERR_INVALID_PTR, AVERROR(EFAULT), "invalid ptr" },
87 { NV_ENC_ERR_INVALID_EVENT, AVERROR(EINVAL), "invalid event" },
88 { NV_ENC_ERR_INVALID_PARAM, AVERROR(EINVAL), "invalid param" },
89 { NV_ENC_ERR_INVALID_CALL, AVERROR(EINVAL), "invalid call" },
90 { NV_ENC_ERR_OUT_OF_MEMORY, AVERROR(ENOMEM), "out of memory" },
91 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED, AVERROR(EINVAL), "encoder not initialized" },
92 { NV_ENC_ERR_UNSUPPORTED_PARAM, AVERROR(ENOSYS), "unsupported param" },
93 { NV_ENC_ERR_LOCK_BUSY, AVERROR(EAGAIN), "lock busy" },
94 { NV_ENC_ERR_NOT_ENOUGH_BUFFER, AVERROR_BUFFER_TOO_SMALL, "not enough buffer"},
95 { NV_ENC_ERR_INVALID_VERSION, AVERROR(EINVAL), "invalid version" },
96 { NV_ENC_ERR_MAP_FAILED, AVERROR(EIO), "map failed" },
97 { NV_ENC_ERR_NEED_MORE_INPUT, AVERROR(EAGAIN), "need more input" },
98 { NV_ENC_ERR_ENCODER_BUSY, AVERROR(EAGAIN), "encoder busy" },
99 { NV_ENC_ERR_EVENT_NOT_REGISTERD, AVERROR(EBADF), "event not registered" },
100 { NV_ENC_ERR_GENERIC, AVERROR_UNKNOWN, "generic error" },
101 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY, AVERROR(EINVAL), "incompatible client key" },
102 { NV_ENC_ERR_UNIMPLEMENTED, AVERROR(ENOSYS), "unimplemented" },
103 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO), "resource register failed" },
104 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED, AVERROR(EBADF), "resource not registered" },
105 { NV_ENC_ERR_RESOURCE_NOT_MAPPED, AVERROR(EBADF), "resource not mapped" },
108 static int nvenc_map_error(NVENCSTATUS err, const char **desc)
111 for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
112 if (nvenc_errors[i].nverr == err) {
114 *desc = nvenc_errors[i].desc;
115 return nvenc_errors[i].averr;
119 *desc = "unknown error";
120 return AVERROR_UNKNOWN;
123 static int nvenc_print_error(AVCodecContext *avctx, NVENCSTATUS err,
124 const char *error_string)
127 const char *details = "(no details)";
128 int ret = nvenc_map_error(err, &desc);
130 #ifdef NVENC_HAVE_GETLASTERRORSTRING
131 NvencContext *ctx = avctx->priv_data;
132 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
134 if (p_nvenc && ctx->nvencoder)
135 details = p_nvenc->nvEncGetLastErrorString(ctx->nvencoder);
138 av_log(avctx, AV_LOG_ERROR, "%s: %s (%d): %s\n", error_string, desc, err, details);
143 static void nvenc_print_driver_requirement(AVCodecContext *avctx, int level)
145 #if NVENCAPI_CHECK_VERSION(9, 2)
146 const char *minver = "(unknown)";
147 #elif NVENCAPI_CHECK_VERSION(9, 1)
148 # if defined(_WIN32) || defined(__CYGWIN__)
149 const char *minver = "436.15";
151 const char *minver = "435.21";
153 #elif NVENCAPI_CHECK_VERSION(9, 0)
154 # if defined(_WIN32) || defined(__CYGWIN__)
155 const char *minver = "418.81";
157 const char *minver = "418.30";
159 #elif NVENCAPI_CHECK_VERSION(8, 2)
160 # if defined(_WIN32) || defined(__CYGWIN__)
161 const char *minver = "397.93";
163 const char *minver = "396.24";
165 #elif NVENCAPI_CHECK_VERSION(8, 1)
166 # if defined(_WIN32) || defined(__CYGWIN__)
167 const char *minver = "390.77";
169 const char *minver = "390.25";
172 # if defined(_WIN32) || defined(__CYGWIN__)
173 const char *minver = "378.66";
175 const char *minver = "378.13";
178 av_log(avctx, level, "The minimum required Nvidia driver for nvenc is %s or newer\n", minver);
181 static av_cold int nvenc_load_libraries(AVCodecContext *avctx)
183 NvencContext *ctx = avctx->priv_data;
184 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
186 uint32_t nvenc_max_ver;
189 ret = cuda_load_functions(&dl_fn->cuda_dl, avctx);
193 ret = nvenc_load_functions(&dl_fn->nvenc_dl, avctx);
195 nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
199 err = dl_fn->nvenc_dl->NvEncodeAPIGetMaxSupportedVersion(&nvenc_max_ver);
200 if (err != NV_ENC_SUCCESS)
201 return nvenc_print_error(avctx, err, "Failed to query nvenc max version");
203 av_log(avctx, AV_LOG_VERBOSE, "Loaded Nvenc version %d.%d\n", nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
205 if ((NVENCAPI_MAJOR_VERSION << 4 | NVENCAPI_MINOR_VERSION) > nvenc_max_ver) {
206 av_log(avctx, AV_LOG_ERROR, "Driver does not support the required nvenc API version. "
207 "Required: %d.%d Found: %d.%d\n",
208 NVENCAPI_MAJOR_VERSION, NVENCAPI_MINOR_VERSION,
209 nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
210 nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
211 return AVERROR(ENOSYS);
214 dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
216 err = dl_fn->nvenc_dl->NvEncodeAPICreateInstance(&dl_fn->nvenc_funcs);
217 if (err != NV_ENC_SUCCESS)
218 return nvenc_print_error(avctx, err, "Failed to create nvenc instance");
220 av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
225 static int nvenc_push_context(AVCodecContext *avctx)
227 NvencContext *ctx = avctx->priv_data;
228 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
230 if (ctx->d3d11_device)
233 return CHECK_CU(dl_fn->cuda_dl->cuCtxPushCurrent(ctx->cu_context));
236 static int nvenc_pop_context(AVCodecContext *avctx)
238 NvencContext *ctx = avctx->priv_data;
239 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
242 if (ctx->d3d11_device)
245 return CHECK_CU(dl_fn->cuda_dl->cuCtxPopCurrent(&dummy));
248 static av_cold int nvenc_open_session(AVCodecContext *avctx)
250 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
251 NvencContext *ctx = avctx->priv_data;
252 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
255 params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
256 params.apiVersion = NVENCAPI_VERSION;
257 if (ctx->d3d11_device) {
258 params.device = ctx->d3d11_device;
259 params.deviceType = NV_ENC_DEVICE_TYPE_DIRECTX;
261 params.device = ctx->cu_context;
262 params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
265 ret = p_nvenc->nvEncOpenEncodeSessionEx(¶ms, &ctx->nvencoder);
266 if (ret != NV_ENC_SUCCESS) {
267 ctx->nvencoder = NULL;
268 return nvenc_print_error(avctx, ret, "OpenEncodeSessionEx failed");
274 static int nvenc_check_codec_support(AVCodecContext *avctx)
276 NvencContext *ctx = avctx->priv_data;
277 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
278 int i, ret, count = 0;
281 ret = p_nvenc->nvEncGetEncodeGUIDCount(ctx->nvencoder, &count);
283 if (ret != NV_ENC_SUCCESS || !count)
284 return AVERROR(ENOSYS);
286 guids = av_malloc(count * sizeof(GUID));
288 return AVERROR(ENOMEM);
290 ret = p_nvenc->nvEncGetEncodeGUIDs(ctx->nvencoder, guids, count, &count);
291 if (ret != NV_ENC_SUCCESS) {
292 ret = AVERROR(ENOSYS);
296 ret = AVERROR(ENOSYS);
297 for (i = 0; i < count; i++) {
298 if (!memcmp(&guids[i], &ctx->init_encode_params.encodeGUID, sizeof(*guids))) {
310 static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
312 NvencContext *ctx = avctx->priv_data;
313 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
314 NV_ENC_CAPS_PARAM params = { 0 };
317 params.version = NV_ENC_CAPS_PARAM_VER;
318 params.capsToQuery = cap;
320 ret = p_nvenc->nvEncGetEncodeCaps(ctx->nvencoder, ctx->init_encode_params.encodeGUID, ¶ms, &val);
322 if (ret == NV_ENC_SUCCESS)
327 static int nvenc_check_capabilities(AVCodecContext *avctx)
329 NvencContext *ctx = avctx->priv_data;
332 ret = nvenc_check_codec_support(avctx);
334 av_log(avctx, AV_LOG_WARNING, "Codec not supported\n");
338 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
339 if (IS_YUV444(ctx->data_pix_fmt) && ret <= 0) {
340 av_log(avctx, AV_LOG_WARNING, "YUV444P not supported\n");
341 return AVERROR(ENOSYS);
344 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOSSLESS_ENCODE);
345 if (ctx->preset >= PRESET_LOSSLESS_DEFAULT && ret <= 0) {
346 av_log(avctx, AV_LOG_WARNING, "Lossless encoding not supported\n");
347 return AVERROR(ENOSYS);
350 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
351 if (ret < avctx->width) {
352 av_log(avctx, AV_LOG_WARNING, "Width %d exceeds %d\n",
354 return AVERROR(ENOSYS);
357 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
358 if (ret < avctx->height) {
359 av_log(avctx, AV_LOG_WARNING, "Height %d exceeds %d\n",
361 return AVERROR(ENOSYS);
364 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
365 if (ret < avctx->max_b_frames) {
366 av_log(avctx, AV_LOG_WARNING, "Max B-frames %d exceed %d\n",
367 avctx->max_b_frames, ret);
369 return AVERROR(ENOSYS);
372 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_FIELD_ENCODING);
373 if (ret < 1 && avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
374 av_log(avctx, AV_LOG_WARNING,
375 "Interlaced encoding is not supported. Supported level: %d\n",
377 return AVERROR(ENOSYS);
380 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_10BIT_ENCODE);
381 if (IS_10BIT(ctx->data_pix_fmt) && ret <= 0) {
382 av_log(avctx, AV_LOG_WARNING, "10 bit encode not supported\n");
383 return AVERROR(ENOSYS);
386 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOOKAHEAD);
387 if (ctx->rc_lookahead > 0 && ret <= 0) {
388 av_log(avctx, AV_LOG_WARNING, "RC lookahead not supported\n");
389 return AVERROR(ENOSYS);
392 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_TEMPORAL_AQ);
393 if (ctx->temporal_aq > 0 && ret <= 0) {
394 av_log(avctx, AV_LOG_WARNING, "Temporal AQ not supported\n");
395 return AVERROR(ENOSYS);
398 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_WEIGHTED_PREDICTION);
399 if (ctx->weighted_pred > 0 && ret <= 0) {
400 av_log (avctx, AV_LOG_WARNING, "Weighted Prediction not supported\n");
401 return AVERROR(ENOSYS);
404 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_CABAC);
405 if (ctx->coder == NV_ENC_H264_ENTROPY_CODING_MODE_CABAC && ret <= 0) {
406 av_log(avctx, AV_LOG_WARNING, "CABAC entropy coding not supported\n");
407 return AVERROR(ENOSYS);
410 #ifdef NVENC_HAVE_BFRAME_REF_MODE
411 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_BFRAME_REF_MODE);
412 if (ctx->b_ref_mode == NV_ENC_BFRAME_REF_MODE_EACH && ret != 1) {
413 av_log(avctx, AV_LOG_WARNING, "Each B frame as reference is not supported\n");
414 return AVERROR(ENOSYS);
415 } else if (ctx->b_ref_mode != NV_ENC_BFRAME_REF_MODE_DISABLED && ret == 0) {
416 av_log(avctx, AV_LOG_WARNING, "B frames as references are not supported\n");
417 return AVERROR(ENOSYS);
420 if (ctx->b_ref_mode != 0) {
421 av_log(avctx, AV_LOG_WARNING, "B frames as references need SDK 8.1 at build time\n");
422 return AVERROR(ENOSYS);
426 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
427 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_MULTIPLE_REF_FRAMES);
428 if(avctx->refs != NV_ENC_NUM_REF_FRAMES_AUTOSELECT && ret <= 0) {
429 av_log(avctx, AV_LOG_WARNING, "Multiple reference frames are not supported by the device\n");
430 return AVERROR(ENOSYS);
433 if(avctx->refs != 0) {
434 av_log(avctx, AV_LOG_WARNING, "Multiple reference frames need SDK 9.1 at build time\n");
435 return AVERROR(ENOSYS);
439 ctx->support_dyn_bitrate = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_DYN_BITRATE_CHANGE);
444 static av_cold int nvenc_check_device(AVCodecContext *avctx, int idx)
446 NvencContext *ctx = avctx->priv_data;
447 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
448 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
449 char name[128] = { 0};
450 int major, minor, ret;
452 int loglevel = AV_LOG_VERBOSE;
454 if (ctx->device == LIST_DEVICES)
455 loglevel = AV_LOG_INFO;
457 ret = CHECK_CU(dl_fn->cuda_dl->cuDeviceGet(&cu_device, idx));
461 ret = CHECK_CU(dl_fn->cuda_dl->cuDeviceGetName(name, sizeof(name), cu_device));
465 ret = CHECK_CU(dl_fn->cuda_dl->cuDeviceComputeCapability(&major, &minor, cu_device));
469 av_log(avctx, loglevel, "[ GPU #%d - < %s > has Compute SM %d.%d ]\n", idx, name, major, minor);
470 if (((major << 4) | minor) < NVENC_CAP) {
471 av_log(avctx, loglevel, "does not support NVENC\n");
475 if (ctx->device != idx && ctx->device != ANY_DEVICE)
478 ret = CHECK_CU(dl_fn->cuda_dl->cuCtxCreate(&ctx->cu_context_internal, 0, cu_device));
482 ctx->cu_context = ctx->cu_context_internal;
483 ctx->cu_stream = NULL;
485 if ((ret = nvenc_pop_context(avctx)) < 0)
488 if ((ret = nvenc_open_session(avctx)) < 0)
491 if ((ret = nvenc_check_capabilities(avctx)) < 0)
494 av_log(avctx, loglevel, "supports NVENC\n");
496 dl_fn->nvenc_device_count++;
498 if (ctx->device == idx || ctx->device == ANY_DEVICE)
502 if ((ret = nvenc_push_context(avctx)) < 0)
505 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
506 ctx->nvencoder = NULL;
508 if ((ret = nvenc_pop_context(avctx)) < 0)
512 CHECK_CU(dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal));
513 ctx->cu_context_internal = NULL;
516 return AVERROR(ENOSYS);
519 static av_cold int nvenc_setup_device(AVCodecContext *avctx)
521 NvencContext *ctx = avctx->priv_data;
522 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
524 switch (avctx->codec->id) {
525 case AV_CODEC_ID_H264:
526 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
528 case AV_CODEC_ID_HEVC:
529 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
535 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11 || avctx->hw_frames_ctx || avctx->hw_device_ctx) {
536 AVHWFramesContext *frames_ctx;
537 AVHWDeviceContext *hwdev_ctx;
538 AVCUDADeviceContext *cuda_device_hwctx = NULL;
540 AVD3D11VADeviceContext *d3d11_device_hwctx = NULL;
544 if (avctx->hw_frames_ctx) {
545 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
546 if (frames_ctx->format == AV_PIX_FMT_CUDA)
547 cuda_device_hwctx = frames_ctx->device_ctx->hwctx;
549 else if (frames_ctx->format == AV_PIX_FMT_D3D11)
550 d3d11_device_hwctx = frames_ctx->device_ctx->hwctx;
553 return AVERROR(EINVAL);
554 } else if (avctx->hw_device_ctx) {
555 hwdev_ctx = (AVHWDeviceContext*)avctx->hw_device_ctx->data;
556 if (hwdev_ctx->type == AV_HWDEVICE_TYPE_CUDA)
557 cuda_device_hwctx = hwdev_ctx->hwctx;
559 else if (hwdev_ctx->type == AV_HWDEVICE_TYPE_D3D11VA)
560 d3d11_device_hwctx = hwdev_ctx->hwctx;
563 return AVERROR(EINVAL);
565 return AVERROR(EINVAL);
568 if (cuda_device_hwctx) {
569 ctx->cu_context = cuda_device_hwctx->cuda_ctx;
570 ctx->cu_stream = cuda_device_hwctx->stream;
573 else if (d3d11_device_hwctx) {
574 ctx->d3d11_device = d3d11_device_hwctx->device;
575 ID3D11Device_AddRef(ctx->d3d11_device);
579 ret = nvenc_open_session(avctx);
583 ret = nvenc_check_capabilities(avctx);
585 av_log(avctx, AV_LOG_FATAL, "Provided device doesn't support required NVENC features\n");
589 int i, nb_devices = 0;
591 if (CHECK_CU(dl_fn->cuda_dl->cuInit(0)) < 0)
592 return AVERROR_UNKNOWN;
594 if (CHECK_CU(dl_fn->cuda_dl->cuDeviceGetCount(&nb_devices)) < 0)
595 return AVERROR_UNKNOWN;
598 av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
599 return AVERROR_EXTERNAL;
602 av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", nb_devices);
604 dl_fn->nvenc_device_count = 0;
605 for (i = 0; i < nb_devices; ++i) {
606 if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
610 if (ctx->device == LIST_DEVICES)
613 if (!dl_fn->nvenc_device_count) {
614 av_log(avctx, AV_LOG_FATAL, "No capable devices found\n");
615 return AVERROR_EXTERNAL;
618 av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->device, nb_devices);
619 return AVERROR(EINVAL);
625 typedef struct GUIDTuple {
630 #define PRESET_ALIAS(alias, name, ...) \
631 [PRESET_ ## alias] = { NV_ENC_PRESET_ ## name ## _GUID, __VA_ARGS__ }
633 #define PRESET(name, ...) PRESET_ALIAS(name, name, __VA_ARGS__)
635 static void nvenc_map_preset(NvencContext *ctx)
637 GUIDTuple presets[] = {
642 PRESET_ALIAS(SLOW, HQ, NVENC_TWO_PASSES),
643 PRESET_ALIAS(MEDIUM, HQ, NVENC_ONE_PASS),
644 PRESET_ALIAS(FAST, HP, NVENC_ONE_PASS),
645 PRESET(LOW_LATENCY_DEFAULT, NVENC_LOWLATENCY),
646 PRESET(LOW_LATENCY_HP, NVENC_LOWLATENCY),
647 PRESET(LOW_LATENCY_HQ, NVENC_LOWLATENCY),
648 PRESET(LOSSLESS_DEFAULT, NVENC_LOSSLESS),
649 PRESET(LOSSLESS_HP, NVENC_LOSSLESS),
652 GUIDTuple *t = &presets[ctx->preset];
654 ctx->init_encode_params.presetGUID = t->guid;
655 ctx->flags = t->flags;
661 static av_cold void set_constqp(AVCodecContext *avctx)
663 NvencContext *ctx = avctx->priv_data;
664 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
666 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
668 if (ctx->init_qp_p >= 0) {
669 rc->constQP.qpInterP = ctx->init_qp_p;
670 if (ctx->init_qp_i >= 0 && ctx->init_qp_b >= 0) {
671 rc->constQP.qpIntra = ctx->init_qp_i;
672 rc->constQP.qpInterB = ctx->init_qp_b;
673 } else if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
674 rc->constQP.qpIntra = av_clip(
675 rc->constQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
676 rc->constQP.qpInterB = av_clip(
677 rc->constQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
679 rc->constQP.qpIntra = rc->constQP.qpInterP;
680 rc->constQP.qpInterB = rc->constQP.qpInterP;
682 } else if (ctx->cqp >= 0) {
683 rc->constQP.qpInterP = rc->constQP.qpInterB = rc->constQP.qpIntra = ctx->cqp;
684 if (avctx->b_quant_factor != 0.0)
685 rc->constQP.qpInterB = av_clip(ctx->cqp * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
686 if (avctx->i_quant_factor != 0.0)
687 rc->constQP.qpIntra = av_clip(ctx->cqp * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
694 static av_cold void set_vbr(AVCodecContext *avctx)
696 NvencContext *ctx = avctx->priv_data;
697 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
700 if (avctx->qmin >= 0 && avctx->qmax >= 0) {
704 rc->minQP.qpInterB = avctx->qmin;
705 rc->minQP.qpInterP = avctx->qmin;
706 rc->minQP.qpIntra = avctx->qmin;
708 rc->maxQP.qpInterB = avctx->qmax;
709 rc->maxQP.qpInterP = avctx->qmax;
710 rc->maxQP.qpIntra = avctx->qmax;
712 qp_inter_p = (avctx->qmax + 3 * avctx->qmin) / 4; // biased towards Qmin
713 } else if (avctx->qmin >= 0) {
716 rc->minQP.qpInterB = avctx->qmin;
717 rc->minQP.qpInterP = avctx->qmin;
718 rc->minQP.qpIntra = avctx->qmin;
720 qp_inter_p = avctx->qmin;
722 qp_inter_p = 26; // default to 26
725 rc->enableInitialRCQP = 1;
727 if (ctx->init_qp_p < 0) {
728 rc->initialRCQP.qpInterP = qp_inter_p;
730 rc->initialRCQP.qpInterP = ctx->init_qp_p;
733 if (ctx->init_qp_i < 0) {
734 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
735 rc->initialRCQP.qpIntra = av_clip(
736 rc->initialRCQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
738 rc->initialRCQP.qpIntra = rc->initialRCQP.qpInterP;
741 rc->initialRCQP.qpIntra = ctx->init_qp_i;
744 if (ctx->init_qp_b < 0) {
745 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
746 rc->initialRCQP.qpInterB = av_clip(
747 rc->initialRCQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
749 rc->initialRCQP.qpInterB = rc->initialRCQP.qpInterP;
752 rc->initialRCQP.qpInterB = ctx->init_qp_b;
756 static av_cold void set_lossless(AVCodecContext *avctx)
758 NvencContext *ctx = avctx->priv_data;
759 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
761 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
762 rc->constQP.qpInterB = 0;
763 rc->constQP.qpInterP = 0;
764 rc->constQP.qpIntra = 0;
770 static void nvenc_override_rate_control(AVCodecContext *avctx)
772 NvencContext *ctx = avctx->priv_data;
773 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
776 case NV_ENC_PARAMS_RC_CONSTQP:
779 case NV_ENC_PARAMS_RC_VBR_MINQP:
780 if (avctx->qmin < 0) {
781 av_log(avctx, AV_LOG_WARNING,
782 "The variable bitrate rate-control requires "
783 "the 'qmin' option set.\n");
788 case NV_ENC_PARAMS_RC_VBR_HQ:
789 case NV_ENC_PARAMS_RC_VBR:
792 case NV_ENC_PARAMS_RC_CBR:
793 case NV_ENC_PARAMS_RC_CBR_HQ:
794 case NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ:
798 rc->rateControlMode = ctx->rc;
801 static av_cold int nvenc_recalc_surfaces(AVCodecContext *avctx)
803 NvencContext *ctx = avctx->priv_data;
804 // default minimum of 4 surfaces
805 // multiply by 2 for number of NVENCs on gpu (hardcode to 2)
806 // another multiply by 2 to avoid blocking next PBB group
807 int nb_surfaces = FFMAX(4, ctx->encode_config.frameIntervalP * 2 * 2);
810 if (ctx->rc_lookahead > 0) {
811 // +1 is to account for lkd_bound calculation later
812 // +4 is to allow sufficient pipelining with lookahead
813 nb_surfaces = FFMAX(1, FFMAX(nb_surfaces, ctx->rc_lookahead + ctx->encode_config.frameIntervalP + 1 + 4));
814 if (nb_surfaces > ctx->nb_surfaces && ctx->nb_surfaces > 0)
816 av_log(avctx, AV_LOG_WARNING,
817 "Defined rc_lookahead requires more surfaces, "
818 "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
820 ctx->nb_surfaces = FFMAX(nb_surfaces, ctx->nb_surfaces);
822 if (ctx->encode_config.frameIntervalP > 1 && ctx->nb_surfaces < nb_surfaces && ctx->nb_surfaces > 0)
824 av_log(avctx, AV_LOG_WARNING,
825 "Defined b-frame requires more surfaces, "
826 "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
827 ctx->nb_surfaces = FFMAX(ctx->nb_surfaces, nb_surfaces);
829 else if (ctx->nb_surfaces <= 0)
830 ctx->nb_surfaces = nb_surfaces;
831 // otherwise use user specified value
834 ctx->nb_surfaces = FFMAX(1, FFMIN(MAX_REGISTERED_FRAMES, ctx->nb_surfaces));
835 ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
840 static av_cold void nvenc_setup_rate_control(AVCodecContext *avctx)
842 NvencContext *ctx = avctx->priv_data;
844 if (avctx->global_quality > 0)
845 av_log(avctx, AV_LOG_WARNING, "Using global_quality with nvenc is deprecated. Use qp instead.\n");
847 if (ctx->cqp < 0 && avctx->global_quality > 0)
848 ctx->cqp = avctx->global_quality;
850 if (avctx->bit_rate > 0) {
851 ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
852 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
853 ctx->encode_config.rcParams.maxBitRate = ctx->encode_config.rcParams.averageBitRate;
856 if (avctx->rc_max_rate > 0)
857 ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
860 if (ctx->flags & NVENC_ONE_PASS)
862 if (ctx->flags & NVENC_TWO_PASSES)
865 if (ctx->twopass < 0)
866 ctx->twopass = (ctx->flags & NVENC_LOWLATENCY) != 0;
870 ctx->rc = NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ;
872 ctx->rc = NV_ENC_PARAMS_RC_CBR;
874 } else if (ctx->cqp >= 0) {
875 ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
876 } else if (ctx->twopass) {
877 ctx->rc = NV_ENC_PARAMS_RC_VBR_HQ;
878 } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
879 ctx->rc = NV_ENC_PARAMS_RC_VBR_MINQP;
883 if (ctx->rc >= 0 && ctx->rc & RC_MODE_DEPRECATED) {
884 av_log(avctx, AV_LOG_WARNING, "Specified rc mode is deprecated.\n");
885 av_log(avctx, AV_LOG_WARNING, "\tll_2pass_quality -> cbr_ld_hq\n");
886 av_log(avctx, AV_LOG_WARNING, "\tll_2pass_size -> cbr_hq\n");
887 av_log(avctx, AV_LOG_WARNING, "\tvbr_2pass -> vbr_hq\n");
888 av_log(avctx, AV_LOG_WARNING, "\tvbr_minqp -> (no replacement)\n");
890 ctx->rc &= ~RC_MODE_DEPRECATED;
893 if (ctx->flags & NVENC_LOSSLESS) {
895 } else if (ctx->rc >= 0) {
896 nvenc_override_rate_control(avctx);
898 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
902 if (avctx->rc_buffer_size > 0) {
903 ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
904 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
905 avctx->rc_buffer_size = ctx->encode_config.rcParams.vbvBufferSize = 2 * ctx->encode_config.rcParams.averageBitRate;
909 ctx->encode_config.rcParams.enableAQ = 1;
910 ctx->encode_config.rcParams.aqStrength = ctx->aq_strength;
911 av_log(avctx, AV_LOG_VERBOSE, "AQ enabled.\n");
914 if (ctx->temporal_aq) {
915 ctx->encode_config.rcParams.enableTemporalAQ = 1;
916 av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ enabled.\n");
919 if (ctx->rc_lookahead > 0) {
920 int lkd_bound = FFMIN(ctx->nb_surfaces, ctx->async_depth) -
921 ctx->encode_config.frameIntervalP - 4;
924 av_log(avctx, AV_LOG_WARNING,
925 "Lookahead not enabled. Increase buffer delay (-delay).\n");
927 ctx->encode_config.rcParams.enableLookahead = 1;
928 ctx->encode_config.rcParams.lookaheadDepth = av_clip(ctx->rc_lookahead, 0, lkd_bound);
929 ctx->encode_config.rcParams.disableIadapt = ctx->no_scenecut;
930 ctx->encode_config.rcParams.disableBadapt = !ctx->b_adapt;
931 av_log(avctx, AV_LOG_VERBOSE,
932 "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",
933 ctx->encode_config.rcParams.lookaheadDepth,
934 ctx->encode_config.rcParams.disableIadapt ? "disabled" : "enabled",
935 ctx->encode_config.rcParams.disableBadapt ? "disabled" : "enabled");
939 if (ctx->strict_gop) {
940 ctx->encode_config.rcParams.strictGOPTarget = 1;
941 av_log(avctx, AV_LOG_VERBOSE, "Strict GOP target enabled.\n");
945 ctx->encode_config.rcParams.enableNonRefP = 1;
947 if (ctx->zerolatency)
948 ctx->encode_config.rcParams.zeroReorderDelay = 1;
952 //convert from float to fixed point 8.8
953 int tmp_quality = (int)(ctx->quality * 256.0f);
954 ctx->encode_config.rcParams.targetQuality = (uint8_t)(tmp_quality >> 8);
955 ctx->encode_config.rcParams.targetQualityLSB = (uint8_t)(tmp_quality & 0xff);
959 static av_cold int nvenc_setup_h264_config(AVCodecContext *avctx)
961 NvencContext *ctx = avctx->priv_data;
962 NV_ENC_CONFIG *cc = &ctx->encode_config;
963 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
964 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
966 vui->colourMatrix = avctx->colorspace;
967 vui->colourPrimaries = avctx->color_primaries;
968 vui->transferCharacteristics = avctx->color_trc;
969 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
970 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
972 vui->colourDescriptionPresentFlag =
973 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
975 vui->videoSignalTypePresentFlag =
976 (vui->colourDescriptionPresentFlag
977 || vui->videoFormat != 5
978 || vui->videoFullRangeFlag != 0);
981 h264->sliceModeData = 1;
983 h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
984 h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
985 h264->outputAUD = ctx->aud;
987 if (ctx->dpb_size >= 0) {
988 /* 0 means "let the hardware decide" */
989 h264->maxNumRefFrames = ctx->dpb_size;
991 if (avctx->gop_size >= 0) {
992 h264->idrPeriod = cc->gopLength;
995 if (IS_CBR(cc->rcParams.rateControlMode)) {
996 h264->outputBufferingPeriodSEI = 1;
999 h264->outputPictureTimingSEI = 1;
1001 if (cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ ||
1002 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_HQ ||
1003 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_VBR_HQ) {
1004 h264->adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
1005 h264->fmoMode = NV_ENC_H264_FMO_DISABLE;
1008 if (ctx->flags & NVENC_LOSSLESS) {
1009 h264->qpPrimeYZeroTransformBypassFlag = 1;
1011 switch(ctx->profile) {
1012 case NV_ENC_H264_PROFILE_BASELINE:
1013 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
1014 avctx->profile = FF_PROFILE_H264_BASELINE;
1016 case NV_ENC_H264_PROFILE_MAIN:
1017 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
1018 avctx->profile = FF_PROFILE_H264_MAIN;
1020 case NV_ENC_H264_PROFILE_HIGH:
1021 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
1022 avctx->profile = FF_PROFILE_H264_HIGH;
1024 case NV_ENC_H264_PROFILE_HIGH_444P:
1025 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1026 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
1031 // force setting profile as high444p if input is AV_PIX_FMT_YUV444P
1032 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P) {
1033 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1034 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
1037 h264->chromaFormatIDC = avctx->profile == FF_PROFILE_H264_HIGH_444_PREDICTIVE ? 3 : 1;
1039 h264->level = ctx->level;
1041 if (ctx->coder >= 0)
1042 h264->entropyCodingMode = ctx->coder;
1044 #ifdef NVENC_HAVE_BFRAME_REF_MODE
1045 h264->useBFramesAsRef = ctx->b_ref_mode;
1048 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
1049 h264->numRefL0 = avctx->refs;
1050 h264->numRefL1 = avctx->refs;
1056 static av_cold int nvenc_setup_hevc_config(AVCodecContext *avctx)
1058 NvencContext *ctx = avctx->priv_data;
1059 NV_ENC_CONFIG *cc = &ctx->encode_config;
1060 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
1061 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
1063 vui->colourMatrix = avctx->colorspace;
1064 vui->colourPrimaries = avctx->color_primaries;
1065 vui->transferCharacteristics = avctx->color_trc;
1066 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
1067 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
1069 vui->colourDescriptionPresentFlag =
1070 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
1072 vui->videoSignalTypePresentFlag =
1073 (vui->colourDescriptionPresentFlag
1074 || vui->videoFormat != 5
1075 || vui->videoFullRangeFlag != 0);
1077 hevc->sliceMode = 3;
1078 hevc->sliceModeData = 1;
1080 hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
1081 hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
1082 hevc->outputAUD = ctx->aud;
1084 if (ctx->dpb_size >= 0) {
1085 /* 0 means "let the hardware decide" */
1086 hevc->maxNumRefFramesInDPB = ctx->dpb_size;
1088 if (avctx->gop_size >= 0) {
1089 hevc->idrPeriod = cc->gopLength;
1092 if (IS_CBR(cc->rcParams.rateControlMode)) {
1093 hevc->outputBufferingPeriodSEI = 1;
1096 hevc->outputPictureTimingSEI = 1;
1098 switch (ctx->profile) {
1099 case NV_ENC_HEVC_PROFILE_MAIN:
1100 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
1101 avctx->profile = FF_PROFILE_HEVC_MAIN;
1103 case NV_ENC_HEVC_PROFILE_MAIN_10:
1104 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1105 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
1107 case NV_ENC_HEVC_PROFILE_REXT:
1108 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1109 avctx->profile = FF_PROFILE_HEVC_REXT;
1113 // force setting profile as main10 if input is 10 bit
1114 if (IS_10BIT(ctx->data_pix_fmt)) {
1115 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1116 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
1119 // force setting profile as rext if input is yuv444
1120 if (IS_YUV444(ctx->data_pix_fmt)) {
1121 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1122 avctx->profile = FF_PROFILE_HEVC_REXT;
1125 hevc->chromaFormatIDC = IS_YUV444(ctx->data_pix_fmt) ? 3 : 1;
1127 hevc->pixelBitDepthMinus8 = IS_10BIT(ctx->data_pix_fmt) ? 2 : 0;
1129 hevc->level = ctx->level;
1131 hevc->tier = ctx->tier;
1133 #ifdef NVENC_HAVE_HEVC_BFRAME_REF_MODE
1134 hevc->useBFramesAsRef = ctx->b_ref_mode;
1137 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
1138 hevc->numRefL0 = avctx->refs;
1139 hevc->numRefL1 = avctx->refs;
1145 static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx)
1147 switch (avctx->codec->id) {
1148 case AV_CODEC_ID_H264:
1149 return nvenc_setup_h264_config(avctx);
1150 case AV_CODEC_ID_HEVC:
1151 return nvenc_setup_hevc_config(avctx);
1152 /* Earlier switch/case will return if unknown codec is passed. */
1158 static void compute_dar(AVCodecContext *avctx, int *dw, int *dh) {
1164 if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0) {
1165 sw *= avctx->sample_aspect_ratio.num;
1166 sh *= avctx->sample_aspect_ratio.den;
1169 av_reduce(dw, dh, sw, sh, 1024 * 1024);
1172 static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
1174 NvencContext *ctx = avctx->priv_data;
1175 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1176 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1178 NV_ENC_PRESET_CONFIG preset_config = { 0 };
1179 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
1180 AVCPBProperties *cpb_props;
1184 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1185 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
1187 ctx->init_encode_params.encodeHeight = avctx->height;
1188 ctx->init_encode_params.encodeWidth = avctx->width;
1190 ctx->init_encode_params.encodeConfig = &ctx->encode_config;
1192 nvenc_map_preset(ctx);
1194 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
1195 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
1197 nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder,
1198 ctx->init_encode_params.encodeGUID,
1199 ctx->init_encode_params.presetGUID,
1201 if (nv_status != NV_ENC_SUCCESS)
1202 return nvenc_print_error(avctx, nv_status, "Cannot get the preset configuration");
1204 memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
1206 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1208 compute_dar(avctx, &dw, &dh);
1209 ctx->init_encode_params.darHeight = dh;
1210 ctx->init_encode_params.darWidth = dw;
1212 ctx->init_encode_params.frameRateNum = avctx->time_base.den;
1213 ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
1215 ctx->init_encode_params.enableEncodeAsync = 0;
1216 ctx->init_encode_params.enablePTD = 1;
1218 if (ctx->weighted_pred == 1)
1219 ctx->init_encode_params.enableWeightedPrediction = 1;
1221 if (ctx->bluray_compat) {
1223 ctx->dpb_size = FFMIN(FFMAX(avctx->refs, 0), 6);
1224 avctx->max_b_frames = FFMIN(avctx->max_b_frames, 3);
1225 switch (avctx->codec->id) {
1226 case AV_CODEC_ID_H264:
1227 /* maximum level depends on used resolution */
1229 case AV_CODEC_ID_HEVC:
1230 ctx->level = NV_ENC_LEVEL_HEVC_51;
1231 ctx->tier = NV_ENC_TIER_HEVC_HIGH;
1236 if (avctx->gop_size > 0) {
1237 if (avctx->max_b_frames >= 0) {
1238 /* 0 is intra-only, 1 is I/P only, 2 is one B-Frame, 3 two B-frames, and so on. */
1239 ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
1242 ctx->encode_config.gopLength = avctx->gop_size;
1243 } else if (avctx->gop_size == 0) {
1244 ctx->encode_config.frameIntervalP = 0;
1245 ctx->encode_config.gopLength = 1;
1248 ctx->initial_pts[0] = AV_NOPTS_VALUE;
1249 ctx->initial_pts[1] = AV_NOPTS_VALUE;
1251 nvenc_recalc_surfaces(avctx);
1253 nvenc_setup_rate_control(avctx);
1255 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1256 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
1258 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
1261 res = nvenc_setup_codec_config(avctx);
1265 res = nvenc_push_context(avctx);
1269 nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
1270 if (nv_status != NV_ENC_SUCCESS) {
1271 nvenc_pop_context(avctx);
1272 return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
1275 #ifdef NVENC_HAVE_CUSTREAM_PTR
1276 if (ctx->cu_context) {
1277 nv_status = p_nvenc->nvEncSetIOCudaStreams(ctx->nvencoder, &ctx->cu_stream, &ctx->cu_stream);
1278 if (nv_status != NV_ENC_SUCCESS) {
1279 nvenc_pop_context(avctx);
1280 return nvenc_print_error(avctx, nv_status, "SetIOCudaStreams failed");
1285 res = nvenc_pop_context(avctx);
1289 if (ctx->encode_config.frameIntervalP > 1)
1290 avctx->has_b_frames = 2;
1292 if (ctx->encode_config.rcParams.averageBitRate > 0)
1293 avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
1295 cpb_props = ff_add_cpb_side_data(avctx);
1297 return AVERROR(ENOMEM);
1298 cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
1299 cpb_props->avg_bitrate = avctx->bit_rate;
1300 cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
1305 static NV_ENC_BUFFER_FORMAT nvenc_map_buffer_format(enum AVPixelFormat pix_fmt)
1308 case AV_PIX_FMT_YUV420P:
1309 return NV_ENC_BUFFER_FORMAT_YV12_PL;
1310 case AV_PIX_FMT_NV12:
1311 return NV_ENC_BUFFER_FORMAT_NV12_PL;
1312 case AV_PIX_FMT_P010:
1313 case AV_PIX_FMT_P016:
1314 return NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1315 case AV_PIX_FMT_YUV444P:
1316 return NV_ENC_BUFFER_FORMAT_YUV444_PL;
1317 case AV_PIX_FMT_YUV444P16:
1318 return NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1319 case AV_PIX_FMT_0RGB32:
1320 return NV_ENC_BUFFER_FORMAT_ARGB;
1321 case AV_PIX_FMT_0BGR32:
1322 return NV_ENC_BUFFER_FORMAT_ABGR;
1324 return NV_ENC_BUFFER_FORMAT_UNDEFINED;
1328 static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
1330 NvencContext *ctx = avctx->priv_data;
1331 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1332 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1333 NvencSurface* tmp_surface = &ctx->surfaces[idx];
1335 NVENCSTATUS nv_status;
1336 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
1337 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1339 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1340 ctx->surfaces[idx].in_ref = av_frame_alloc();
1341 if (!ctx->surfaces[idx].in_ref)
1342 return AVERROR(ENOMEM);
1344 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1346 ctx->surfaces[idx].format = nvenc_map_buffer_format(ctx->data_pix_fmt);
1347 if (ctx->surfaces[idx].format == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1348 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1349 av_get_pix_fmt_name(ctx->data_pix_fmt));
1350 return AVERROR(EINVAL);
1353 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1354 allocSurf.width = avctx->width;
1355 allocSurf.height = avctx->height;
1356 allocSurf.bufferFmt = ctx->surfaces[idx].format;
1358 nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
1359 if (nv_status != NV_ENC_SUCCESS) {
1360 return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
1363 ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
1364 ctx->surfaces[idx].width = allocSurf.width;
1365 ctx->surfaces[idx].height = allocSurf.height;
1368 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
1369 if (nv_status != NV_ENC_SUCCESS) {
1370 int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
1371 if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
1372 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
1373 av_frame_free(&ctx->surfaces[idx].in_ref);
1377 ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1378 ctx->surfaces[idx].size = allocOut.size;
1380 av_fifo_generic_write(ctx->unused_surface_queue, &tmp_surface, sizeof(tmp_surface), NULL);
1385 static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx)
1387 NvencContext *ctx = avctx->priv_data;
1388 int i, res = 0, res2;
1390 ctx->surfaces = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->surfaces));
1392 return AVERROR(ENOMEM);
1394 ctx->timestamp_list = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
1395 if (!ctx->timestamp_list)
1396 return AVERROR(ENOMEM);
1398 ctx->unused_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1399 if (!ctx->unused_surface_queue)
1400 return AVERROR(ENOMEM);
1402 ctx->output_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1403 if (!ctx->output_surface_queue)
1404 return AVERROR(ENOMEM);
1405 ctx->output_surface_ready_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1406 if (!ctx->output_surface_ready_queue)
1407 return AVERROR(ENOMEM);
1409 res = nvenc_push_context(avctx);
1413 for (i = 0; i < ctx->nb_surfaces; i++) {
1414 if ((res = nvenc_alloc_surface(avctx, i)) < 0)
1419 res2 = nvenc_pop_context(avctx);
1426 static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
1428 NvencContext *ctx = avctx->priv_data;
1429 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1430 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1432 NVENCSTATUS nv_status;
1433 uint32_t outSize = 0;
1434 char tmpHeader[256];
1435 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1436 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1438 payload.spsppsBuffer = tmpHeader;
1439 payload.inBufferSize = sizeof(tmpHeader);
1440 payload.outSPSPPSPayloadSize = &outSize;
1442 nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
1443 if (nv_status != NV_ENC_SUCCESS) {
1444 return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
1447 avctx->extradata_size = outSize;
1448 avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
1450 if (!avctx->extradata) {
1451 return AVERROR(ENOMEM);
1454 memcpy(avctx->extradata, tmpHeader, outSize);
1459 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
1461 NvencContext *ctx = avctx->priv_data;
1462 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1463 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1466 /* the encoder has to be flushed before it can be closed */
1467 if (ctx->nvencoder) {
1468 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
1469 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
1471 res = nvenc_push_context(avctx);
1475 p_nvenc->nvEncEncodePicture(ctx->nvencoder, ¶ms);
1478 av_fifo_freep(&ctx->timestamp_list);
1479 av_fifo_freep(&ctx->output_surface_ready_queue);
1480 av_fifo_freep(&ctx->output_surface_queue);
1481 av_fifo_freep(&ctx->unused_surface_queue);
1483 if (ctx->surfaces && (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11)) {
1484 for (i = 0; i < ctx->nb_registered_frames; i++) {
1485 if (ctx->registered_frames[i].mapped)
1486 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[i].in_map.mappedResource);
1487 if (ctx->registered_frames[i].regptr)
1488 p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1490 ctx->nb_registered_frames = 0;
1493 if (ctx->surfaces) {
1494 for (i = 0; i < ctx->nb_surfaces; ++i) {
1495 if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
1496 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
1497 av_frame_free(&ctx->surfaces[i].in_ref);
1498 p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
1501 av_freep(&ctx->surfaces);
1502 ctx->nb_surfaces = 0;
1504 if (ctx->nvencoder) {
1505 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1507 res = nvenc_pop_context(avctx);
1511 ctx->nvencoder = NULL;
1513 if (ctx->cu_context_internal)
1514 CHECK_CU(dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal));
1515 ctx->cu_context = ctx->cu_context_internal = NULL;
1518 if (ctx->d3d11_device) {
1519 ID3D11Device_Release(ctx->d3d11_device);
1520 ctx->d3d11_device = NULL;
1524 nvenc_free_functions(&dl_fn->nvenc_dl);
1525 cuda_free_functions(&dl_fn->cuda_dl);
1527 dl_fn->nvenc_device_count = 0;
1529 av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
1534 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
1536 NvencContext *ctx = avctx->priv_data;
1539 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1540 AVHWFramesContext *frames_ctx;
1541 if (!avctx->hw_frames_ctx) {
1542 av_log(avctx, AV_LOG_ERROR,
1543 "hw_frames_ctx must be set when using GPU frames as input\n");
1544 return AVERROR(EINVAL);
1546 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1547 if (frames_ctx->format != avctx->pix_fmt) {
1548 av_log(avctx, AV_LOG_ERROR,
1549 "hw_frames_ctx must match the GPU frame type\n");
1550 return AVERROR(EINVAL);
1552 ctx->data_pix_fmt = frames_ctx->sw_format;
1554 ctx->data_pix_fmt = avctx->pix_fmt;
1557 if ((ret = nvenc_load_libraries(avctx)) < 0)
1560 if ((ret = nvenc_setup_device(avctx)) < 0)
1563 if ((ret = nvenc_setup_encoder(avctx)) < 0)
1566 if ((ret = nvenc_setup_surfaces(avctx)) < 0)
1569 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1570 if ((ret = nvenc_setup_extradata(avctx)) < 0)
1577 static NvencSurface *get_free_frame(NvencContext *ctx)
1579 NvencSurface *tmp_surf;
1581 if (!(av_fifo_size(ctx->unused_surface_queue) > 0))
1585 av_fifo_generic_read(ctx->unused_surface_queue, &tmp_surf, sizeof(tmp_surf), NULL);
1589 static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *nv_surface,
1590 NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params, const AVFrame *frame)
1592 int dst_linesize[4] = {
1593 lock_buffer_params->pitch,
1594 lock_buffer_params->pitch,
1595 lock_buffer_params->pitch,
1596 lock_buffer_params->pitch
1598 uint8_t *dst_data[4];
1601 if (frame->format == AV_PIX_FMT_YUV420P)
1602 dst_linesize[1] = dst_linesize[2] >>= 1;
1604 ret = av_image_fill_pointers(dst_data, frame->format, nv_surface->height,
1605 lock_buffer_params->bufferDataPtr, dst_linesize);
1609 if (frame->format == AV_PIX_FMT_YUV420P)
1610 FFSWAP(uint8_t*, dst_data[1], dst_data[2]);
1612 av_image_copy(dst_data, dst_linesize,
1613 (const uint8_t**)frame->data, frame->linesize, frame->format,
1614 avctx->width, avctx->height);
1619 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1621 NvencContext *ctx = avctx->priv_data;
1622 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1623 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1624 NVENCSTATUS nv_status;
1628 if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1629 for (first_round = 1; first_round >= 0; first_round--) {
1630 for (i = 0; i < ctx->nb_registered_frames; i++) {
1631 if (!ctx->registered_frames[i].mapped) {
1632 if (ctx->registered_frames[i].regptr) {
1635 nv_status = p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1636 if (nv_status != NV_ENC_SUCCESS)
1637 return nvenc_print_error(avctx, nv_status, "Failed unregistering unused input resource");
1638 ctx->registered_frames[i].ptr = NULL;
1639 ctx->registered_frames[i].regptr = NULL;
1646 return ctx->nb_registered_frames++;
1649 av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1650 return AVERROR(ENOMEM);
1653 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1655 NvencContext *ctx = avctx->priv_data;
1656 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1657 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1659 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frame->hw_frames_ctx->data;
1660 NV_ENC_REGISTER_RESOURCE reg;
1663 for (i = 0; i < ctx->nb_registered_frames; i++) {
1664 if (avctx->pix_fmt == AV_PIX_FMT_CUDA && ctx->registered_frames[i].ptr == frame->data[0])
1666 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])
1670 idx = nvenc_find_free_reg_resource(avctx);
1674 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1675 reg.width = frames_ctx->width;
1676 reg.height = frames_ctx->height;
1677 reg.pitch = frame->linesize[0];
1678 reg.resourceToRegister = frame->data[0];
1680 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1681 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1683 else if (avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1684 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX;
1685 reg.subResourceIndex = (intptr_t)frame->data[1];
1688 reg.bufferFormat = nvenc_map_buffer_format(frames_ctx->sw_format);
1689 if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1690 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1691 av_get_pix_fmt_name(frames_ctx->sw_format));
1692 return AVERROR(EINVAL);
1695 ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, ®);
1696 if (ret != NV_ENC_SUCCESS) {
1697 nvenc_print_error(avctx, ret, "Error registering an input resource");
1698 return AVERROR_UNKNOWN;
1701 ctx->registered_frames[idx].ptr = frame->data[0];
1702 ctx->registered_frames[idx].ptr_index = reg.subResourceIndex;
1703 ctx->registered_frames[idx].regptr = reg.registeredResource;
1707 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1708 NvencSurface *nvenc_frame)
1710 NvencContext *ctx = avctx->priv_data;
1711 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1712 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1715 NVENCSTATUS nv_status;
1717 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1718 int reg_idx = nvenc_register_frame(avctx, frame);
1720 av_log(avctx, AV_LOG_ERROR, "Could not register an input HW frame\n");
1724 res = av_frame_ref(nvenc_frame->in_ref, frame);
1728 if (!ctx->registered_frames[reg_idx].mapped) {
1729 ctx->registered_frames[reg_idx].in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1730 ctx->registered_frames[reg_idx].in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1731 nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &ctx->registered_frames[reg_idx].in_map);
1732 if (nv_status != NV_ENC_SUCCESS) {
1733 av_frame_unref(nvenc_frame->in_ref);
1734 return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
1738 ctx->registered_frames[reg_idx].mapped += 1;
1740 nvenc_frame->reg_idx = reg_idx;
1741 nvenc_frame->input_surface = ctx->registered_frames[reg_idx].in_map.mappedResource;
1742 nvenc_frame->format = ctx->registered_frames[reg_idx].in_map.mappedBufferFmt;
1743 nvenc_frame->pitch = frame->linesize[0];
1747 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1749 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1750 lockBufferParams.inputBuffer = nvenc_frame->input_surface;
1752 nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
1753 if (nv_status != NV_ENC_SUCCESS) {
1754 return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
1757 nvenc_frame->pitch = lockBufferParams.pitch;
1758 res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
1760 nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
1761 if (nv_status != NV_ENC_SUCCESS) {
1762 return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
1769 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1770 NV_ENC_PIC_PARAMS *params,
1771 NV_ENC_SEI_PAYLOAD *sei_data)
1773 NvencContext *ctx = avctx->priv_data;
1775 switch (avctx->codec->id) {
1776 case AV_CODEC_ID_H264:
1777 params->codecPicParams.h264PicParams.sliceMode =
1778 ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1779 params->codecPicParams.h264PicParams.sliceModeData =
1780 ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1782 params->codecPicParams.h264PicParams.seiPayloadArray = sei_data;
1783 params->codecPicParams.h264PicParams.seiPayloadArrayCnt = 1;
1787 case AV_CODEC_ID_HEVC:
1788 params->codecPicParams.hevcPicParams.sliceMode =
1789 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1790 params->codecPicParams.hevcPicParams.sliceModeData =
1791 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1793 params->codecPicParams.hevcPicParams.seiPayloadArray = sei_data;
1794 params->codecPicParams.hevcPicParams.seiPayloadArrayCnt = 1;
1801 static inline void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
1803 av_fifo_generic_write(queue, ×tamp, sizeof(timestamp), NULL);
1806 static inline int64_t timestamp_queue_dequeue(AVFifoBuffer* queue)
1808 int64_t timestamp = AV_NOPTS_VALUE;
1809 if (av_fifo_size(queue) > 0)
1810 av_fifo_generic_read(queue, ×tamp, sizeof(timestamp), NULL);
1815 static int nvenc_set_timestamp(AVCodecContext *avctx,
1816 NV_ENC_LOCK_BITSTREAM *params,
1819 NvencContext *ctx = avctx->priv_data;
1821 pkt->pts = params->outputTimeStamp;
1823 /* generate the first dts by linearly extrapolating the
1824 * first two pts values to the past */
1825 if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
1826 ctx->initial_pts[1] != AV_NOPTS_VALUE) {
1827 int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
1830 if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
1831 (ts0 > 0 && ts1 < INT64_MIN + ts0))
1832 return AVERROR(ERANGE);
1835 if ((delta < 0 && ts0 > INT64_MAX + delta) ||
1836 (delta > 0 && ts0 < INT64_MIN + delta))
1837 return AVERROR(ERANGE);
1838 pkt->dts = ts0 - delta;
1840 ctx->first_packet_output = 1;
1842 pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
1845 pkt->dts -= avctx->max_b_frames;
1850 static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
1852 NvencContext *ctx = avctx->priv_data;
1853 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1854 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1856 uint32_t slice_mode_data;
1857 uint32_t *slice_offsets = NULL;
1858 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1859 NVENCSTATUS nv_status;
1862 enum AVPictureType pict_type;
1864 switch (avctx->codec->id) {
1865 case AV_CODEC_ID_H264:
1866 slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1868 case AV_CODEC_ID_H265:
1869 slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1872 av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
1873 res = AVERROR(EINVAL);
1876 slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
1878 if (!slice_offsets) {
1879 res = AVERROR(ENOMEM);
1883 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1885 lock_params.doNotWait = 0;
1886 lock_params.outputBitstream = tmpoutsurf->output_surface;
1887 lock_params.sliceOffsets = slice_offsets;
1889 nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
1890 if (nv_status != NV_ENC_SUCCESS) {
1891 res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
1896 ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes, lock_params.bitstreamSizeInBytes) :
1897 av_new_packet(pkt, lock_params.bitstreamSizeInBytes);
1900 p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1904 memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1906 nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1907 if (nv_status != NV_ENC_SUCCESS) {
1908 res = nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
1913 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1914 ctx->registered_frames[tmpoutsurf->reg_idx].mapped -= 1;
1915 if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped == 0) {
1916 nv_status = p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[tmpoutsurf->reg_idx].in_map.mappedResource);
1917 if (nv_status != NV_ENC_SUCCESS) {
1918 res = nvenc_print_error(avctx, nv_status, "Failed unmapping input resource");
1921 } else if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped < 0) {
1926 av_frame_unref(tmpoutsurf->in_ref);
1928 tmpoutsurf->input_surface = NULL;
1931 switch (lock_params.pictureType) {
1932 case NV_ENC_PIC_TYPE_IDR:
1933 pkt->flags |= AV_PKT_FLAG_KEY;
1934 case NV_ENC_PIC_TYPE_I:
1935 pict_type = AV_PICTURE_TYPE_I;
1937 case NV_ENC_PIC_TYPE_P:
1938 pict_type = AV_PICTURE_TYPE_P;
1940 case NV_ENC_PIC_TYPE_B:
1941 pict_type = AV_PICTURE_TYPE_B;
1943 case NV_ENC_PIC_TYPE_BI:
1944 pict_type = AV_PICTURE_TYPE_BI;
1947 av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
1948 av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
1949 res = AVERROR_EXTERNAL;
1953 #if FF_API_CODED_FRAME
1954 FF_DISABLE_DEPRECATION_WARNINGS
1955 avctx->coded_frame->pict_type = pict_type;
1956 FF_ENABLE_DEPRECATION_WARNINGS
1959 ff_side_data_set_encoder_stats(pkt,
1960 (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
1962 res = nvenc_set_timestamp(avctx, &lock_params, pkt);
1966 av_free(slice_offsets);
1971 timestamp_queue_dequeue(ctx->timestamp_list);
1974 av_free(slice_offsets);
1979 static int output_ready(AVCodecContext *avctx, int flush)
1981 NvencContext *ctx = avctx->priv_data;
1982 int nb_ready, nb_pending;
1984 /* when B-frames are enabled, we wait for two initial timestamps to
1985 * calculate the first dts */
1986 if (!flush && avctx->max_b_frames > 0 &&
1987 (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
1990 nb_ready = av_fifo_size(ctx->output_surface_ready_queue) / sizeof(NvencSurface*);
1991 nb_pending = av_fifo_size(ctx->output_surface_queue) / sizeof(NvencSurface*);
1993 return nb_ready > 0;
1994 return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
1997 static void reconfig_encoder(AVCodecContext *avctx, const AVFrame *frame)
1999 NvencContext *ctx = avctx->priv_data;
2000 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
2003 NV_ENC_RECONFIGURE_PARAMS params = { 0 };
2004 int needs_reconfig = 0;
2005 int needs_encode_config = 0;
2006 int reconfig_bitrate = 0, reconfig_dar = 0;
2009 params.version = NV_ENC_RECONFIGURE_PARAMS_VER;
2010 params.reInitEncodeParams = ctx->init_encode_params;
2012 compute_dar(avctx, &dw, &dh);
2013 if (dw != ctx->init_encode_params.darWidth || dh != ctx->init_encode_params.darHeight) {
2014 av_log(avctx, AV_LOG_VERBOSE,
2015 "aspect ratio change (DAR): %d:%d -> %d:%d\n",
2016 ctx->init_encode_params.darWidth,
2017 ctx->init_encode_params.darHeight, dw, dh);
2019 params.reInitEncodeParams.darHeight = dh;
2020 params.reInitEncodeParams.darWidth = dw;
2026 if (ctx->rc != NV_ENC_PARAMS_RC_CONSTQP && ctx->support_dyn_bitrate) {
2027 if (avctx->bit_rate > 0 && params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate != avctx->bit_rate) {
2028 av_log(avctx, AV_LOG_VERBOSE,
2029 "avg bitrate change: %d -> %d\n",
2030 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate,
2031 (uint32_t)avctx->bit_rate);
2033 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate = avctx->bit_rate;
2034 reconfig_bitrate = 1;
2037 if (avctx->rc_max_rate > 0 && ctx->encode_config.rcParams.maxBitRate != avctx->rc_max_rate) {
2038 av_log(avctx, AV_LOG_VERBOSE,
2039 "max bitrate change: %d -> %d\n",
2040 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate,
2041 (uint32_t)avctx->rc_max_rate);
2043 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate = avctx->rc_max_rate;
2044 reconfig_bitrate = 1;
2047 if (avctx->rc_buffer_size > 0 && ctx->encode_config.rcParams.vbvBufferSize != avctx->rc_buffer_size) {
2048 av_log(avctx, AV_LOG_VERBOSE,
2049 "vbv buffer size change: %d -> %d\n",
2050 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize,
2051 avctx->rc_buffer_size);
2053 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize = avctx->rc_buffer_size;
2054 reconfig_bitrate = 1;
2057 if (reconfig_bitrate) {
2058 params.resetEncoder = 1;
2059 params.forceIDR = 1;
2061 needs_encode_config = 1;
2066 if (!needs_encode_config)
2067 params.reInitEncodeParams.encodeConfig = NULL;
2069 if (needs_reconfig) {
2070 ret = p_nvenc->nvEncReconfigureEncoder(ctx->nvencoder, ¶ms);
2071 if (ret != NV_ENC_SUCCESS) {
2072 nvenc_print_error(avctx, ret, "failed to reconfigure nvenc");
2075 ctx->init_encode_params.darHeight = dh;
2076 ctx->init_encode_params.darWidth = dw;
2079 if (reconfig_bitrate) {
2080 ctx->encode_config.rcParams.averageBitRate = params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate;
2081 ctx->encode_config.rcParams.maxBitRate = params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate;
2082 ctx->encode_config.rcParams.vbvBufferSize = params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize;
2089 int ff_nvenc_send_frame(AVCodecContext *avctx, const AVFrame *frame)
2091 NVENCSTATUS nv_status;
2092 NvencSurface *tmp_out_surf, *in_surf;
2094 NV_ENC_SEI_PAYLOAD *sei_data = NULL;
2097 NvencContext *ctx = avctx->priv_data;
2098 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
2099 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
2101 NV_ENC_PIC_PARAMS pic_params = { 0 };
2102 pic_params.version = NV_ENC_PIC_PARAMS_VER;
2104 if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
2105 return AVERROR(EINVAL);
2107 if (ctx->encoder_flushing) {
2108 if (avctx->internal->draining)
2111 ctx->encoder_flushing = 0;
2112 ctx->first_packet_output = 0;
2113 ctx->initial_pts[0] = AV_NOPTS_VALUE;
2114 ctx->initial_pts[1] = AV_NOPTS_VALUE;
2115 av_fifo_reset(ctx->timestamp_list);
2119 in_surf = get_free_frame(ctx);
2121 return AVERROR(EAGAIN);
2123 res = nvenc_push_context(avctx);
2127 reconfig_encoder(avctx, frame);
2129 res = nvenc_upload_frame(avctx, frame, in_surf);
2131 res2 = nvenc_pop_context(avctx);
2138 pic_params.inputBuffer = in_surf->input_surface;
2139 pic_params.bufferFmt = in_surf->format;
2140 pic_params.inputWidth = in_surf->width;
2141 pic_params.inputHeight = in_surf->height;
2142 pic_params.inputPitch = in_surf->pitch;
2143 pic_params.outputBitstream = in_surf->output_surface;
2145 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
2146 if (frame->top_field_first)
2147 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
2149 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
2151 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
2154 if (ctx->forced_idr >= 0 && frame->pict_type == AV_PICTURE_TYPE_I) {
2155 pic_params.encodePicFlags =
2156 ctx->forced_idr ? NV_ENC_PIC_FLAG_FORCEIDR : NV_ENC_PIC_FLAG_FORCEINTRA;
2158 pic_params.encodePicFlags = 0;
2161 pic_params.inputTimeStamp = frame->pts;
2163 if (ctx->a53_cc && av_frame_get_side_data(frame, AV_FRAME_DATA_A53_CC)) {
2164 if (ff_alloc_a53_sei(frame, sizeof(NV_ENC_SEI_PAYLOAD), (void**)&sei_data, &sei_size) < 0) {
2165 av_log(ctx, AV_LOG_ERROR, "Not enough memory for closed captions, skipping\n");
2169 sei_data->payloadSize = (uint32_t)sei_size;
2170 sei_data->payloadType = 4;
2171 sei_data->payload = (uint8_t*)(sei_data + 1);
2175 nvenc_codec_specific_pic_params(avctx, &pic_params, sei_data);
2177 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
2178 ctx->encoder_flushing = 1;
2181 res = nvenc_push_context(avctx);
2185 nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
2188 res = nvenc_pop_context(avctx);
2192 if (nv_status != NV_ENC_SUCCESS &&
2193 nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
2194 return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
2197 av_fifo_generic_write(ctx->output_surface_queue, &in_surf, sizeof(in_surf), NULL);
2198 timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
2200 if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
2201 ctx->initial_pts[0] = frame->pts;
2202 else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
2203 ctx->initial_pts[1] = frame->pts;
2206 /* all the pending buffers are now ready for output */
2207 if (nv_status == NV_ENC_SUCCESS) {
2208 while (av_fifo_size(ctx->output_surface_queue) > 0) {
2209 av_fifo_generic_read(ctx->output_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2210 av_fifo_generic_write(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2217 int ff_nvenc_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
2219 NvencSurface *tmp_out_surf;
2222 NvencContext *ctx = avctx->priv_data;
2224 if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
2225 return AVERROR(EINVAL);
2227 if (output_ready(avctx, ctx->encoder_flushing)) {
2228 av_fifo_generic_read(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2230 res = nvenc_push_context(avctx);
2234 res = process_output_surface(avctx, pkt, tmp_out_surf);
2236 res2 = nvenc_pop_context(avctx);
2243 av_fifo_generic_write(ctx->unused_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2244 } else if (ctx->encoder_flushing) {
2247 return AVERROR(EAGAIN);
2253 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
2254 const AVFrame *frame, int *got_packet)
2256 NvencContext *ctx = avctx->priv_data;
2259 if (!ctx->encoder_flushing) {
2260 res = ff_nvenc_send_frame(avctx, frame);
2265 res = ff_nvenc_receive_packet(avctx, pkt);
2266 if (res == AVERROR(EAGAIN) || res == AVERROR_EOF) {
2268 } else if (res < 0) {
2277 av_cold void ff_nvenc_encode_flush(AVCodecContext *avctx)
2279 ff_nvenc_send_frame(avctx, NULL);