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
24 #if defined(_WIN32) || defined(__CYGWIN__)
25 # define CUDA_LIBNAME "nvcuda.dll"
27 # define NVENC_LIBNAME "nvEncodeAPI64.dll"
29 # define NVENC_LIBNAME "nvEncodeAPI.dll"
32 # define CUDA_LIBNAME "libcuda.so.1"
33 # define NVENC_LIBNAME "libnvidia-encode.so.1"
39 #define dlopen(filename, flags) LoadLibrary(TEXT(filename))
40 #define dlsym(handle, symbol) GetProcAddress(handle, symbol)
41 #define dlclose(handle) FreeLibrary(handle)
46 #include "libavutil/hwcontext.h"
47 #include "libavutil/imgutils.h"
48 #include "libavutil/avassert.h"
49 #include "libavutil/mem.h"
53 #define NVENC_CAP 0x30
54 #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR || \
55 rc == NV_ENC_PARAMS_RC_2_PASS_QUALITY || \
56 rc == NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP)
58 #define LOAD_LIBRARY(l, path) \
60 if (!((l) = dlopen(path, RTLD_LAZY))) { \
61 av_log(avctx, AV_LOG_ERROR, \
64 return AVERROR_UNKNOWN; \
68 #define LOAD_SYMBOL(fun, lib, symbol) \
70 if (!((fun) = dlsym(lib, symbol))) { \
71 av_log(avctx, AV_LOG_ERROR, \
74 return AVERROR_UNKNOWN; \
78 const enum AVPixelFormat ff_nvenc_pix_fmts[] = {
90 #define IS_10BIT(pix_fmt) (pix_fmt == AV_PIX_FMT_P010 || \
91 pix_fmt == AV_PIX_FMT_YUV444P16)
93 #define IS_YUV444(pix_fmt) (pix_fmt == AV_PIX_FMT_YUV444P || \
94 pix_fmt == AV_PIX_FMT_YUV444P16)
101 { NV_ENC_SUCCESS, 0, "success" },
102 { NV_ENC_ERR_NO_ENCODE_DEVICE, AVERROR(ENOENT), "no encode device" },
103 { NV_ENC_ERR_UNSUPPORTED_DEVICE, AVERROR(ENOSYS), "unsupported device" },
104 { NV_ENC_ERR_INVALID_ENCODERDEVICE, AVERROR(EINVAL), "invalid encoder device" },
105 { NV_ENC_ERR_INVALID_DEVICE, AVERROR(EINVAL), "invalid device" },
106 { NV_ENC_ERR_DEVICE_NOT_EXIST, AVERROR(EIO), "device does not exist" },
107 { NV_ENC_ERR_INVALID_PTR, AVERROR(EFAULT), "invalid ptr" },
108 { NV_ENC_ERR_INVALID_EVENT, AVERROR(EINVAL), "invalid event" },
109 { NV_ENC_ERR_INVALID_PARAM, AVERROR(EINVAL), "invalid param" },
110 { NV_ENC_ERR_INVALID_CALL, AVERROR(EINVAL), "invalid call" },
111 { NV_ENC_ERR_OUT_OF_MEMORY, AVERROR(ENOMEM), "out of memory" },
112 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED, AVERROR(EINVAL), "encoder not initialized" },
113 { NV_ENC_ERR_UNSUPPORTED_PARAM, AVERROR(ENOSYS), "unsupported param" },
114 { NV_ENC_ERR_LOCK_BUSY, AVERROR(EAGAIN), "lock busy" },
115 { NV_ENC_ERR_NOT_ENOUGH_BUFFER, AVERROR(ENOBUFS), "not enough buffer" },
116 { NV_ENC_ERR_INVALID_VERSION, AVERROR(EINVAL), "invalid version" },
117 { NV_ENC_ERR_MAP_FAILED, AVERROR(EIO), "map failed" },
118 { NV_ENC_ERR_NEED_MORE_INPUT, AVERROR(EAGAIN), "need more input" },
119 { NV_ENC_ERR_ENCODER_BUSY, AVERROR(EAGAIN), "encoder busy" },
120 { NV_ENC_ERR_EVENT_NOT_REGISTERD, AVERROR(EBADF), "event not registered" },
121 { NV_ENC_ERR_GENERIC, AVERROR_UNKNOWN, "generic error" },
122 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY, AVERROR(EINVAL), "incompatible client key" },
123 { NV_ENC_ERR_UNIMPLEMENTED, AVERROR(ENOSYS), "unimplemented" },
124 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO), "resource register failed" },
125 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED, AVERROR(EBADF), "resource not registered" },
126 { NV_ENC_ERR_RESOURCE_NOT_MAPPED, AVERROR(EBADF), "resource not mapped" },
129 static int nvenc_map_error(NVENCSTATUS err, const char **desc)
132 for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
133 if (nvenc_errors[i].nverr == err) {
135 *desc = nvenc_errors[i].desc;
136 return nvenc_errors[i].averr;
140 *desc = "unknown error";
141 return AVERROR_UNKNOWN;
144 static int nvenc_print_error(void *log_ctx, NVENCSTATUS err,
145 const char *error_string)
149 ret = nvenc_map_error(err, &desc);
150 av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
154 static av_cold int nvenc_load_libraries(AVCodecContext *avctx)
156 NvencContext *ctx = avctx->priv_data;
157 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
158 PNVENCODEAPIGETMAXSUPPORTEDVERSION nvenc_get_max_ver;
159 PNVENCODEAPICREATEINSTANCE nvenc_create_instance;
161 uint32_t nvenc_max_ver;
164 dl_fn->cu_init = cuInit;
165 dl_fn->cu_device_get_count = cuDeviceGetCount;
166 dl_fn->cu_device_get = cuDeviceGet;
167 dl_fn->cu_device_get_name = cuDeviceGetName;
168 dl_fn->cu_device_compute_capability = cuDeviceComputeCapability;
169 dl_fn->cu_ctx_create = cuCtxCreate_v2;
170 dl_fn->cu_ctx_pop_current = cuCtxPopCurrent_v2;
171 dl_fn->cu_ctx_destroy = cuCtxDestroy_v2;
173 LOAD_LIBRARY(dl_fn->cuda, CUDA_LIBNAME);
175 LOAD_SYMBOL(dl_fn->cu_init, dl_fn->cuda, "cuInit");
176 LOAD_SYMBOL(dl_fn->cu_device_get_count, dl_fn->cuda, "cuDeviceGetCount");
177 LOAD_SYMBOL(dl_fn->cu_device_get, dl_fn->cuda, "cuDeviceGet");
178 LOAD_SYMBOL(dl_fn->cu_device_get_name, dl_fn->cuda, "cuDeviceGetName");
179 LOAD_SYMBOL(dl_fn->cu_device_compute_capability, dl_fn->cuda,
180 "cuDeviceComputeCapability");
181 LOAD_SYMBOL(dl_fn->cu_ctx_create, dl_fn->cuda, "cuCtxCreate_v2");
182 LOAD_SYMBOL(dl_fn->cu_ctx_pop_current, dl_fn->cuda, "cuCtxPopCurrent_v2");
183 LOAD_SYMBOL(dl_fn->cu_ctx_destroy, dl_fn->cuda, "cuCtxDestroy_v2");
186 LOAD_LIBRARY(dl_fn->nvenc, NVENC_LIBNAME);
188 LOAD_SYMBOL(nvenc_get_max_ver, dl_fn->nvenc,
189 "NvEncodeAPIGetMaxSupportedVersion");
190 LOAD_SYMBOL(nvenc_create_instance, dl_fn->nvenc,
191 "NvEncodeAPICreateInstance");
193 err = nvenc_get_max_ver(&nvenc_max_ver);
194 if (err != NV_ENC_SUCCESS)
195 return nvenc_print_error(avctx, err, "Failed to query nvenc max version");
197 av_log(avctx, AV_LOG_VERBOSE, "Loaded Nvenc version %d.%d\n", nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
199 if ((NVENCAPI_MAJOR_VERSION << 4 | NVENCAPI_MINOR_VERSION) > nvenc_max_ver) {
200 av_log(avctx, AV_LOG_ERROR, "Driver does not support the required nvenc API version. "
201 "Required: %d.%d Found: %d.%d\n",
202 NVENCAPI_MAJOR_VERSION, NVENCAPI_MINOR_VERSION,
203 nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
204 return AVERROR(ENOSYS);
207 dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
209 err = nvenc_create_instance(&dl_fn->nvenc_funcs);
210 if (err != NV_ENC_SUCCESS)
211 return nvenc_print_error(avctx, err, "Failed to create nvenc instance");
213 av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
218 static av_cold int nvenc_open_session(AVCodecContext *avctx)
220 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
221 NvencContext *ctx = avctx->priv_data;
222 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
225 params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
226 params.apiVersion = NVENCAPI_VERSION;
227 params.device = ctx->cu_context;
228 params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
230 ret = p_nvenc->nvEncOpenEncodeSessionEx(¶ms, &ctx->nvencoder);
231 if (ret != NV_ENC_SUCCESS) {
232 ctx->nvencoder = NULL;
233 return nvenc_print_error(avctx, ret, "OpenEncodeSessionEx failed");
239 static int nvenc_check_codec_support(AVCodecContext *avctx)
241 NvencContext *ctx = avctx->priv_data;
242 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
243 int i, ret, count = 0;
246 ret = p_nvenc->nvEncGetEncodeGUIDCount(ctx->nvencoder, &count);
248 if (ret != NV_ENC_SUCCESS || !count)
249 return AVERROR(ENOSYS);
251 guids = av_malloc(count * sizeof(GUID));
253 return AVERROR(ENOMEM);
255 ret = p_nvenc->nvEncGetEncodeGUIDs(ctx->nvencoder, guids, count, &count);
256 if (ret != NV_ENC_SUCCESS) {
257 ret = AVERROR(ENOSYS);
261 ret = AVERROR(ENOSYS);
262 for (i = 0; i < count; i++) {
263 if (!memcmp(&guids[i], &ctx->init_encode_params.encodeGUID, sizeof(*guids))) {
275 static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
277 NvencContext *ctx = avctx->priv_data;
278 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
279 NV_ENC_CAPS_PARAM params = { 0 };
282 params.version = NV_ENC_CAPS_PARAM_VER;
283 params.capsToQuery = cap;
285 ret = p_nvenc->nvEncGetEncodeCaps(ctx->nvencoder, ctx->init_encode_params.encodeGUID, ¶ms, &val);
287 if (ret == NV_ENC_SUCCESS)
292 static int nvenc_check_capabilities(AVCodecContext *avctx)
294 NvencContext *ctx = avctx->priv_data;
297 ret = nvenc_check_codec_support(avctx);
299 av_log(avctx, AV_LOG_VERBOSE, "Codec not supported\n");
303 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
304 if (IS_YUV444(ctx->data_pix_fmt) && ret <= 0) {
305 av_log(avctx, AV_LOG_VERBOSE, "YUV444P not supported\n");
306 return AVERROR(ENOSYS);
309 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOSSLESS_ENCODE);
310 if (ctx->preset >= PRESET_LOSSLESS_DEFAULT && ret <= 0) {
311 av_log(avctx, AV_LOG_VERBOSE, "Lossless encoding not supported\n");
312 return AVERROR(ENOSYS);
315 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
316 if (ret < avctx->width) {
317 av_log(avctx, AV_LOG_VERBOSE, "Width %d exceeds %d\n",
319 return AVERROR(ENOSYS);
322 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
323 if (ret < avctx->height) {
324 av_log(avctx, AV_LOG_VERBOSE, "Height %d exceeds %d\n",
326 return AVERROR(ENOSYS);
329 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
330 if (ret < avctx->max_b_frames) {
331 av_log(avctx, AV_LOG_VERBOSE, "Max B-frames %d exceed %d\n",
332 avctx->max_b_frames, ret);
334 return AVERROR(ENOSYS);
337 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_FIELD_ENCODING);
338 if (ret < 1 && avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
339 av_log(avctx, AV_LOG_VERBOSE,
340 "Interlaced encoding is not supported. Supported level: %d\n",
342 return AVERROR(ENOSYS);
345 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_10BIT_ENCODE);
346 if (IS_10BIT(ctx->data_pix_fmt) && ret <= 0) {
347 av_log(avctx, AV_LOG_VERBOSE, "10 bit encode not supported\n");
348 return AVERROR(ENOSYS);
351 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOOKAHEAD);
352 if (ctx->rc_lookahead > 0 && ret <= 0) {
353 av_log(avctx, AV_LOG_VERBOSE, "RC lookahead not supported\n");
354 return AVERROR(ENOSYS);
360 static av_cold int nvenc_check_device(AVCodecContext *avctx, int idx)
362 NvencContext *ctx = avctx->priv_data;
363 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
364 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
365 char name[128] = { 0};
366 int major, minor, ret;
370 int loglevel = AV_LOG_VERBOSE;
372 if (ctx->device == LIST_DEVICES)
373 loglevel = AV_LOG_INFO;
375 cu_res = dl_fn->cu_device_get(&cu_device, idx);
376 if (cu_res != CUDA_SUCCESS) {
377 av_log(avctx, AV_LOG_ERROR,
378 "Cannot access the CUDA device %d\n",
383 cu_res = dl_fn->cu_device_get_name(name, sizeof(name), cu_device);
384 if (cu_res != CUDA_SUCCESS)
387 cu_res = dl_fn->cu_device_compute_capability(&major, &minor, cu_device);
388 if (cu_res != CUDA_SUCCESS)
391 av_log(avctx, loglevel, "[ GPU #%d - < %s > has Compute SM %d.%d ]\n", idx, name, major, minor);
392 if (((major << 4) | minor) < NVENC_CAP) {
393 av_log(avctx, loglevel, "does not support NVENC\n");
397 cu_res = dl_fn->cu_ctx_create(&ctx->cu_context_internal, 0, cu_device);
398 if (cu_res != CUDA_SUCCESS) {
399 av_log(avctx, AV_LOG_FATAL, "Failed creating CUDA context for NVENC: 0x%x\n", (int)cu_res);
403 ctx->cu_context = ctx->cu_context_internal;
405 cu_res = dl_fn->cu_ctx_pop_current(&dummy);
406 if (cu_res != CUDA_SUCCESS) {
407 av_log(avctx, AV_LOG_FATAL, "Failed popping CUDA context: 0x%x\n", (int)cu_res);
411 if ((ret = nvenc_open_session(avctx)) < 0)
414 if ((ret = nvenc_check_capabilities(avctx)) < 0)
417 av_log(avctx, loglevel, "supports NVENC\n");
419 dl_fn->nvenc_device_count++;
421 if (ctx->device == dl_fn->nvenc_device_count - 1 || ctx->device == ANY_DEVICE)
425 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
426 ctx->nvencoder = NULL;
429 dl_fn->cu_ctx_destroy(ctx->cu_context_internal);
430 ctx->cu_context_internal = NULL;
433 return AVERROR(ENOSYS);
436 static av_cold int nvenc_setup_device(AVCodecContext *avctx)
438 NvencContext *ctx = avctx->priv_data;
439 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
441 switch (avctx->codec->id) {
442 case AV_CODEC_ID_H264:
443 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
445 case AV_CODEC_ID_HEVC:
446 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
452 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
454 AVHWFramesContext *frames_ctx;
455 AVCUDADeviceContext *device_hwctx;
458 if (!avctx->hw_frames_ctx)
459 return AVERROR(EINVAL);
461 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
462 device_hwctx = frames_ctx->device_ctx->hwctx;
464 ctx->cu_context = device_hwctx->cuda_ctx;
466 ret = nvenc_open_session(avctx);
470 ret = nvenc_check_capabilities(avctx);
472 av_log(avctx, AV_LOG_FATAL, "Provided device doesn't support required NVENC features\n");
479 int i, nb_devices = 0;
481 if ((dl_fn->cu_init(0)) != CUDA_SUCCESS) {
482 av_log(avctx, AV_LOG_ERROR,
483 "Cannot init CUDA\n");
484 return AVERROR_UNKNOWN;
487 if ((dl_fn->cu_device_get_count(&nb_devices)) != CUDA_SUCCESS) {
488 av_log(avctx, AV_LOG_ERROR,
489 "Cannot enumerate the CUDA devices\n");
490 return AVERROR_UNKNOWN;
494 av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
495 return AVERROR_EXTERNAL;
498 av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", nb_devices);
500 dl_fn->nvenc_device_count = 0;
501 for (i = 0; i < nb_devices; ++i) {
502 if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
506 if (ctx->device == LIST_DEVICES)
509 if (!dl_fn->nvenc_device_count) {
510 av_log(avctx, AV_LOG_FATAL, "No NVENC capable devices found\n");
511 return AVERROR_EXTERNAL;
514 av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->device, dl_fn->nvenc_device_count);
515 return AVERROR(EINVAL);
521 typedef struct GUIDTuple {
526 static void nvenc_map_preset(NvencContext *ctx)
528 GUIDTuple presets[] = {
529 { NV_ENC_PRESET_DEFAULT_GUID },
530 { NV_ENC_PRESET_HQ_GUID, NVENC_TWO_PASSES }, /* slow */
531 { NV_ENC_PRESET_HQ_GUID, NVENC_ONE_PASS }, /* medium */
532 { NV_ENC_PRESET_HP_GUID, NVENC_ONE_PASS }, /* fast */
533 { NV_ENC_PRESET_HP_GUID },
534 { NV_ENC_PRESET_HQ_GUID },
535 { NV_ENC_PRESET_BD_GUID },
536 { NV_ENC_PRESET_LOW_LATENCY_DEFAULT_GUID, NVENC_LOWLATENCY },
537 { NV_ENC_PRESET_LOW_LATENCY_HQ_GUID, NVENC_LOWLATENCY },
538 { NV_ENC_PRESET_LOW_LATENCY_HP_GUID, NVENC_LOWLATENCY },
539 { NV_ENC_PRESET_LOSSLESS_DEFAULT_GUID, NVENC_LOSSLESS },
540 { NV_ENC_PRESET_LOSSLESS_HP_GUID, NVENC_LOSSLESS },
543 GUIDTuple *t = &presets[ctx->preset];
545 ctx->init_encode_params.presetGUID = t->guid;
546 ctx->flags = t->flags;
549 static av_cold void set_constqp(AVCodecContext *avctx)
551 NvencContext *ctx = avctx->priv_data;
552 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
554 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
555 rc->constQP.qpInterB = avctx->global_quality;
556 rc->constQP.qpInterP = avctx->global_quality;
557 rc->constQP.qpIntra = avctx->global_quality;
563 static av_cold void set_vbr(AVCodecContext *avctx)
565 NvencContext *ctx = avctx->priv_data;
566 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
569 if (avctx->qmin >= 0 && avctx->qmax >= 0) {
573 rc->minQP.qpInterB = avctx->qmin;
574 rc->minQP.qpInterP = avctx->qmin;
575 rc->minQP.qpIntra = avctx->qmin;
577 rc->maxQP.qpInterB = avctx->qmax;
578 rc->maxQP.qpInterP = avctx->qmax;
579 rc->maxQP.qpIntra = avctx->qmax;
581 qp_inter_p = (avctx->qmax + 3 * avctx->qmin) / 4; // biased towards Qmin
582 } else if (avctx->qmin >= 0) {
585 rc->minQP.qpInterB = avctx->qmin;
586 rc->minQP.qpInterP = avctx->qmin;
587 rc->minQP.qpIntra = avctx->qmin;
589 qp_inter_p = avctx->qmin;
591 qp_inter_p = 26; // default to 26
594 rc->enableInitialRCQP = 1;
595 rc->initialRCQP.qpInterP = qp_inter_p;
597 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
598 rc->initialRCQP.qpIntra = av_clip(
599 qp_inter_p * fabs(avctx->i_quant_factor) + avctx->i_quant_offset, 0, 51);
600 rc->initialRCQP.qpInterB = av_clip(
601 qp_inter_p * fabs(avctx->b_quant_factor) + avctx->b_quant_offset, 0, 51);
603 rc->initialRCQP.qpIntra = qp_inter_p;
604 rc->initialRCQP.qpInterB = qp_inter_p;
608 static av_cold void set_lossless(AVCodecContext *avctx)
610 NvencContext *ctx = avctx->priv_data;
611 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
613 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
614 rc->constQP.qpInterB = 0;
615 rc->constQP.qpInterP = 0;
616 rc->constQP.qpIntra = 0;
622 static void nvenc_override_rate_control(AVCodecContext *avctx)
624 NvencContext *ctx = avctx->priv_data;
625 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
628 case NV_ENC_PARAMS_RC_CONSTQP:
629 if (avctx->global_quality <= 0) {
630 av_log(avctx, AV_LOG_WARNING,
631 "The constant quality rate-control requires "
632 "the 'global_quality' option set.\n");
637 case NV_ENC_PARAMS_RC_2_PASS_VBR:
638 case NV_ENC_PARAMS_RC_VBR:
639 if (avctx->qmin < 0 && avctx->qmax < 0) {
640 av_log(avctx, AV_LOG_WARNING,
641 "The variable bitrate rate-control requires "
642 "the 'qmin' and/or 'qmax' option set.\n");
646 case NV_ENC_PARAMS_RC_VBR_MINQP:
647 if (avctx->qmin < 0) {
648 av_log(avctx, AV_LOG_WARNING,
649 "The variable bitrate rate-control requires "
650 "the 'qmin' option set.\n");
656 case NV_ENC_PARAMS_RC_CBR:
657 case NV_ENC_PARAMS_RC_2_PASS_QUALITY:
658 case NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP:
662 rc->rateControlMode = ctx->rc;
665 static av_cold void nvenc_setup_rate_control(AVCodecContext *avctx)
667 NvencContext *ctx = avctx->priv_data;
669 if (avctx->bit_rate > 0) {
670 ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
671 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
672 ctx->encode_config.rcParams.maxBitRate = ctx->encode_config.rcParams.averageBitRate;
675 if (avctx->rc_max_rate > 0)
676 ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
679 if (ctx->flags & NVENC_ONE_PASS)
681 if (ctx->flags & NVENC_TWO_PASSES)
684 if (ctx->twopass < 0)
685 ctx->twopass = (ctx->flags & NVENC_LOWLATENCY) != 0;
689 ctx->rc = NV_ENC_PARAMS_RC_2_PASS_QUALITY;
691 ctx->rc = NV_ENC_PARAMS_RC_CBR;
693 } else if (avctx->global_quality > 0) {
694 ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
695 } else if (ctx->twopass) {
696 ctx->rc = NV_ENC_PARAMS_RC_2_PASS_VBR;
697 } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
698 ctx->rc = NV_ENC_PARAMS_RC_VBR_MINQP;
702 if (ctx->flags & NVENC_LOSSLESS) {
704 } else if (ctx->rc >= 0) {
705 nvenc_override_rate_control(avctx);
707 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
711 if (avctx->rc_buffer_size > 0) {
712 ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
713 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
714 ctx->encode_config.rcParams.vbvBufferSize = 2 * ctx->encode_config.rcParams.averageBitRate;
717 if (ctx->rc_lookahead > 0) {
718 ctx->encode_config.rcParams.enableLookahead = 1;
719 ctx->encode_config.rcParams.lookaheadDepth = FFMIN(ctx->rc_lookahead, 32);
723 static av_cold int nvenc_setup_h264_config(AVCodecContext *avctx)
725 NvencContext *ctx = avctx->priv_data;
726 NV_ENC_CONFIG *cc = &ctx->encode_config;
727 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
728 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
730 vui->colourMatrix = avctx->colorspace;
731 vui->colourPrimaries = avctx->color_primaries;
732 vui->transferCharacteristics = avctx->color_trc;
733 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
734 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
736 vui->colourDescriptionPresentFlag =
737 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
739 vui->videoSignalTypePresentFlag =
740 (vui->colourDescriptionPresentFlag
741 || vui->videoFormat != 5
742 || vui->videoFullRangeFlag != 0);
745 h264->sliceModeData = 1;
747 h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
748 h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
751 if (avctx->refs >= 0) {
752 /* 0 means "let the hardware decide" */
753 h264->maxNumRefFrames = avctx->refs;
755 if (avctx->gop_size >= 0) {
756 h264->idrPeriod = cc->gopLength;
759 if (IS_CBR(cc->rcParams.rateControlMode)) {
760 h264->outputBufferingPeriodSEI = 1;
761 h264->outputPictureTimingSEI = 1;
764 if (cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_2_PASS_QUALITY ||
765 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP ||
766 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_2_PASS_VBR) {
767 h264->adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
768 h264->fmoMode = NV_ENC_H264_FMO_DISABLE;
771 if (ctx->flags & NVENC_LOSSLESS) {
772 h264->qpPrimeYZeroTransformBypassFlag = 1;
774 switch(ctx->profile) {
775 case NV_ENC_H264_PROFILE_BASELINE:
776 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
777 avctx->profile = FF_PROFILE_H264_BASELINE;
779 case NV_ENC_H264_PROFILE_MAIN:
780 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
781 avctx->profile = FF_PROFILE_H264_MAIN;
783 case NV_ENC_H264_PROFILE_HIGH:
784 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
785 avctx->profile = FF_PROFILE_H264_HIGH;
787 case NV_ENC_H264_PROFILE_HIGH_444P:
788 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
789 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
794 // force setting profile as high444p if input is AV_PIX_FMT_YUV444P
795 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P) {
796 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
797 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
800 h264->chromaFormatIDC = avctx->profile == FF_PROFILE_H264_HIGH_444_PREDICTIVE ? 3 : 1;
802 h264->level = ctx->level;
807 static av_cold int nvenc_setup_hevc_config(AVCodecContext *avctx)
809 NvencContext *ctx = avctx->priv_data;
810 NV_ENC_CONFIG *cc = &ctx->encode_config;
811 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
812 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
814 vui->colourMatrix = avctx->colorspace;
815 vui->colourPrimaries = avctx->color_primaries;
816 vui->transferCharacteristics = avctx->color_trc;
817 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
818 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
820 vui->colourDescriptionPresentFlag =
821 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
823 vui->videoSignalTypePresentFlag =
824 (vui->colourDescriptionPresentFlag
825 || vui->videoFormat != 5
826 || vui->videoFullRangeFlag != 0);
829 hevc->sliceModeData = 1;
831 hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
832 hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
835 if (avctx->refs >= 0) {
836 /* 0 means "let the hardware decide" */
837 hevc->maxNumRefFramesInDPB = avctx->refs;
839 if (avctx->gop_size >= 0) {
840 hevc->idrPeriod = cc->gopLength;
843 if (IS_CBR(cc->rcParams.rateControlMode)) {
844 hevc->outputBufferingPeriodSEI = 1;
845 hevc->outputPictureTimingSEI = 1;
848 switch(ctx->profile) {
849 case NV_ENC_HEVC_PROFILE_MAIN:
850 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
851 avctx->profile = FF_PROFILE_HEVC_MAIN;
853 case NV_ENC_HEVC_PROFILE_MAIN_10:
854 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
855 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
859 // force setting profile as main10 if input is 10 bit
860 if (IS_10BIT(ctx->data_pix_fmt)) {
861 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
862 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
865 hevc->chromaFormatIDC = IS_YUV444(ctx->data_pix_fmt) ? 3 : 1;
867 hevc->pixelBitDepthMinus8 = IS_10BIT(ctx->data_pix_fmt) ? 2 : 0;
869 hevc->level = ctx->level;
871 hevc->tier = ctx->tier;
876 static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx)
878 switch (avctx->codec->id) {
879 case AV_CODEC_ID_H264:
880 return nvenc_setup_h264_config(avctx);
881 case AV_CODEC_ID_HEVC:
882 return nvenc_setup_hevc_config(avctx);
883 /* Earlier switch/case will return if unknown codec is passed. */
889 static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
891 NvencContext *ctx = avctx->priv_data;
892 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
893 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
895 NV_ENC_PRESET_CONFIG preset_config = { 0 };
896 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
897 AVCPBProperties *cpb_props;
901 ctx->encode_config.version = NV_ENC_CONFIG_VER;
902 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
904 ctx->init_encode_params.encodeHeight = avctx->height;
905 ctx->init_encode_params.encodeWidth = avctx->width;
907 ctx->init_encode_params.encodeConfig = &ctx->encode_config;
909 nvenc_map_preset(ctx);
911 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
912 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
914 nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder,
915 ctx->init_encode_params.encodeGUID,
916 ctx->init_encode_params.presetGUID,
918 if (nv_status != NV_ENC_SUCCESS)
919 return nvenc_print_error(avctx, nv_status, "Cannot get the preset configuration");
921 memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
923 ctx->encode_config.version = NV_ENC_CONFIG_VER;
925 if (avctx->sample_aspect_ratio.num && avctx->sample_aspect_ratio.den &&
926 (avctx->sample_aspect_ratio.num != 1 || avctx->sample_aspect_ratio.num != 1)) {
928 avctx->width * avctx->sample_aspect_ratio.num,
929 avctx->height * avctx->sample_aspect_ratio.den,
931 ctx->init_encode_params.darHeight = dh;
932 ctx->init_encode_params.darWidth = dw;
934 ctx->init_encode_params.darHeight = avctx->height;
935 ctx->init_encode_params.darWidth = avctx->width;
938 // De-compensate for hardware, dubiously, trying to compensate for
939 // playback at 704 pixel width.
940 if (avctx->width == 720 &&
941 (avctx->height == 480 || avctx->height == 576)) {
943 ctx->init_encode_params.darWidth * 44,
944 ctx->init_encode_params.darHeight * 45,
946 ctx->init_encode_params.darHeight = dh;
947 ctx->init_encode_params.darWidth = dw;
950 ctx->init_encode_params.frameRateNum = avctx->time_base.den;
951 ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
953 ctx->init_encode_params.enableEncodeAsync = 0;
954 ctx->init_encode_params.enablePTD = 1;
956 if (avctx->gop_size > 0) {
957 if (avctx->max_b_frames >= 0) {
958 /* 0 is intra-only, 1 is I/P only, 2 is one B-Frame, 3 two B-frames, and so on. */
959 ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
962 ctx->encode_config.gopLength = avctx->gop_size;
963 } else if (avctx->gop_size == 0) {
964 ctx->encode_config.frameIntervalP = 0;
965 ctx->encode_config.gopLength = 1;
968 ctx->initial_pts[0] = AV_NOPTS_VALUE;
969 ctx->initial_pts[1] = AV_NOPTS_VALUE;
971 nvenc_setup_rate_control(avctx);
973 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
974 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
976 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
979 res = nvenc_setup_codec_config(avctx);
983 nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
984 if (nv_status != NV_ENC_SUCCESS) {
985 return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
988 if (ctx->encode_config.frameIntervalP > 1)
989 avctx->has_b_frames = 2;
991 if (ctx->encode_config.rcParams.averageBitRate > 0)
992 avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
994 cpb_props = ff_add_cpb_side_data(avctx);
996 return AVERROR(ENOMEM);
997 cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
998 cpb_props->avg_bitrate = avctx->bit_rate;
999 cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
1004 static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
1006 NvencContext *ctx = avctx->priv_data;
1007 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1008 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1010 NVENCSTATUS nv_status;
1011 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
1012 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1014 switch (ctx->data_pix_fmt) {
1015 case AV_PIX_FMT_YUV420P:
1016 ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_YV12_PL;
1019 case AV_PIX_FMT_NV12:
1020 ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_NV12_PL;
1023 case AV_PIX_FMT_P010:
1024 ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1027 case AV_PIX_FMT_YUV444P:
1028 ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_YUV444_PL;
1031 case AV_PIX_FMT_YUV444P16:
1032 ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1036 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format\n");
1037 return AVERROR(EINVAL);
1040 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1041 ctx->surfaces[idx].in_ref = av_frame_alloc();
1042 if (!ctx->surfaces[idx].in_ref)
1043 return AVERROR(ENOMEM);
1045 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1046 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1047 allocSurf.width = (avctx->width + 31) & ~31;
1048 allocSurf.height = (avctx->height + 31) & ~31;
1049 allocSurf.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
1050 allocSurf.bufferFmt = ctx->surfaces[idx].format;
1052 nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
1053 if (nv_status != NV_ENC_SUCCESS) {
1054 return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
1057 ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
1058 ctx->surfaces[idx].width = allocSurf.width;
1059 ctx->surfaces[idx].height = allocSurf.height;
1062 ctx->surfaces[idx].lockCount = 0;
1064 /* 1MB is large enough to hold most output frames.
1065 * NVENC increases this automaticaly if it is not enough. */
1066 allocOut.size = 1024 * 1024;
1068 allocOut.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
1070 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
1071 if (nv_status != NV_ENC_SUCCESS) {
1072 int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
1073 if (avctx->pix_fmt != AV_PIX_FMT_CUDA)
1074 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
1075 av_frame_free(&ctx->surfaces[idx].in_ref);
1079 ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1080 ctx->surfaces[idx].size = allocOut.size;
1085 static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx)
1087 NvencContext *ctx = avctx->priv_data;
1089 int num_mbs = ((avctx->width + 15) >> 4) * ((avctx->height + 15) >> 4);
1090 ctx->nb_surfaces = FFMAX((num_mbs >= 8160) ? 32 : 48,
1092 ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
1095 ctx->surfaces = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->surfaces));
1097 return AVERROR(ENOMEM);
1099 ctx->timestamp_list = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
1100 if (!ctx->timestamp_list)
1101 return AVERROR(ENOMEM);
1102 ctx->output_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1103 if (!ctx->output_surface_queue)
1104 return AVERROR(ENOMEM);
1105 ctx->output_surface_ready_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1106 if (!ctx->output_surface_ready_queue)
1107 return AVERROR(ENOMEM);
1109 for (i = 0; i < ctx->nb_surfaces; i++) {
1110 if ((res = nvenc_alloc_surface(avctx, i)) < 0)
1117 static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
1119 NvencContext *ctx = avctx->priv_data;
1120 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1121 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1123 NVENCSTATUS nv_status;
1124 uint32_t outSize = 0;
1125 char tmpHeader[256];
1126 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1127 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1129 payload.spsppsBuffer = tmpHeader;
1130 payload.inBufferSize = sizeof(tmpHeader);
1131 payload.outSPSPPSPayloadSize = &outSize;
1133 nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
1134 if (nv_status != NV_ENC_SUCCESS) {
1135 return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
1138 avctx->extradata_size = outSize;
1139 avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
1141 if (!avctx->extradata) {
1142 return AVERROR(ENOMEM);
1145 memcpy(avctx->extradata, tmpHeader, outSize);
1150 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
1152 NvencContext *ctx = avctx->priv_data;
1153 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1154 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1157 /* the encoder has to be flushed before it can be closed */
1158 if (ctx->nvencoder) {
1159 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
1160 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
1162 p_nvenc->nvEncEncodePicture(ctx->nvencoder, ¶ms);
1165 av_fifo_freep(&ctx->timestamp_list);
1166 av_fifo_freep(&ctx->output_surface_ready_queue);
1167 av_fifo_freep(&ctx->output_surface_queue);
1169 if (ctx->surfaces && avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1170 for (i = 0; i < ctx->nb_surfaces; ++i) {
1171 if (ctx->surfaces[i].input_surface) {
1172 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->surfaces[i].in_map.mappedResource);
1175 for (i = 0; i < ctx->nb_registered_frames; i++) {
1176 if (ctx->registered_frames[i].regptr)
1177 p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1179 ctx->nb_registered_frames = 0;
1182 if (ctx->surfaces) {
1183 for (i = 0; i < ctx->nb_surfaces; ++i) {
1184 if (avctx->pix_fmt != AV_PIX_FMT_CUDA)
1185 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
1186 av_frame_free(&ctx->surfaces[i].in_ref);
1187 p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
1190 av_freep(&ctx->surfaces);
1191 ctx->nb_surfaces = 0;
1194 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1195 ctx->nvencoder = NULL;
1197 if (ctx->cu_context_internal)
1198 dl_fn->cu_ctx_destroy(ctx->cu_context_internal);
1199 ctx->cu_context = ctx->cu_context_internal = NULL;
1202 dlclose(dl_fn->nvenc);
1203 dl_fn->nvenc = NULL;
1205 dl_fn->nvenc_device_count = 0;
1209 dlclose(dl_fn->cuda);
1213 dl_fn->cu_init = NULL;
1214 dl_fn->cu_device_get_count = NULL;
1215 dl_fn->cu_device_get = NULL;
1216 dl_fn->cu_device_get_name = NULL;
1217 dl_fn->cu_device_compute_capability = NULL;
1218 dl_fn->cu_ctx_create = NULL;
1219 dl_fn->cu_ctx_pop_current = NULL;
1220 dl_fn->cu_ctx_destroy = NULL;
1222 av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
1227 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
1229 NvencContext *ctx = avctx->priv_data;
1232 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1233 AVHWFramesContext *frames_ctx;
1234 if (!avctx->hw_frames_ctx) {
1235 av_log(avctx, AV_LOG_ERROR,
1236 "hw_frames_ctx must be set when using GPU frames as input\n");
1237 return AVERROR(EINVAL);
1239 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1240 ctx->data_pix_fmt = frames_ctx->sw_format;
1242 ctx->data_pix_fmt = avctx->pix_fmt;
1245 if ((ret = nvenc_load_libraries(avctx)) < 0)
1248 if ((ret = nvenc_setup_device(avctx)) < 0)
1251 if ((ret = nvenc_setup_encoder(avctx)) < 0)
1254 if ((ret = nvenc_setup_surfaces(avctx)) < 0)
1257 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1258 if ((ret = nvenc_setup_extradata(avctx)) < 0)
1265 static NvencSurface *get_free_frame(NvencContext *ctx)
1269 for (i = 0; i < ctx->nb_surfaces; ++i) {
1270 if (!ctx->surfaces[i].lockCount) {
1271 ctx->surfaces[i].lockCount = 1;
1272 return &ctx->surfaces[i];
1279 static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *nv_surface,
1280 NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params, const AVFrame *frame)
1282 int dst_linesize[4] = {
1283 lock_buffer_params->pitch,
1284 lock_buffer_params->pitch,
1285 lock_buffer_params->pitch,
1286 lock_buffer_params->pitch
1288 uint8_t *dst_data[4];
1291 if (frame->format == AV_PIX_FMT_YUV420P)
1292 dst_linesize[1] = dst_linesize[2] >>= 1;
1294 ret = av_image_fill_pointers(dst_data, frame->format, nv_surface->height,
1295 lock_buffer_params->bufferDataPtr, dst_linesize);
1299 if (frame->format == AV_PIX_FMT_YUV420P)
1300 FFSWAP(uint8_t*, dst_data[1], dst_data[2]);
1302 av_image_copy(dst_data, dst_linesize,
1303 (const uint8_t**)frame->data, frame->linesize, frame->format,
1304 nv_surface->width, nv_surface->height);
1309 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1311 NvencContext *ctx = avctx->priv_data;
1312 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1313 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1317 if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1318 for (i = 0; i < ctx->nb_registered_frames; i++) {
1319 if (!ctx->registered_frames[i].mapped) {
1320 if (ctx->registered_frames[i].regptr) {
1321 p_nvenc->nvEncUnregisterResource(ctx->nvencoder,
1322 ctx->registered_frames[i].regptr);
1323 ctx->registered_frames[i].regptr = NULL;
1329 return ctx->nb_registered_frames++;
1332 av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1333 return AVERROR(ENOMEM);
1336 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1338 NvencContext *ctx = avctx->priv_data;
1339 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1340 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1342 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1343 NV_ENC_REGISTER_RESOURCE reg;
1346 for (i = 0; i < ctx->nb_registered_frames; i++) {
1347 if (ctx->registered_frames[i].ptr == (CUdeviceptr)frame->data[0])
1351 idx = nvenc_find_free_reg_resource(avctx);
1355 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1356 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1357 reg.width = frames_ctx->width;
1358 reg.height = frames_ctx->height;
1359 reg.bufferFormat = ctx->surfaces[0].format;
1360 reg.pitch = frame->linesize[0];
1361 reg.resourceToRegister = frame->data[0];
1363 ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, ®);
1364 if (ret != NV_ENC_SUCCESS) {
1365 nvenc_print_error(avctx, ret, "Error registering an input resource");
1366 return AVERROR_UNKNOWN;
1369 ctx->registered_frames[idx].ptr = (CUdeviceptr)frame->data[0];
1370 ctx->registered_frames[idx].regptr = reg.registeredResource;
1374 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1375 NvencSurface *nvenc_frame)
1377 NvencContext *ctx = avctx->priv_data;
1378 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1379 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1382 NVENCSTATUS nv_status;
1384 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1385 int reg_idx = nvenc_register_frame(avctx, frame);
1387 av_log(avctx, AV_LOG_ERROR, "Could not register an input CUDA frame\n");
1391 res = av_frame_ref(nvenc_frame->in_ref, frame);
1395 nvenc_frame->in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1396 nvenc_frame->in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1397 nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &nvenc_frame->in_map);
1398 if (nv_status != NV_ENC_SUCCESS) {
1399 av_frame_unref(nvenc_frame->in_ref);
1400 return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
1403 ctx->registered_frames[reg_idx].mapped = 1;
1404 nvenc_frame->reg_idx = reg_idx;
1405 nvenc_frame->input_surface = nvenc_frame->in_map.mappedResource;
1408 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1410 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1411 lockBufferParams.inputBuffer = nvenc_frame->input_surface;
1413 nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
1414 if (nv_status != NV_ENC_SUCCESS) {
1415 return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
1418 res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
1420 nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
1421 if (nv_status != NV_ENC_SUCCESS) {
1422 return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
1429 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1430 NV_ENC_PIC_PARAMS *params)
1432 NvencContext *ctx = avctx->priv_data;
1434 switch (avctx->codec->id) {
1435 case AV_CODEC_ID_H264:
1436 params->codecPicParams.h264PicParams.sliceMode =
1437 ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1438 params->codecPicParams.h264PicParams.sliceModeData =
1439 ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1441 case AV_CODEC_ID_HEVC:
1442 params->codecPicParams.hevcPicParams.sliceMode =
1443 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1444 params->codecPicParams.hevcPicParams.sliceModeData =
1445 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1450 static inline void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
1452 av_fifo_generic_write(queue, ×tamp, sizeof(timestamp), NULL);
1455 static inline int64_t timestamp_queue_dequeue(AVFifoBuffer* queue)
1457 int64_t timestamp = AV_NOPTS_VALUE;
1458 if (av_fifo_size(queue) > 0)
1459 av_fifo_generic_read(queue, ×tamp, sizeof(timestamp), NULL);
1464 static int nvenc_set_timestamp(AVCodecContext *avctx,
1465 NV_ENC_LOCK_BITSTREAM *params,
1468 NvencContext *ctx = avctx->priv_data;
1470 pkt->pts = params->outputTimeStamp;
1472 /* generate the first dts by linearly extrapolating the
1473 * first two pts values to the past */
1474 if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
1475 ctx->initial_pts[1] != AV_NOPTS_VALUE) {
1476 int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
1479 if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
1480 (ts0 > 0 && ts1 < INT64_MIN + ts0))
1481 return AVERROR(ERANGE);
1484 if ((delta < 0 && ts0 > INT64_MAX + delta) ||
1485 (delta > 0 && ts0 < INT64_MIN + delta))
1486 return AVERROR(ERANGE);
1487 pkt->dts = ts0 - delta;
1489 ctx->first_packet_output = 1;
1493 pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
1498 static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
1500 NvencContext *ctx = avctx->priv_data;
1501 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1502 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1504 uint32_t slice_mode_data;
1505 uint32_t *slice_offsets = NULL;
1506 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1507 NVENCSTATUS nv_status;
1510 enum AVPictureType pict_type;
1512 switch (avctx->codec->id) {
1513 case AV_CODEC_ID_H264:
1514 slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1516 case AV_CODEC_ID_H265:
1517 slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1520 av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
1521 res = AVERROR(EINVAL);
1524 slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
1529 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1531 lock_params.doNotWait = 0;
1532 lock_params.outputBitstream = tmpoutsurf->output_surface;
1533 lock_params.sliceOffsets = slice_offsets;
1535 nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
1536 if (nv_status != NV_ENC_SUCCESS) {
1537 res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
1541 if (res = ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes,0)) {
1542 p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1546 memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1548 nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1549 if (nv_status != NV_ENC_SUCCESS)
1550 nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
1553 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1554 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, tmpoutsurf->in_map.mappedResource);
1555 av_frame_unref(tmpoutsurf->in_ref);
1556 ctx->registered_frames[tmpoutsurf->reg_idx].mapped = 0;
1558 tmpoutsurf->input_surface = NULL;
1561 switch (lock_params.pictureType) {
1562 case NV_ENC_PIC_TYPE_IDR:
1563 pkt->flags |= AV_PKT_FLAG_KEY;
1564 case NV_ENC_PIC_TYPE_I:
1565 pict_type = AV_PICTURE_TYPE_I;
1567 case NV_ENC_PIC_TYPE_P:
1568 pict_type = AV_PICTURE_TYPE_P;
1570 case NV_ENC_PIC_TYPE_B:
1571 pict_type = AV_PICTURE_TYPE_B;
1573 case NV_ENC_PIC_TYPE_BI:
1574 pict_type = AV_PICTURE_TYPE_BI;
1577 av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
1578 av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
1579 res = AVERROR_EXTERNAL;
1583 #if FF_API_CODED_FRAME
1584 FF_DISABLE_DEPRECATION_WARNINGS
1585 avctx->coded_frame->pict_type = pict_type;
1586 FF_ENABLE_DEPRECATION_WARNINGS
1589 ff_side_data_set_encoder_stats(pkt,
1590 (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
1592 res = nvenc_set_timestamp(avctx, &lock_params, pkt);
1596 av_free(slice_offsets);
1601 timestamp_queue_dequeue(ctx->timestamp_list);
1604 av_free(slice_offsets);
1609 static int output_ready(AVCodecContext *avctx, int flush)
1611 NvencContext *ctx = avctx->priv_data;
1612 int nb_ready, nb_pending;
1614 /* when B-frames are enabled, we wait for two initial timestamps to
1615 * calculate the first dts */
1616 if (!flush && avctx->max_b_frames > 0 &&
1617 (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
1620 nb_ready = av_fifo_size(ctx->output_surface_ready_queue) / sizeof(NvencSurface*);
1621 nb_pending = av_fifo_size(ctx->output_surface_queue) / sizeof(NvencSurface*);
1623 return nb_ready > 0;
1624 return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
1627 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1628 const AVFrame *frame, int *got_packet)
1630 NVENCSTATUS nv_status;
1631 NvencSurface *tmpoutsurf, *inSurf;
1634 NvencContext *ctx = avctx->priv_data;
1635 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1636 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1638 NV_ENC_PIC_PARAMS pic_params = { 0 };
1639 pic_params.version = NV_ENC_PIC_PARAMS_VER;
1642 inSurf = get_free_frame(ctx);
1644 av_log(avctx, AV_LOG_ERROR, "No free surfaces\n");
1648 res = nvenc_upload_frame(avctx, frame, inSurf);
1650 inSurf->lockCount = 0;
1654 pic_params.inputBuffer = inSurf->input_surface;
1655 pic_params.bufferFmt = inSurf->format;
1656 pic_params.inputWidth = avctx->width;
1657 pic_params.inputHeight = avctx->height;
1658 pic_params.outputBitstream = inSurf->output_surface;
1660 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1661 if (frame->top_field_first)
1662 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
1664 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
1666 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1669 pic_params.encodePicFlags = 0;
1670 pic_params.inputTimeStamp = frame->pts;
1672 nvenc_codec_specific_pic_params(avctx, &pic_params);
1674 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1677 nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
1678 if (nv_status != NV_ENC_SUCCESS &&
1679 nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
1680 return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
1683 av_fifo_generic_write(ctx->output_surface_queue, &inSurf, sizeof(inSurf), NULL);
1684 timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
1686 if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
1687 ctx->initial_pts[0] = frame->pts;
1688 else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
1689 ctx->initial_pts[1] = frame->pts;
1692 /* all the pending buffers are now ready for output */
1693 if (nv_status == NV_ENC_SUCCESS) {
1694 while (av_fifo_size(ctx->output_surface_queue) > 0) {
1695 av_fifo_generic_read(ctx->output_surface_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
1696 av_fifo_generic_write(ctx->output_surface_ready_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
1700 if (output_ready(avctx, !frame)) {
1701 av_fifo_generic_read(ctx->output_surface_ready_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
1703 res = process_output_surface(avctx, pkt, tmpoutsurf);
1708 av_assert0(tmpoutsurf->lockCount);
1709 tmpoutsurf->lockCount--;