2 * H.264 hardware encoding using nvidia nvenc
3 * Copyright (c) 2014 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"
33 # define NVENC_LIBNAME "libnvidia-encode.so"
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 PNVENCODEAPICREATEINSTANCE nvenc_create_instance;
162 dl_fn->cu_init = cuInit;
163 dl_fn->cu_device_get_count = cuDeviceGetCount;
164 dl_fn->cu_device_get = cuDeviceGet;
165 dl_fn->cu_device_get_name = cuDeviceGetName;
166 dl_fn->cu_device_compute_capability = cuDeviceComputeCapability;
167 dl_fn->cu_ctx_create = cuCtxCreate_v2;
168 dl_fn->cu_ctx_pop_current = cuCtxPopCurrent_v2;
169 dl_fn->cu_ctx_destroy = cuCtxDestroy_v2;
171 LOAD_LIBRARY(dl_fn->cuda, CUDA_LIBNAME);
173 LOAD_SYMBOL(dl_fn->cu_init, dl_fn->cuda, "cuInit");
174 LOAD_SYMBOL(dl_fn->cu_device_get_count, dl_fn->cuda, "cuDeviceGetCount");
175 LOAD_SYMBOL(dl_fn->cu_device_get, dl_fn->cuda, "cuDeviceGet");
176 LOAD_SYMBOL(dl_fn->cu_device_get_name, dl_fn->cuda, "cuDeviceGetName");
177 LOAD_SYMBOL(dl_fn->cu_device_compute_capability, dl_fn->cuda,
178 "cuDeviceComputeCapability");
179 LOAD_SYMBOL(dl_fn->cu_ctx_create, dl_fn->cuda, "cuCtxCreate_v2");
180 LOAD_SYMBOL(dl_fn->cu_ctx_pop_current, dl_fn->cuda, "cuCtxPopCurrent_v2");
181 LOAD_SYMBOL(dl_fn->cu_ctx_destroy, dl_fn->cuda, "cuCtxDestroy_v2");
184 LOAD_LIBRARY(dl_fn->nvenc, NVENC_LIBNAME);
186 LOAD_SYMBOL(nvenc_create_instance, dl_fn->nvenc,
187 "NvEncodeAPICreateInstance");
189 dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
191 err = nvenc_create_instance(&dl_fn->nvenc_funcs);
192 if (err != NV_ENC_SUCCESS)
193 return nvenc_print_error(avctx, err, "Failed to create nvenc instance");
195 av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
200 static av_cold int nvenc_open_session(AVCodecContext *avctx)
202 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
203 NvencContext *ctx = avctx->priv_data;
204 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
207 params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
208 params.apiVersion = NVENCAPI_VERSION;
209 params.device = ctx->cu_context;
210 params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
212 ret = p_nvenc->nvEncOpenEncodeSessionEx(¶ms, &ctx->nvencoder);
213 if (ret != NV_ENC_SUCCESS) {
214 ctx->nvencoder = NULL;
215 return nvenc_print_error(avctx, ret, "OpenEncodeSessionEx failed");
221 static int nvenc_check_codec_support(AVCodecContext *avctx)
223 NvencContext *ctx = avctx->priv_data;
224 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
225 int i, ret, count = 0;
228 ret = p_nvenc->nvEncGetEncodeGUIDCount(ctx->nvencoder, &count);
230 if (ret != NV_ENC_SUCCESS || !count)
231 return AVERROR(ENOSYS);
233 guids = av_malloc(count * sizeof(GUID));
235 return AVERROR(ENOMEM);
237 ret = p_nvenc->nvEncGetEncodeGUIDs(ctx->nvencoder, guids, count, &count);
238 if (ret != NV_ENC_SUCCESS) {
239 ret = AVERROR(ENOSYS);
243 ret = AVERROR(ENOSYS);
244 for (i = 0; i < count; i++) {
245 if (!memcmp(&guids[i], &ctx->init_encode_params.encodeGUID, sizeof(*guids))) {
257 static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
259 NvencContext *ctx = avctx->priv_data;
260 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
261 NV_ENC_CAPS_PARAM params = { 0 };
264 params.version = NV_ENC_CAPS_PARAM_VER;
265 params.capsToQuery = cap;
267 ret = p_nvenc->nvEncGetEncodeCaps(ctx->nvencoder, ctx->init_encode_params.encodeGUID, ¶ms, &val);
269 if (ret == NV_ENC_SUCCESS)
274 static int nvenc_check_capabilities(AVCodecContext *avctx)
276 NvencContext *ctx = avctx->priv_data;
279 ret = nvenc_check_codec_support(avctx);
281 av_log(avctx, AV_LOG_VERBOSE, "Codec not supported\n");
285 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
286 if (IS_YUV444(ctx->data_pix_fmt) && ret <= 0) {
287 av_log(avctx, AV_LOG_VERBOSE, "YUV444P not supported\n");
288 return AVERROR(ENOSYS);
291 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOSSLESS_ENCODE);
292 if (ctx->preset >= PRESET_LOSSLESS_DEFAULT && ret <= 0) {
293 av_log(avctx, AV_LOG_VERBOSE, "Lossless encoding not supported\n");
294 return AVERROR(ENOSYS);
297 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
298 if (ret < avctx->width) {
299 av_log(avctx, AV_LOG_VERBOSE, "Width %d exceeds %d\n",
301 return AVERROR(ENOSYS);
304 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
305 if (ret < avctx->height) {
306 av_log(avctx, AV_LOG_VERBOSE, "Height %d exceeds %d\n",
308 return AVERROR(ENOSYS);
311 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
312 if (ret < avctx->max_b_frames) {
313 av_log(avctx, AV_LOG_VERBOSE, "Max B-frames %d exceed %d\n",
314 avctx->max_b_frames, ret);
316 return AVERROR(ENOSYS);
319 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_FIELD_ENCODING);
320 if (ret < 1 && avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
321 av_log(avctx, AV_LOG_VERBOSE,
322 "Interlaced encoding is not supported. Supported level: %d\n",
324 return AVERROR(ENOSYS);
327 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_10BIT_ENCODE);
328 if (IS_10BIT(ctx->data_pix_fmt) && ret <= 0) {
329 av_log(avctx, AV_LOG_VERBOSE, "10 bit encode not supported\n");
330 return AVERROR(ENOSYS);
333 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOOKAHEAD);
334 if (ctx->rc_lookahead > 0 && ret <= 0) {
335 av_log(avctx, AV_LOG_VERBOSE, "RC lookahead not supported\n");
336 return AVERROR(ENOSYS);
342 static av_cold int nvenc_check_device(AVCodecContext *avctx, int idx)
344 NvencContext *ctx = avctx->priv_data;
345 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
346 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
347 char name[128] = { 0};
348 int major, minor, ret;
352 int loglevel = AV_LOG_VERBOSE;
354 if (ctx->device == LIST_DEVICES)
355 loglevel = AV_LOG_INFO;
357 cu_res = dl_fn->cu_device_get(&cu_device, idx);
358 if (cu_res != CUDA_SUCCESS) {
359 av_log(avctx, AV_LOG_ERROR,
360 "Cannot access the CUDA device %d\n",
365 cu_res = dl_fn->cu_device_get_name(name, sizeof(name), cu_device);
366 if (cu_res != CUDA_SUCCESS)
369 cu_res = dl_fn->cu_device_compute_capability(&major, &minor, cu_device);
370 if (cu_res != CUDA_SUCCESS)
373 av_log(avctx, loglevel, "[ GPU #%d - < %s > has Compute SM %d.%d ]\n", idx, name, major, minor);
374 if (((major << 4) | minor) < NVENC_CAP) {
375 av_log(avctx, loglevel, "does not support NVENC\n");
379 cu_res = dl_fn->cu_ctx_create(&ctx->cu_context_internal, 0, cu_device);
380 if (cu_res != CUDA_SUCCESS) {
381 av_log(avctx, AV_LOG_FATAL, "Failed creating CUDA context for NVENC: 0x%x\n", (int)cu_res);
385 ctx->cu_context = ctx->cu_context_internal;
387 cu_res = dl_fn->cu_ctx_pop_current(&dummy);
388 if (cu_res != CUDA_SUCCESS) {
389 av_log(avctx, AV_LOG_FATAL, "Failed popping CUDA context: 0x%x\n", (int)cu_res);
393 if ((ret = nvenc_open_session(avctx)) < 0)
396 if ((ret = nvenc_check_capabilities(avctx)) < 0)
399 av_log(avctx, loglevel, "supports NVENC\n");
401 dl_fn->nvenc_device_count++;
403 if (ctx->device == dl_fn->nvenc_device_count - 1 || ctx->device == ANY_DEVICE)
407 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
408 ctx->nvencoder = NULL;
411 dl_fn->cu_ctx_destroy(ctx->cu_context_internal);
412 ctx->cu_context_internal = NULL;
415 return AVERROR(ENOSYS);
418 static av_cold int nvenc_setup_device(AVCodecContext *avctx)
420 NvencContext *ctx = avctx->priv_data;
421 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
423 switch (avctx->codec->id) {
424 case AV_CODEC_ID_H264:
425 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
427 case AV_CODEC_ID_HEVC:
428 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
434 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
436 AVHWFramesContext *frames_ctx;
437 AVCUDADeviceContext *device_hwctx;
440 if (!avctx->hw_frames_ctx)
441 return AVERROR(EINVAL);
443 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
444 device_hwctx = frames_ctx->device_ctx->hwctx;
446 ctx->cu_context = device_hwctx->cuda_ctx;
448 ret = nvenc_open_session(avctx);
452 ret = nvenc_check_capabilities(avctx);
454 av_log(avctx, AV_LOG_FATAL, "Provided device doesn't support required NVENC features\n");
461 int i, nb_devices = 0;
463 if ((dl_fn->cu_init(0)) != CUDA_SUCCESS) {
464 av_log(avctx, AV_LOG_ERROR,
465 "Cannot init CUDA\n");
466 return AVERROR_UNKNOWN;
469 if ((dl_fn->cu_device_get_count(&nb_devices)) != CUDA_SUCCESS) {
470 av_log(avctx, AV_LOG_ERROR,
471 "Cannot enumerate the CUDA devices\n");
472 return AVERROR_UNKNOWN;
476 av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
477 return AVERROR_EXTERNAL;
480 av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", nb_devices);
482 dl_fn->nvenc_device_count = 0;
483 for (i = 0; i < nb_devices; ++i) {
484 if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
488 if (ctx->device == LIST_DEVICES)
491 if (!dl_fn->nvenc_device_count) {
492 av_log(avctx, AV_LOG_FATAL, "No NVENC capable devices found\n");
493 return AVERROR_EXTERNAL;
496 av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->device, dl_fn->nvenc_device_count);
497 return AVERROR(EINVAL);
503 typedef struct GUIDTuple {
508 static void nvenc_map_preset(NvencContext *ctx)
510 GUIDTuple presets[] = {
511 { NV_ENC_PRESET_DEFAULT_GUID },
512 { NV_ENC_PRESET_HQ_GUID, NVENC_TWO_PASSES }, /* slow */
513 { NV_ENC_PRESET_HQ_GUID, NVENC_ONE_PASS }, /* medium */
514 { NV_ENC_PRESET_HP_GUID, NVENC_ONE_PASS }, /* fast */
515 { NV_ENC_PRESET_HP_GUID },
516 { NV_ENC_PRESET_HQ_GUID },
517 { NV_ENC_PRESET_BD_GUID },
518 { NV_ENC_PRESET_LOW_LATENCY_DEFAULT_GUID, NVENC_LOWLATENCY },
519 { NV_ENC_PRESET_LOW_LATENCY_HQ_GUID, NVENC_LOWLATENCY },
520 { NV_ENC_PRESET_LOW_LATENCY_HP_GUID, NVENC_LOWLATENCY },
521 { NV_ENC_PRESET_LOSSLESS_DEFAULT_GUID, NVENC_LOSSLESS },
522 { NV_ENC_PRESET_LOSSLESS_HP_GUID, NVENC_LOSSLESS },
525 GUIDTuple *t = &presets[ctx->preset];
527 ctx->init_encode_params.presetGUID = t->guid;
528 ctx->flags = t->flags;
531 static av_cold void set_constqp(AVCodecContext *avctx)
533 NvencContext *ctx = avctx->priv_data;
534 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
536 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
537 rc->constQP.qpInterB = avctx->global_quality;
538 rc->constQP.qpInterP = avctx->global_quality;
539 rc->constQP.qpIntra = avctx->global_quality;
545 static av_cold void set_vbr(AVCodecContext *avctx)
547 NvencContext *ctx = avctx->priv_data;
548 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
551 if (avctx->qmin >= 0 && avctx->qmax >= 0) {
555 rc->minQP.qpInterB = avctx->qmin;
556 rc->minQP.qpInterP = avctx->qmin;
557 rc->minQP.qpIntra = avctx->qmin;
559 rc->maxQP.qpInterB = avctx->qmax;
560 rc->maxQP.qpInterP = avctx->qmax;
561 rc->maxQP.qpIntra = avctx->qmax;
563 qp_inter_p = (avctx->qmax + 3 * avctx->qmin) / 4; // biased towards Qmin
564 } else if (avctx->qmin >= 0) {
567 rc->minQP.qpInterB = avctx->qmin;
568 rc->minQP.qpInterP = avctx->qmin;
569 rc->minQP.qpIntra = avctx->qmin;
571 qp_inter_p = avctx->qmin;
573 qp_inter_p = 26; // default to 26
576 rc->enableInitialRCQP = 1;
577 rc->initialRCQP.qpInterP = qp_inter_p;
579 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
580 rc->initialRCQP.qpIntra = av_clip(
581 qp_inter_p * fabs(avctx->i_quant_factor) + avctx->i_quant_offset, 0, 51);
582 rc->initialRCQP.qpInterB = av_clip(
583 qp_inter_p * fabs(avctx->b_quant_factor) + avctx->b_quant_offset, 0, 51);
585 rc->initialRCQP.qpIntra = qp_inter_p;
586 rc->initialRCQP.qpInterB = qp_inter_p;
590 static av_cold void set_lossless(AVCodecContext *avctx)
592 NvencContext *ctx = avctx->priv_data;
593 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
595 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
596 rc->constQP.qpInterB = 0;
597 rc->constQP.qpInterP = 0;
598 rc->constQP.qpIntra = 0;
604 static void nvenc_override_rate_control(AVCodecContext *avctx)
606 NvencContext *ctx = avctx->priv_data;
607 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
610 case NV_ENC_PARAMS_RC_CONSTQP:
611 if (avctx->global_quality <= 0) {
612 av_log(avctx, AV_LOG_WARNING,
613 "The constant quality rate-control requires "
614 "the 'global_quality' option set.\n");
619 case NV_ENC_PARAMS_RC_2_PASS_VBR:
620 case NV_ENC_PARAMS_RC_VBR:
621 if (avctx->qmin < 0 && avctx->qmax < 0) {
622 av_log(avctx, AV_LOG_WARNING,
623 "The variable bitrate rate-control requires "
624 "the 'qmin' and/or 'qmax' option set.\n");
628 case NV_ENC_PARAMS_RC_VBR_MINQP:
629 if (avctx->qmin < 0) {
630 av_log(avctx, AV_LOG_WARNING,
631 "The variable bitrate rate-control requires "
632 "the 'qmin' option set.\n");
638 case NV_ENC_PARAMS_RC_CBR:
639 case NV_ENC_PARAMS_RC_2_PASS_QUALITY:
640 case NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP:
644 rc->rateControlMode = ctx->rc;
647 static av_cold void nvenc_setup_rate_control(AVCodecContext *avctx)
649 NvencContext *ctx = avctx->priv_data;
651 if (avctx->bit_rate > 0) {
652 ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
653 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
654 ctx->encode_config.rcParams.maxBitRate = ctx->encode_config.rcParams.averageBitRate;
657 if (avctx->rc_max_rate > 0)
658 ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
661 if (ctx->flags & NVENC_ONE_PASS)
663 if (ctx->flags & NVENC_TWO_PASSES)
666 if (ctx->twopass < 0)
667 ctx->twopass = (ctx->flags & NVENC_LOWLATENCY) != 0;
671 ctx->rc = NV_ENC_PARAMS_RC_2_PASS_QUALITY;
673 ctx->rc = NV_ENC_PARAMS_RC_CBR;
675 } else if (avctx->global_quality > 0) {
676 ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
677 } else if (ctx->twopass) {
678 ctx->rc = NV_ENC_PARAMS_RC_2_PASS_VBR;
679 } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
680 ctx->rc = NV_ENC_PARAMS_RC_VBR_MINQP;
684 if (ctx->flags & NVENC_LOSSLESS) {
686 } else if (ctx->rc >= 0) {
687 nvenc_override_rate_control(avctx);
689 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
693 if (avctx->rc_buffer_size > 0) {
694 ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
695 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
696 ctx->encode_config.rcParams.vbvBufferSize = 2 * ctx->encode_config.rcParams.averageBitRate;
699 if (ctx->rc_lookahead > 0) {
700 ctx->encode_config.rcParams.enableLookahead = 1;
701 ctx->encode_config.rcParams.lookaheadDepth = FFMIN(ctx->rc_lookahead, 32);
705 static av_cold int nvenc_setup_h264_config(AVCodecContext *avctx)
707 NvencContext *ctx = avctx->priv_data;
708 NV_ENC_CONFIG *cc = &ctx->encode_config;
709 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
710 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
712 vui->colourMatrix = avctx->colorspace;
713 vui->colourPrimaries = avctx->color_primaries;
714 vui->transferCharacteristics = avctx->color_trc;
715 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
716 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
718 vui->colourDescriptionPresentFlag =
719 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
721 vui->videoSignalTypePresentFlag =
722 (vui->colourDescriptionPresentFlag
723 || vui->videoFormat != 5
724 || vui->videoFullRangeFlag != 0);
727 h264->sliceModeData = 1;
729 h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
730 h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
733 if (avctx->refs >= 0) {
734 /* 0 means "let the hardware decide" */
735 h264->maxNumRefFrames = avctx->refs;
737 if (avctx->gop_size >= 0) {
738 h264->idrPeriod = cc->gopLength;
741 if (IS_CBR(cc->rcParams.rateControlMode)) {
742 h264->outputBufferingPeriodSEI = 1;
743 h264->outputPictureTimingSEI = 1;
746 if (cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_2_PASS_QUALITY ||
747 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP ||
748 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_2_PASS_VBR) {
749 h264->adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
750 h264->fmoMode = NV_ENC_H264_FMO_DISABLE;
753 if (ctx->flags & NVENC_LOSSLESS) {
754 h264->qpPrimeYZeroTransformBypassFlag = 1;
756 switch(ctx->profile) {
757 case NV_ENC_H264_PROFILE_BASELINE:
758 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
759 avctx->profile = FF_PROFILE_H264_BASELINE;
761 case NV_ENC_H264_PROFILE_MAIN:
762 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
763 avctx->profile = FF_PROFILE_H264_MAIN;
765 case NV_ENC_H264_PROFILE_HIGH:
766 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
767 avctx->profile = FF_PROFILE_H264_HIGH;
769 case NV_ENC_H264_PROFILE_HIGH_444P:
770 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
771 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
776 // force setting profile as high444p if input is AV_PIX_FMT_YUV444P
777 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P) {
778 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
779 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
782 h264->chromaFormatIDC = avctx->profile == FF_PROFILE_H264_HIGH_444_PREDICTIVE ? 3 : 1;
784 h264->level = ctx->level;
789 static av_cold int nvenc_setup_hevc_config(AVCodecContext *avctx)
791 NvencContext *ctx = avctx->priv_data;
792 NV_ENC_CONFIG *cc = &ctx->encode_config;
793 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
794 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
796 vui->colourMatrix = avctx->colorspace;
797 vui->colourPrimaries = avctx->color_primaries;
798 vui->transferCharacteristics = avctx->color_trc;
799 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
800 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
802 vui->colourDescriptionPresentFlag =
803 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
805 vui->videoSignalTypePresentFlag =
806 (vui->colourDescriptionPresentFlag
807 || vui->videoFormat != 5
808 || vui->videoFullRangeFlag != 0);
811 hevc->sliceModeData = 1;
813 hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
814 hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
817 if (avctx->refs >= 0) {
818 /* 0 means "let the hardware decide" */
819 hevc->maxNumRefFramesInDPB = avctx->refs;
821 if (avctx->gop_size >= 0) {
822 hevc->idrPeriod = cc->gopLength;
825 if (IS_CBR(cc->rcParams.rateControlMode)) {
826 hevc->outputBufferingPeriodSEI = 1;
827 hevc->outputPictureTimingSEI = 1;
830 switch(ctx->profile) {
831 case NV_ENC_HEVC_PROFILE_MAIN:
832 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
833 avctx->profile = FF_PROFILE_HEVC_MAIN;
835 case NV_ENC_HEVC_PROFILE_MAIN_10:
836 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
837 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
841 // force setting profile as main10 if input is 10 bit
842 if (IS_10BIT(ctx->data_pix_fmt)) {
843 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
844 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
847 hevc->chromaFormatIDC = IS_YUV444(ctx->data_pix_fmt) ? 3 : 1;
849 hevc->pixelBitDepthMinus8 = IS_10BIT(ctx->data_pix_fmt) ? 2 : 0;
851 hevc->level = ctx->level;
853 hevc->tier = ctx->tier;
858 static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx)
860 switch (avctx->codec->id) {
861 case AV_CODEC_ID_H264:
862 return nvenc_setup_h264_config(avctx);
863 case AV_CODEC_ID_HEVC:
864 return nvenc_setup_hevc_config(avctx);
865 /* Earlier switch/case will return if unknown codec is passed. */
871 static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
873 NvencContext *ctx = avctx->priv_data;
874 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
875 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
877 NV_ENC_PRESET_CONFIG preset_config = { 0 };
878 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
879 AVCPBProperties *cpb_props;
883 ctx->encode_config.version = NV_ENC_CONFIG_VER;
884 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
886 ctx->init_encode_params.encodeHeight = avctx->height;
887 ctx->init_encode_params.encodeWidth = avctx->width;
889 ctx->init_encode_params.encodeConfig = &ctx->encode_config;
891 nvenc_map_preset(ctx);
893 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
894 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
896 nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder,
897 ctx->init_encode_params.encodeGUID,
898 ctx->init_encode_params.presetGUID,
900 if (nv_status != NV_ENC_SUCCESS)
901 return nvenc_print_error(avctx, nv_status, "Cannot get the preset configuration");
903 memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
905 ctx->encode_config.version = NV_ENC_CONFIG_VER;
907 if (avctx->sample_aspect_ratio.num && avctx->sample_aspect_ratio.den &&
908 (avctx->sample_aspect_ratio.num != 1 || avctx->sample_aspect_ratio.num != 1)) {
910 avctx->width * avctx->sample_aspect_ratio.num,
911 avctx->height * avctx->sample_aspect_ratio.den,
913 ctx->init_encode_params.darHeight = dh;
914 ctx->init_encode_params.darWidth = dw;
916 ctx->init_encode_params.darHeight = avctx->height;
917 ctx->init_encode_params.darWidth = avctx->width;
920 // De-compensate for hardware, dubiously, trying to compensate for
921 // playback at 704 pixel width.
922 if (avctx->width == 720 &&
923 (avctx->height == 480 || avctx->height == 576)) {
925 ctx->init_encode_params.darWidth * 44,
926 ctx->init_encode_params.darHeight * 45,
928 ctx->init_encode_params.darHeight = dh;
929 ctx->init_encode_params.darWidth = dw;
932 ctx->init_encode_params.frameRateNum = avctx->time_base.den;
933 ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
935 ctx->init_encode_params.enableEncodeAsync = 0;
936 ctx->init_encode_params.enablePTD = 1;
938 if (avctx->gop_size > 0) {
939 if (avctx->max_b_frames >= 0) {
940 /* 0 is intra-only, 1 is I/P only, 2 is one B-Frame, 3 two B-frames, and so on. */
941 ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
944 ctx->encode_config.gopLength = avctx->gop_size;
945 } else if (avctx->gop_size == 0) {
946 ctx->encode_config.frameIntervalP = 0;
947 ctx->encode_config.gopLength = 1;
950 ctx->initial_pts[0] = AV_NOPTS_VALUE;
951 ctx->initial_pts[1] = AV_NOPTS_VALUE;
953 nvenc_setup_rate_control(avctx);
955 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
956 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
958 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
961 res = nvenc_setup_codec_config(avctx);
965 nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
966 if (nv_status != NV_ENC_SUCCESS) {
967 return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
970 if (ctx->encode_config.frameIntervalP > 1)
971 avctx->has_b_frames = 2;
973 if (ctx->encode_config.rcParams.averageBitRate > 0)
974 avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
976 cpb_props = ff_add_cpb_side_data(avctx);
978 return AVERROR(ENOMEM);
979 cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
980 cpb_props->avg_bitrate = avctx->bit_rate;
981 cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
986 static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
988 NvencContext *ctx = avctx->priv_data;
989 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
990 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
992 NVENCSTATUS nv_status;
993 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
994 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
996 switch (ctx->data_pix_fmt) {
997 case AV_PIX_FMT_YUV420P:
998 ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_YV12_PL;
1001 case AV_PIX_FMT_NV12:
1002 ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_NV12_PL;
1005 case AV_PIX_FMT_P010:
1006 ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1009 case AV_PIX_FMT_YUV444P:
1010 ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_YUV444_PL;
1013 case AV_PIX_FMT_YUV444P16:
1014 ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1018 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format\n");
1019 return AVERROR(EINVAL);
1022 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1023 ctx->surfaces[idx].in_ref = av_frame_alloc();
1024 if (!ctx->surfaces[idx].in_ref)
1025 return AVERROR(ENOMEM);
1027 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1028 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1029 allocSurf.width = (avctx->width + 31) & ~31;
1030 allocSurf.height = (avctx->height + 31) & ~31;
1031 allocSurf.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
1032 allocSurf.bufferFmt = ctx->surfaces[idx].format;
1034 nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
1035 if (nv_status != NV_ENC_SUCCESS) {
1036 return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
1039 ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
1040 ctx->surfaces[idx].width = allocSurf.width;
1041 ctx->surfaces[idx].height = allocSurf.height;
1044 ctx->surfaces[idx].lockCount = 0;
1046 /* 1MB is large enough to hold most output frames.
1047 * NVENC increases this automaticaly if it is not enough. */
1048 allocOut.size = 1024 * 1024;
1050 allocOut.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
1052 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
1053 if (nv_status != NV_ENC_SUCCESS) {
1054 int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
1055 if (avctx->pix_fmt != AV_PIX_FMT_CUDA)
1056 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
1057 av_frame_free(&ctx->surfaces[idx].in_ref);
1061 ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1062 ctx->surfaces[idx].size = allocOut.size;
1067 static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx)
1069 NvencContext *ctx = avctx->priv_data;
1071 int num_mbs = ((avctx->width + 15) >> 4) * ((avctx->height + 15) >> 4);
1072 ctx->nb_surfaces = FFMAX((num_mbs >= 8160) ? 32 : 48,
1074 ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
1077 ctx->surfaces = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->surfaces));
1079 return AVERROR(ENOMEM);
1081 ctx->timestamp_list = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
1082 if (!ctx->timestamp_list)
1083 return AVERROR(ENOMEM);
1084 ctx->output_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1085 if (!ctx->output_surface_queue)
1086 return AVERROR(ENOMEM);
1087 ctx->output_surface_ready_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1088 if (!ctx->output_surface_ready_queue)
1089 return AVERROR(ENOMEM);
1091 for (i = 0; i < ctx->nb_surfaces; i++) {
1092 if ((res = nvenc_alloc_surface(avctx, i)) < 0)
1099 static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
1101 NvencContext *ctx = avctx->priv_data;
1102 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1103 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1105 NVENCSTATUS nv_status;
1106 uint32_t outSize = 0;
1107 char tmpHeader[256];
1108 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1109 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1111 payload.spsppsBuffer = tmpHeader;
1112 payload.inBufferSize = sizeof(tmpHeader);
1113 payload.outSPSPPSPayloadSize = &outSize;
1115 nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
1116 if (nv_status != NV_ENC_SUCCESS) {
1117 return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
1120 avctx->extradata_size = outSize;
1121 avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
1123 if (!avctx->extradata) {
1124 return AVERROR(ENOMEM);
1127 memcpy(avctx->extradata, tmpHeader, outSize);
1132 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
1134 NvencContext *ctx = avctx->priv_data;
1135 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1136 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1139 /* the encoder has to be flushed before it can be closed */
1140 if (ctx->nvencoder) {
1141 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
1142 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
1144 p_nvenc->nvEncEncodePicture(ctx->nvencoder, ¶ms);
1147 av_fifo_freep(&ctx->timestamp_list);
1148 av_fifo_freep(&ctx->output_surface_ready_queue);
1149 av_fifo_freep(&ctx->output_surface_queue);
1151 if (ctx->surfaces && avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1152 for (i = 0; i < ctx->nb_surfaces; ++i) {
1153 if (ctx->surfaces[i].input_surface) {
1154 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->surfaces[i].in_map.mappedResource);
1157 for (i = 0; i < ctx->nb_registered_frames; i++) {
1158 if (ctx->registered_frames[i].regptr)
1159 p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1161 ctx->nb_registered_frames = 0;
1164 if (ctx->surfaces) {
1165 for (i = 0; i < ctx->nb_surfaces; ++i) {
1166 if (avctx->pix_fmt != AV_PIX_FMT_CUDA)
1167 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
1168 av_frame_free(&ctx->surfaces[i].in_ref);
1169 p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
1172 av_freep(&ctx->surfaces);
1173 ctx->nb_surfaces = 0;
1176 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1177 ctx->nvencoder = NULL;
1179 if (ctx->cu_context_internal)
1180 dl_fn->cu_ctx_destroy(ctx->cu_context_internal);
1181 ctx->cu_context = ctx->cu_context_internal = NULL;
1184 dlclose(dl_fn->nvenc);
1185 dl_fn->nvenc = NULL;
1187 dl_fn->nvenc_device_count = 0;
1191 dlclose(dl_fn->cuda);
1195 dl_fn->cu_init = NULL;
1196 dl_fn->cu_device_get_count = NULL;
1197 dl_fn->cu_device_get = NULL;
1198 dl_fn->cu_device_get_name = NULL;
1199 dl_fn->cu_device_compute_capability = NULL;
1200 dl_fn->cu_ctx_create = NULL;
1201 dl_fn->cu_ctx_pop_current = NULL;
1202 dl_fn->cu_ctx_destroy = NULL;
1204 av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
1209 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
1211 NvencContext *ctx = avctx->priv_data;
1214 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1215 AVHWFramesContext *frames_ctx;
1216 if (!avctx->hw_frames_ctx) {
1217 av_log(avctx, AV_LOG_ERROR,
1218 "hw_frames_ctx must be set when using GPU frames as input\n");
1219 return AVERROR(EINVAL);
1221 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1222 ctx->data_pix_fmt = frames_ctx->sw_format;
1224 ctx->data_pix_fmt = avctx->pix_fmt;
1227 if ((ret = nvenc_load_libraries(avctx)) < 0)
1230 if ((ret = nvenc_setup_device(avctx)) < 0)
1233 if ((ret = nvenc_setup_encoder(avctx)) < 0)
1236 if ((ret = nvenc_setup_surfaces(avctx)) < 0)
1239 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1240 if ((ret = nvenc_setup_extradata(avctx)) < 0)
1247 static NvencSurface *get_free_frame(NvencContext *ctx)
1251 for (i = 0; i < ctx->nb_surfaces; ++i) {
1252 if (!ctx->surfaces[i].lockCount) {
1253 ctx->surfaces[i].lockCount = 1;
1254 return &ctx->surfaces[i];
1261 static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *inSurf,
1262 NV_ENC_LOCK_INPUT_BUFFER *lockBufferParams, const AVFrame *frame)
1264 uint8_t *buf = lockBufferParams->bufferDataPtr;
1265 int off = inSurf->height * lockBufferParams->pitch;
1267 if (frame->format == AV_PIX_FMT_YUV420P) {
1268 av_image_copy_plane(buf, lockBufferParams->pitch,
1269 frame->data[0], frame->linesize[0],
1270 avctx->width, avctx->height);
1274 av_image_copy_plane(buf, lockBufferParams->pitch >> 1,
1275 frame->data[2], frame->linesize[2],
1276 avctx->width >> 1, avctx->height >> 1);
1280 av_image_copy_plane(buf, lockBufferParams->pitch >> 1,
1281 frame->data[1], frame->linesize[1],
1282 avctx->width >> 1, avctx->height >> 1);
1283 } else if (frame->format == AV_PIX_FMT_NV12) {
1284 av_image_copy_plane(buf, lockBufferParams->pitch,
1285 frame->data[0], frame->linesize[0],
1286 avctx->width, avctx->height);
1290 av_image_copy_plane(buf, lockBufferParams->pitch,
1291 frame->data[1], frame->linesize[1],
1292 avctx->width, avctx->height >> 1);
1293 } else if (frame->format == AV_PIX_FMT_P010) {
1294 av_image_copy_plane(buf, lockBufferParams->pitch,
1295 frame->data[0], frame->linesize[0],
1296 avctx->width << 1, avctx->height);
1300 av_image_copy_plane(buf, lockBufferParams->pitch,
1301 frame->data[1], frame->linesize[1],
1302 avctx->width << 1, avctx->height >> 1);
1303 } else if (frame->format == AV_PIX_FMT_YUV444P) {
1304 av_image_copy_plane(buf, lockBufferParams->pitch,
1305 frame->data[0], frame->linesize[0],
1306 avctx->width, avctx->height);
1310 av_image_copy_plane(buf, lockBufferParams->pitch,
1311 frame->data[1], frame->linesize[1],
1312 avctx->width, avctx->height);
1316 av_image_copy_plane(buf, lockBufferParams->pitch,
1317 frame->data[2], frame->linesize[2],
1318 avctx->width, avctx->height);
1319 } else if (frame->format == AV_PIX_FMT_YUV444P16) {
1320 av_image_copy_plane(buf, lockBufferParams->pitch,
1321 frame->data[0], frame->linesize[0],
1322 avctx->width << 1, avctx->height);
1326 av_image_copy_plane(buf, lockBufferParams->pitch,
1327 frame->data[1], frame->linesize[1],
1328 avctx->width << 1, avctx->height);
1332 av_image_copy_plane(buf, lockBufferParams->pitch,
1333 frame->data[2], frame->linesize[2],
1334 avctx->width << 1, avctx->height);
1336 av_log(avctx, AV_LOG_FATAL, "Invalid pixel format!\n");
1337 return AVERROR(EINVAL);
1343 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1345 NvencContext *ctx = avctx->priv_data;
1346 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1347 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1351 if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1352 for (i = 0; i < ctx->nb_registered_frames; i++) {
1353 if (!ctx->registered_frames[i].mapped) {
1354 if (ctx->registered_frames[i].regptr) {
1355 p_nvenc->nvEncUnregisterResource(ctx->nvencoder,
1356 ctx->registered_frames[i].regptr);
1357 ctx->registered_frames[i].regptr = NULL;
1363 return ctx->nb_registered_frames++;
1366 av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1367 return AVERROR(ENOMEM);
1370 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1372 NvencContext *ctx = avctx->priv_data;
1373 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1374 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1376 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1377 NV_ENC_REGISTER_RESOURCE reg;
1380 for (i = 0; i < ctx->nb_registered_frames; i++) {
1381 if (ctx->registered_frames[i].ptr == (CUdeviceptr)frame->data[0])
1385 idx = nvenc_find_free_reg_resource(avctx);
1389 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1390 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1391 reg.width = frames_ctx->width;
1392 reg.height = frames_ctx->height;
1393 reg.bufferFormat = ctx->surfaces[0].format;
1394 reg.pitch = frame->linesize[0];
1395 reg.resourceToRegister = frame->data[0];
1397 ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, ®);
1398 if (ret != NV_ENC_SUCCESS) {
1399 nvenc_print_error(avctx, ret, "Error registering an input resource");
1400 return AVERROR_UNKNOWN;
1403 ctx->registered_frames[idx].ptr = (CUdeviceptr)frame->data[0];
1404 ctx->registered_frames[idx].regptr = reg.registeredResource;
1408 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1409 NvencSurface *nvenc_frame)
1411 NvencContext *ctx = avctx->priv_data;
1412 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1413 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1416 NVENCSTATUS nv_status;
1418 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1419 int reg_idx = nvenc_register_frame(avctx, frame);
1421 av_log(avctx, AV_LOG_ERROR, "Could not register an input CUDA frame\n");
1425 res = av_frame_ref(nvenc_frame->in_ref, frame);
1429 nvenc_frame->in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1430 nvenc_frame->in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1431 nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &nvenc_frame->in_map);
1432 if (nv_status != NV_ENC_SUCCESS) {
1433 av_frame_unref(nvenc_frame->in_ref);
1434 return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
1437 ctx->registered_frames[reg_idx].mapped = 1;
1438 nvenc_frame->reg_idx = reg_idx;
1439 nvenc_frame->input_surface = nvenc_frame->in_map.mappedResource;
1442 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1444 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1445 lockBufferParams.inputBuffer = nvenc_frame->input_surface;
1447 nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
1448 if (nv_status != NV_ENC_SUCCESS) {
1449 return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
1452 res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
1454 nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
1455 if (nv_status != NV_ENC_SUCCESS) {
1456 return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
1463 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1464 NV_ENC_PIC_PARAMS *params)
1466 NvencContext *ctx = avctx->priv_data;
1468 switch (avctx->codec->id) {
1469 case AV_CODEC_ID_H264:
1470 params->codecPicParams.h264PicParams.sliceMode =
1471 ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1472 params->codecPicParams.h264PicParams.sliceModeData =
1473 ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1475 case AV_CODEC_ID_HEVC:
1476 params->codecPicParams.hevcPicParams.sliceMode =
1477 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1478 params->codecPicParams.hevcPicParams.sliceModeData =
1479 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1484 static inline void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
1486 av_fifo_generic_write(queue, ×tamp, sizeof(timestamp), NULL);
1489 static inline int64_t timestamp_queue_dequeue(AVFifoBuffer* queue)
1491 int64_t timestamp = AV_NOPTS_VALUE;
1492 if (av_fifo_size(queue) > 0)
1493 av_fifo_generic_read(queue, ×tamp, sizeof(timestamp), NULL);
1498 static int nvenc_set_timestamp(AVCodecContext *avctx,
1499 NV_ENC_LOCK_BITSTREAM *params,
1502 NvencContext *ctx = avctx->priv_data;
1504 pkt->pts = params->outputTimeStamp;
1506 /* generate the first dts by linearly extrapolating the
1507 * first two pts values to the past */
1508 if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
1509 ctx->initial_pts[1] != AV_NOPTS_VALUE) {
1510 int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
1513 if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
1514 (ts0 > 0 && ts1 < INT64_MIN + ts0))
1515 return AVERROR(ERANGE);
1518 if ((delta < 0 && ts0 > INT64_MAX + delta) ||
1519 (delta > 0 && ts0 < INT64_MIN + delta))
1520 return AVERROR(ERANGE);
1521 pkt->dts = ts0 - delta;
1523 ctx->first_packet_output = 1;
1527 pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
1532 static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
1534 NvencContext *ctx = avctx->priv_data;
1535 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1536 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1538 uint32_t slice_mode_data;
1539 uint32_t *slice_offsets;
1540 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1541 NVENCSTATUS nv_status;
1544 enum AVPictureType pict_type;
1546 switch (avctx->codec->id) {
1547 case AV_CODEC_ID_H264:
1548 slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1550 case AV_CODEC_ID_H265:
1551 slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1554 av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
1555 res = AVERROR(EINVAL);
1558 slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
1563 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1565 lock_params.doNotWait = 0;
1566 lock_params.outputBitstream = tmpoutsurf->output_surface;
1567 lock_params.sliceOffsets = slice_offsets;
1569 nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
1570 if (nv_status != NV_ENC_SUCCESS) {
1571 res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
1575 if (res = ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes,0)) {
1576 p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1580 memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1582 nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1583 if (nv_status != NV_ENC_SUCCESS)
1584 nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
1587 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1588 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, tmpoutsurf->in_map.mappedResource);
1589 av_frame_unref(tmpoutsurf->in_ref);
1590 ctx->registered_frames[tmpoutsurf->reg_idx].mapped = 0;
1592 tmpoutsurf->input_surface = NULL;
1595 switch (lock_params.pictureType) {
1596 case NV_ENC_PIC_TYPE_IDR:
1597 pkt->flags |= AV_PKT_FLAG_KEY;
1598 case NV_ENC_PIC_TYPE_I:
1599 pict_type = AV_PICTURE_TYPE_I;
1601 case NV_ENC_PIC_TYPE_P:
1602 pict_type = AV_PICTURE_TYPE_P;
1604 case NV_ENC_PIC_TYPE_B:
1605 pict_type = AV_PICTURE_TYPE_B;
1607 case NV_ENC_PIC_TYPE_BI:
1608 pict_type = AV_PICTURE_TYPE_BI;
1611 av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
1612 av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
1613 res = AVERROR_EXTERNAL;
1617 #if FF_API_CODED_FRAME
1618 FF_DISABLE_DEPRECATION_WARNINGS
1619 avctx->coded_frame->pict_type = pict_type;
1620 FF_ENABLE_DEPRECATION_WARNINGS
1623 ff_side_data_set_encoder_stats(pkt,
1624 (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
1626 res = nvenc_set_timestamp(avctx, &lock_params, pkt);
1630 av_free(slice_offsets);
1635 timestamp_queue_dequeue(ctx->timestamp_list);
1638 av_free(slice_offsets);
1643 static int output_ready(AVCodecContext *avctx, int flush)
1645 NvencContext *ctx = avctx->priv_data;
1646 int nb_ready, nb_pending;
1648 /* when B-frames are enabled, we wait for two initial timestamps to
1649 * calculate the first dts */
1650 if (!flush && avctx->max_b_frames > 0 &&
1651 (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
1654 nb_ready = av_fifo_size(ctx->output_surface_ready_queue) / sizeof(NvencSurface*);
1655 nb_pending = av_fifo_size(ctx->output_surface_queue) / sizeof(NvencSurface*);
1657 return nb_ready > 0;
1658 return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
1661 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1662 const AVFrame *frame, int *got_packet)
1664 NVENCSTATUS nv_status;
1665 NvencSurface *tmpoutsurf, *inSurf;
1668 NvencContext *ctx = avctx->priv_data;
1669 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1670 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1672 NV_ENC_PIC_PARAMS pic_params = { 0 };
1673 pic_params.version = NV_ENC_PIC_PARAMS_VER;
1676 inSurf = get_free_frame(ctx);
1678 av_log(avctx, AV_LOG_ERROR, "No free surfaces\n");
1682 res = nvenc_upload_frame(avctx, frame, inSurf);
1684 inSurf->lockCount = 0;
1688 pic_params.inputBuffer = inSurf->input_surface;
1689 pic_params.bufferFmt = inSurf->format;
1690 pic_params.inputWidth = avctx->width;
1691 pic_params.inputHeight = avctx->height;
1692 pic_params.outputBitstream = inSurf->output_surface;
1694 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1695 if (frame->top_field_first)
1696 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
1698 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
1700 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1703 pic_params.encodePicFlags = 0;
1704 pic_params.inputTimeStamp = frame->pts;
1706 nvenc_codec_specific_pic_params(avctx, &pic_params);
1708 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1711 nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
1712 if (nv_status != NV_ENC_SUCCESS &&
1713 nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
1714 return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
1717 av_fifo_generic_write(ctx->output_surface_queue, &inSurf, sizeof(inSurf), NULL);
1718 timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
1720 if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
1721 ctx->initial_pts[0] = frame->pts;
1722 else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
1723 ctx->initial_pts[1] = frame->pts;
1726 /* all the pending buffers are now ready for output */
1727 if (nv_status == NV_ENC_SUCCESS) {
1728 while (av_fifo_size(ctx->output_surface_queue) > 0) {
1729 av_fifo_generic_read(ctx->output_surface_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
1730 av_fifo_generic_write(ctx->output_surface_ready_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
1734 if (output_ready(avctx, !frame)) {
1735 av_fifo_generic_read(ctx->output_surface_ready_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
1737 res = process_output_surface(avctx, pkt, tmpoutsurf);
1742 av_assert0(tmpoutsurf->lockCount);
1743 tmpoutsurf->lockCount--;