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[] = {
92 #define IS_10BIT(pix_fmt) (pix_fmt == AV_PIX_FMT_P010 || \
93 pix_fmt == AV_PIX_FMT_YUV444P16)
95 #define IS_YUV444(pix_fmt) (pix_fmt == AV_PIX_FMT_YUV444P || \
96 pix_fmt == AV_PIX_FMT_YUV444P16)
103 { NV_ENC_SUCCESS, 0, "success" },
104 { NV_ENC_ERR_NO_ENCODE_DEVICE, AVERROR(ENOENT), "no encode device" },
105 { NV_ENC_ERR_UNSUPPORTED_DEVICE, AVERROR(ENOSYS), "unsupported device" },
106 { NV_ENC_ERR_INVALID_ENCODERDEVICE, AVERROR(EINVAL), "invalid encoder device" },
107 { NV_ENC_ERR_INVALID_DEVICE, AVERROR(EINVAL), "invalid device" },
108 { NV_ENC_ERR_DEVICE_NOT_EXIST, AVERROR(EIO), "device does not exist" },
109 { NV_ENC_ERR_INVALID_PTR, AVERROR(EFAULT), "invalid ptr" },
110 { NV_ENC_ERR_INVALID_EVENT, AVERROR(EINVAL), "invalid event" },
111 { NV_ENC_ERR_INVALID_PARAM, AVERROR(EINVAL), "invalid param" },
112 { NV_ENC_ERR_INVALID_CALL, AVERROR(EINVAL), "invalid call" },
113 { NV_ENC_ERR_OUT_OF_MEMORY, AVERROR(ENOMEM), "out of memory" },
114 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED, AVERROR(EINVAL), "encoder not initialized" },
115 { NV_ENC_ERR_UNSUPPORTED_PARAM, AVERROR(ENOSYS), "unsupported param" },
116 { NV_ENC_ERR_LOCK_BUSY, AVERROR(EAGAIN), "lock busy" },
117 { NV_ENC_ERR_NOT_ENOUGH_BUFFER, AVERROR_BUFFER_TOO_SMALL, "not enough buffer"},
118 { NV_ENC_ERR_INVALID_VERSION, AVERROR(EINVAL), "invalid version" },
119 { NV_ENC_ERR_MAP_FAILED, AVERROR(EIO), "map failed" },
120 { NV_ENC_ERR_NEED_MORE_INPUT, AVERROR(EAGAIN), "need more input" },
121 { NV_ENC_ERR_ENCODER_BUSY, AVERROR(EAGAIN), "encoder busy" },
122 { NV_ENC_ERR_EVENT_NOT_REGISTERD, AVERROR(EBADF), "event not registered" },
123 { NV_ENC_ERR_GENERIC, AVERROR_UNKNOWN, "generic error" },
124 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY, AVERROR(EINVAL), "incompatible client key" },
125 { NV_ENC_ERR_UNIMPLEMENTED, AVERROR(ENOSYS), "unimplemented" },
126 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO), "resource register failed" },
127 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED, AVERROR(EBADF), "resource not registered" },
128 { NV_ENC_ERR_RESOURCE_NOT_MAPPED, AVERROR(EBADF), "resource not mapped" },
131 static int nvenc_map_error(NVENCSTATUS err, const char **desc)
134 for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
135 if (nvenc_errors[i].nverr == err) {
137 *desc = nvenc_errors[i].desc;
138 return nvenc_errors[i].averr;
142 *desc = "unknown error";
143 return AVERROR_UNKNOWN;
146 static int nvenc_print_error(void *log_ctx, NVENCSTATUS err,
147 const char *error_string)
151 ret = nvenc_map_error(err, &desc);
152 av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
156 static av_cold int nvenc_load_libraries(AVCodecContext *avctx)
158 NvencContext *ctx = avctx->priv_data;
159 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
160 PNVENCODEAPIGETMAXSUPPORTEDVERSION nvenc_get_max_ver;
161 PNVENCODEAPICREATEINSTANCE nvenc_create_instance;
163 uint32_t nvenc_max_ver;
166 dl_fn->cu_init = cuInit;
167 dl_fn->cu_device_get_count = cuDeviceGetCount;
168 dl_fn->cu_device_get = cuDeviceGet;
169 dl_fn->cu_device_get_name = cuDeviceGetName;
170 dl_fn->cu_device_compute_capability = cuDeviceComputeCapability;
171 dl_fn->cu_ctx_create = cuCtxCreate_v2;
172 dl_fn->cu_ctx_pop_current = cuCtxPopCurrent_v2;
173 dl_fn->cu_ctx_destroy = cuCtxDestroy_v2;
175 LOAD_LIBRARY(dl_fn->cuda, CUDA_LIBNAME);
177 LOAD_SYMBOL(dl_fn->cu_init, dl_fn->cuda, "cuInit");
178 LOAD_SYMBOL(dl_fn->cu_device_get_count, dl_fn->cuda, "cuDeviceGetCount");
179 LOAD_SYMBOL(dl_fn->cu_device_get, dl_fn->cuda, "cuDeviceGet");
180 LOAD_SYMBOL(dl_fn->cu_device_get_name, dl_fn->cuda, "cuDeviceGetName");
181 LOAD_SYMBOL(dl_fn->cu_device_compute_capability, dl_fn->cuda,
182 "cuDeviceComputeCapability");
183 LOAD_SYMBOL(dl_fn->cu_ctx_create, dl_fn->cuda, "cuCtxCreate_v2");
184 LOAD_SYMBOL(dl_fn->cu_ctx_pop_current, dl_fn->cuda, "cuCtxPopCurrent_v2");
185 LOAD_SYMBOL(dl_fn->cu_ctx_destroy, dl_fn->cuda, "cuCtxDestroy_v2");
188 LOAD_LIBRARY(dl_fn->nvenc, NVENC_LIBNAME);
190 LOAD_SYMBOL(nvenc_get_max_ver, dl_fn->nvenc,
191 "NvEncodeAPIGetMaxSupportedVersion");
192 LOAD_SYMBOL(nvenc_create_instance, dl_fn->nvenc,
193 "NvEncodeAPICreateInstance");
195 err = nvenc_get_max_ver(&nvenc_max_ver);
196 if (err != NV_ENC_SUCCESS)
197 return nvenc_print_error(avctx, err, "Failed to query nvenc max version");
199 av_log(avctx, AV_LOG_VERBOSE, "Loaded Nvenc version %d.%d\n", nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
201 if ((NVENCAPI_MAJOR_VERSION << 4 | NVENCAPI_MINOR_VERSION) > nvenc_max_ver) {
202 av_log(avctx, AV_LOG_ERROR, "Driver does not support the required nvenc API version. "
203 "Required: %d.%d Found: %d.%d\n",
204 NVENCAPI_MAJOR_VERSION, NVENCAPI_MINOR_VERSION,
205 nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
206 return AVERROR(ENOSYS);
209 dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
211 err = nvenc_create_instance(&dl_fn->nvenc_funcs);
212 if (err != NV_ENC_SUCCESS)
213 return nvenc_print_error(avctx, err, "Failed to create nvenc instance");
215 av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
220 static av_cold int nvenc_open_session(AVCodecContext *avctx)
222 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
223 NvencContext *ctx = avctx->priv_data;
224 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
227 params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
228 params.apiVersion = NVENCAPI_VERSION;
229 params.device = ctx->cu_context;
230 params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
232 ret = p_nvenc->nvEncOpenEncodeSessionEx(¶ms, &ctx->nvencoder);
233 if (ret != NV_ENC_SUCCESS) {
234 ctx->nvencoder = NULL;
235 return nvenc_print_error(avctx, ret, "OpenEncodeSessionEx failed");
241 static int nvenc_check_codec_support(AVCodecContext *avctx)
243 NvencContext *ctx = avctx->priv_data;
244 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
245 int i, ret, count = 0;
248 ret = p_nvenc->nvEncGetEncodeGUIDCount(ctx->nvencoder, &count);
250 if (ret != NV_ENC_SUCCESS || !count)
251 return AVERROR(ENOSYS);
253 guids = av_malloc(count * sizeof(GUID));
255 return AVERROR(ENOMEM);
257 ret = p_nvenc->nvEncGetEncodeGUIDs(ctx->nvencoder, guids, count, &count);
258 if (ret != NV_ENC_SUCCESS) {
259 ret = AVERROR(ENOSYS);
263 ret = AVERROR(ENOSYS);
264 for (i = 0; i < count; i++) {
265 if (!memcmp(&guids[i], &ctx->init_encode_params.encodeGUID, sizeof(*guids))) {
277 static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
279 NvencContext *ctx = avctx->priv_data;
280 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
281 NV_ENC_CAPS_PARAM params = { 0 };
284 params.version = NV_ENC_CAPS_PARAM_VER;
285 params.capsToQuery = cap;
287 ret = p_nvenc->nvEncGetEncodeCaps(ctx->nvencoder, ctx->init_encode_params.encodeGUID, ¶ms, &val);
289 if (ret == NV_ENC_SUCCESS)
294 static int nvenc_check_capabilities(AVCodecContext *avctx)
296 NvencContext *ctx = avctx->priv_data;
299 ret = nvenc_check_codec_support(avctx);
301 av_log(avctx, AV_LOG_VERBOSE, "Codec not supported\n");
305 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
306 if (IS_YUV444(ctx->data_pix_fmt) && ret <= 0) {
307 av_log(avctx, AV_LOG_VERBOSE, "YUV444P not supported\n");
308 return AVERROR(ENOSYS);
311 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOSSLESS_ENCODE);
312 if (ctx->preset >= PRESET_LOSSLESS_DEFAULT && ret <= 0) {
313 av_log(avctx, AV_LOG_VERBOSE, "Lossless encoding not supported\n");
314 return AVERROR(ENOSYS);
317 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
318 if (ret < avctx->width) {
319 av_log(avctx, AV_LOG_VERBOSE, "Width %d exceeds %d\n",
321 return AVERROR(ENOSYS);
324 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
325 if (ret < avctx->height) {
326 av_log(avctx, AV_LOG_VERBOSE, "Height %d exceeds %d\n",
328 return AVERROR(ENOSYS);
331 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
332 if (ret < avctx->max_b_frames) {
333 av_log(avctx, AV_LOG_VERBOSE, "Max B-frames %d exceed %d\n",
334 avctx->max_b_frames, ret);
336 return AVERROR(ENOSYS);
339 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_FIELD_ENCODING);
340 if (ret < 1 && avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
341 av_log(avctx, AV_LOG_VERBOSE,
342 "Interlaced encoding is not supported. Supported level: %d\n",
344 return AVERROR(ENOSYS);
347 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_10BIT_ENCODE);
348 if (IS_10BIT(ctx->data_pix_fmt) && ret <= 0) {
349 av_log(avctx, AV_LOG_VERBOSE, "10 bit encode not supported\n");
350 return AVERROR(ENOSYS);
353 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOOKAHEAD);
354 if (ctx->rc_lookahead > 0 && ret <= 0) {
355 av_log(avctx, AV_LOG_VERBOSE, "RC lookahead not supported\n");
356 return AVERROR(ENOSYS);
362 static av_cold int nvenc_check_device(AVCodecContext *avctx, int idx)
364 NvencContext *ctx = avctx->priv_data;
365 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
366 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
367 char name[128] = { 0};
368 int major, minor, ret;
372 int loglevel = AV_LOG_VERBOSE;
374 if (ctx->device == LIST_DEVICES)
375 loglevel = AV_LOG_INFO;
377 cu_res = dl_fn->cu_device_get(&cu_device, idx);
378 if (cu_res != CUDA_SUCCESS) {
379 av_log(avctx, AV_LOG_ERROR,
380 "Cannot access the CUDA device %d\n",
385 cu_res = dl_fn->cu_device_get_name(name, sizeof(name), cu_device);
386 if (cu_res != CUDA_SUCCESS)
389 cu_res = dl_fn->cu_device_compute_capability(&major, &minor, cu_device);
390 if (cu_res != CUDA_SUCCESS)
393 av_log(avctx, loglevel, "[ GPU #%d - < %s > has Compute SM %d.%d ]\n", idx, name, major, minor);
394 if (((major << 4) | minor) < NVENC_CAP) {
395 av_log(avctx, loglevel, "does not support NVENC\n");
399 cu_res = dl_fn->cu_ctx_create(&ctx->cu_context_internal, 0, cu_device);
400 if (cu_res != CUDA_SUCCESS) {
401 av_log(avctx, AV_LOG_FATAL, "Failed creating CUDA context for NVENC: 0x%x\n", (int)cu_res);
405 ctx->cu_context = ctx->cu_context_internal;
407 cu_res = dl_fn->cu_ctx_pop_current(&dummy);
408 if (cu_res != CUDA_SUCCESS) {
409 av_log(avctx, AV_LOG_FATAL, "Failed popping CUDA context: 0x%x\n", (int)cu_res);
413 if ((ret = nvenc_open_session(avctx)) < 0)
416 if ((ret = nvenc_check_capabilities(avctx)) < 0)
419 av_log(avctx, loglevel, "supports NVENC\n");
421 dl_fn->nvenc_device_count++;
423 if (ctx->device == dl_fn->nvenc_device_count - 1 || ctx->device == ANY_DEVICE)
427 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
428 ctx->nvencoder = NULL;
431 dl_fn->cu_ctx_destroy(ctx->cu_context_internal);
432 ctx->cu_context_internal = NULL;
435 return AVERROR(ENOSYS);
438 static av_cold int nvenc_setup_device(AVCodecContext *avctx)
440 NvencContext *ctx = avctx->priv_data;
441 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
443 switch (avctx->codec->id) {
444 case AV_CODEC_ID_H264:
445 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
447 case AV_CODEC_ID_HEVC:
448 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
454 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
456 AVHWFramesContext *frames_ctx;
457 AVCUDADeviceContext *device_hwctx;
460 if (!avctx->hw_frames_ctx)
461 return AVERROR(EINVAL);
463 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
464 device_hwctx = frames_ctx->device_ctx->hwctx;
466 ctx->cu_context = device_hwctx->cuda_ctx;
468 ret = nvenc_open_session(avctx);
472 ret = nvenc_check_capabilities(avctx);
474 av_log(avctx, AV_LOG_FATAL, "Provided device doesn't support required NVENC features\n");
481 int i, nb_devices = 0;
483 if ((dl_fn->cu_init(0)) != CUDA_SUCCESS) {
484 av_log(avctx, AV_LOG_ERROR,
485 "Cannot init CUDA\n");
486 return AVERROR_UNKNOWN;
489 if ((dl_fn->cu_device_get_count(&nb_devices)) != CUDA_SUCCESS) {
490 av_log(avctx, AV_LOG_ERROR,
491 "Cannot enumerate the CUDA devices\n");
492 return AVERROR_UNKNOWN;
496 av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
497 return AVERROR_EXTERNAL;
500 av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", nb_devices);
502 dl_fn->nvenc_device_count = 0;
503 for (i = 0; i < nb_devices; ++i) {
504 if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
508 if (ctx->device == LIST_DEVICES)
511 if (!dl_fn->nvenc_device_count) {
512 av_log(avctx, AV_LOG_FATAL, "No NVENC capable devices found\n");
513 return AVERROR_EXTERNAL;
516 av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->device, dl_fn->nvenc_device_count);
517 return AVERROR(EINVAL);
523 typedef struct GUIDTuple {
528 #define PRESET_ALIAS(alias, name, ...) \
529 [PRESET_ ## alias] = { NV_ENC_PRESET_ ## name ## _GUID, __VA_ARGS__ }
531 #define PRESET(name, ...) PRESET_ALIAS(name, name, __VA_ARGS__)
533 static void nvenc_map_preset(NvencContext *ctx)
535 GUIDTuple presets[] = {
540 PRESET_ALIAS(SLOW, HQ, NVENC_TWO_PASSES),
541 PRESET_ALIAS(MEDIUM, HQ, NVENC_ONE_PASS),
542 PRESET_ALIAS(FAST, HP, NVENC_ONE_PASS),
543 PRESET(LOW_LATENCY_DEFAULT, NVENC_LOWLATENCY),
544 PRESET(LOW_LATENCY_HP, NVENC_LOWLATENCY),
545 PRESET(LOW_LATENCY_HQ, NVENC_LOWLATENCY),
546 PRESET(LOSSLESS_DEFAULT, NVENC_LOSSLESS),
547 PRESET(LOSSLESS_HP, NVENC_LOSSLESS),
550 GUIDTuple *t = &presets[ctx->preset];
552 ctx->init_encode_params.presetGUID = t->guid;
553 ctx->flags = t->flags;
559 static av_cold void set_constqp(AVCodecContext *avctx)
561 NvencContext *ctx = avctx->priv_data;
562 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
564 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
565 rc->constQP.qpInterB = avctx->global_quality;
566 rc->constQP.qpInterP = avctx->global_quality;
567 rc->constQP.qpIntra = avctx->global_quality;
573 static av_cold void set_vbr(AVCodecContext *avctx)
575 NvencContext *ctx = avctx->priv_data;
576 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
579 if (avctx->qmin >= 0 && avctx->qmax >= 0) {
583 rc->minQP.qpInterB = avctx->qmin;
584 rc->minQP.qpInterP = avctx->qmin;
585 rc->minQP.qpIntra = avctx->qmin;
587 rc->maxQP.qpInterB = avctx->qmax;
588 rc->maxQP.qpInterP = avctx->qmax;
589 rc->maxQP.qpIntra = avctx->qmax;
591 qp_inter_p = (avctx->qmax + 3 * avctx->qmin) / 4; // biased towards Qmin
592 } else if (avctx->qmin >= 0) {
595 rc->minQP.qpInterB = avctx->qmin;
596 rc->minQP.qpInterP = avctx->qmin;
597 rc->minQP.qpIntra = avctx->qmin;
599 qp_inter_p = avctx->qmin;
601 qp_inter_p = 26; // default to 26
604 rc->enableInitialRCQP = 1;
605 rc->initialRCQP.qpInterP = qp_inter_p;
607 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
608 rc->initialRCQP.qpIntra = av_clip(
609 qp_inter_p * fabs(avctx->i_quant_factor) + avctx->i_quant_offset, 0, 51);
610 rc->initialRCQP.qpInterB = av_clip(
611 qp_inter_p * fabs(avctx->b_quant_factor) + avctx->b_quant_offset, 0, 51);
613 rc->initialRCQP.qpIntra = qp_inter_p;
614 rc->initialRCQP.qpInterB = qp_inter_p;
618 static av_cold void set_lossless(AVCodecContext *avctx)
620 NvencContext *ctx = avctx->priv_data;
621 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
623 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
624 rc->constQP.qpInterB = 0;
625 rc->constQP.qpInterP = 0;
626 rc->constQP.qpIntra = 0;
632 static void nvenc_override_rate_control(AVCodecContext *avctx)
634 NvencContext *ctx = avctx->priv_data;
635 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
638 case NV_ENC_PARAMS_RC_CONSTQP:
639 if (avctx->global_quality <= 0) {
640 av_log(avctx, AV_LOG_WARNING,
641 "The constant quality rate-control requires "
642 "the 'global_quality' option set.\n");
647 case NV_ENC_PARAMS_RC_2_PASS_VBR:
648 case NV_ENC_PARAMS_RC_VBR:
649 if (avctx->qmin < 0 && avctx->qmax < 0) {
650 av_log(avctx, AV_LOG_WARNING,
651 "The variable bitrate rate-control requires "
652 "the 'qmin' and/or 'qmax' option set.\n");
656 case NV_ENC_PARAMS_RC_VBR_MINQP:
657 if (avctx->qmin < 0) {
658 av_log(avctx, AV_LOG_WARNING,
659 "The variable bitrate rate-control requires "
660 "the 'qmin' option set.\n");
666 case NV_ENC_PARAMS_RC_CBR:
667 case NV_ENC_PARAMS_RC_2_PASS_QUALITY:
668 case NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP:
672 rc->rateControlMode = ctx->rc;
675 static av_cold void nvenc_setup_rate_control(AVCodecContext *avctx)
677 NvencContext *ctx = avctx->priv_data;
679 if (avctx->bit_rate > 0) {
680 ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
681 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
682 ctx->encode_config.rcParams.maxBitRate = ctx->encode_config.rcParams.averageBitRate;
685 if (avctx->rc_max_rate > 0)
686 ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
689 if (ctx->flags & NVENC_ONE_PASS)
691 if (ctx->flags & NVENC_TWO_PASSES)
694 if (ctx->twopass < 0)
695 ctx->twopass = (ctx->flags & NVENC_LOWLATENCY) != 0;
699 ctx->rc = NV_ENC_PARAMS_RC_2_PASS_QUALITY;
701 ctx->rc = NV_ENC_PARAMS_RC_CBR;
703 } else if (avctx->global_quality > 0) {
704 ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
705 } else if (ctx->twopass) {
706 ctx->rc = NV_ENC_PARAMS_RC_2_PASS_VBR;
707 } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
708 ctx->rc = NV_ENC_PARAMS_RC_VBR_MINQP;
712 if (ctx->flags & NVENC_LOSSLESS) {
714 } else if (ctx->rc >= 0) {
715 nvenc_override_rate_control(avctx);
717 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
721 if (avctx->rc_buffer_size > 0) {
722 ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
723 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
724 ctx->encode_config.rcParams.vbvBufferSize = 2 * ctx->encode_config.rcParams.averageBitRate;
728 ctx->encode_config.rcParams.enableAQ = 1;
729 ctx->encode_config.rcParams.aqStrength = ctx->aq_strength;
730 av_log(avctx, AV_LOG_VERBOSE, "AQ enabled.\n");
733 if (ctx->temporal_aq) {
734 ctx->encode_config.rcParams.enableTemporalAQ = 1;
735 av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ enabled.\n");
738 if (ctx->rc_lookahead) {
739 int lkd_bound = FFMIN(ctx->nb_surfaces, ctx->async_depth) -
740 ctx->encode_config.frameIntervalP - 4;
743 av_log(avctx, AV_LOG_WARNING,
744 "Lookahead not enabled. Increase buffer delay (-delay).\n");
746 ctx->encode_config.rcParams.enableLookahead = 1;
747 ctx->encode_config.rcParams.lookaheadDepth = av_clip(ctx->rc_lookahead, 0, lkd_bound);
748 ctx->encode_config.rcParams.disableIadapt = ctx->no_scenecut;
749 ctx->encode_config.rcParams.disableBadapt = !ctx->b_adapt;
750 av_log(avctx, AV_LOG_VERBOSE,
751 "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",
752 ctx->encode_config.rcParams.lookaheadDepth,
753 ctx->encode_config.rcParams.disableIadapt ? "disabled" : "enabled",
754 ctx->encode_config.rcParams.disableBadapt ? "disabled" : "enabled");
758 if (ctx->strict_gop) {
759 ctx->encode_config.rcParams.strictGOPTarget = 1;
760 av_log(avctx, AV_LOG_VERBOSE, "Strict GOP target enabled.\n");
764 ctx->encode_config.rcParams.enableNonRefP = 1;
766 if (ctx->zerolatency)
767 ctx->encode_config.rcParams.zeroReorderDelay = 1;
770 ctx->encode_config.rcParams.targetQuality = ctx->quality;
773 static av_cold int nvenc_setup_h264_config(AVCodecContext *avctx)
775 NvencContext *ctx = avctx->priv_data;
776 NV_ENC_CONFIG *cc = &ctx->encode_config;
777 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
778 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
780 vui->colourMatrix = avctx->colorspace;
781 vui->colourPrimaries = avctx->color_primaries;
782 vui->transferCharacteristics = avctx->color_trc;
783 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
784 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
786 vui->colourDescriptionPresentFlag =
787 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
789 vui->videoSignalTypePresentFlag =
790 (vui->colourDescriptionPresentFlag
791 || vui->videoFormat != 5
792 || vui->videoFullRangeFlag != 0);
795 h264->sliceModeData = 1;
797 h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
798 h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
801 if (avctx->refs >= 0) {
802 /* 0 means "let the hardware decide" */
803 h264->maxNumRefFrames = avctx->refs;
805 if (avctx->gop_size >= 0) {
806 h264->idrPeriod = cc->gopLength;
809 if (IS_CBR(cc->rcParams.rateControlMode)) {
810 h264->outputBufferingPeriodSEI = 1;
811 h264->outputPictureTimingSEI = 1;
814 if (cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_2_PASS_QUALITY ||
815 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP ||
816 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_2_PASS_VBR) {
817 h264->adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
818 h264->fmoMode = NV_ENC_H264_FMO_DISABLE;
821 if (ctx->flags & NVENC_LOSSLESS) {
822 h264->qpPrimeYZeroTransformBypassFlag = 1;
824 switch(ctx->profile) {
825 case NV_ENC_H264_PROFILE_BASELINE:
826 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
827 avctx->profile = FF_PROFILE_H264_BASELINE;
829 case NV_ENC_H264_PROFILE_MAIN:
830 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
831 avctx->profile = FF_PROFILE_H264_MAIN;
833 case NV_ENC_H264_PROFILE_HIGH:
834 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
835 avctx->profile = FF_PROFILE_H264_HIGH;
837 case NV_ENC_H264_PROFILE_HIGH_444P:
838 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
839 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
844 // force setting profile as high444p if input is AV_PIX_FMT_YUV444P
845 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P) {
846 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
847 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
850 h264->chromaFormatIDC = avctx->profile == FF_PROFILE_H264_HIGH_444_PREDICTIVE ? 3 : 1;
852 h264->level = ctx->level;
857 static av_cold int nvenc_setup_hevc_config(AVCodecContext *avctx)
859 NvencContext *ctx = avctx->priv_data;
860 NV_ENC_CONFIG *cc = &ctx->encode_config;
861 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
862 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
864 vui->colourMatrix = avctx->colorspace;
865 vui->colourPrimaries = avctx->color_primaries;
866 vui->transferCharacteristics = avctx->color_trc;
867 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
868 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
870 vui->colourDescriptionPresentFlag =
871 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
873 vui->videoSignalTypePresentFlag =
874 (vui->colourDescriptionPresentFlag
875 || vui->videoFormat != 5
876 || vui->videoFullRangeFlag != 0);
879 hevc->sliceModeData = 1;
881 hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
882 hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
885 if (avctx->refs >= 0) {
886 /* 0 means "let the hardware decide" */
887 hevc->maxNumRefFramesInDPB = avctx->refs;
889 if (avctx->gop_size >= 0) {
890 hevc->idrPeriod = cc->gopLength;
893 if (IS_CBR(cc->rcParams.rateControlMode)) {
894 hevc->outputBufferingPeriodSEI = 1;
895 hevc->outputPictureTimingSEI = 1;
898 switch(ctx->profile) {
899 case NV_ENC_HEVC_PROFILE_MAIN:
900 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
901 avctx->profile = FF_PROFILE_HEVC_MAIN;
903 case NV_ENC_HEVC_PROFILE_MAIN_10:
904 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
905 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
907 case NV_ENC_HEVC_PROFILE_REXT:
908 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
909 avctx->profile = FF_PROFILE_HEVC_REXT;
913 // force setting profile as main10 if input is 10 bit
914 if (IS_10BIT(ctx->data_pix_fmt)) {
915 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
916 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
919 // force setting profile as rext if input is yuv444
920 if (IS_YUV444(ctx->data_pix_fmt)) {
921 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
922 avctx->profile = FF_PROFILE_HEVC_REXT;
925 hevc->chromaFormatIDC = IS_YUV444(ctx->data_pix_fmt) ? 3 : 1;
927 hevc->pixelBitDepthMinus8 = IS_10BIT(ctx->data_pix_fmt) ? 2 : 0;
929 hevc->level = ctx->level;
931 hevc->tier = ctx->tier;
936 static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx)
938 switch (avctx->codec->id) {
939 case AV_CODEC_ID_H264:
940 return nvenc_setup_h264_config(avctx);
941 case AV_CODEC_ID_HEVC:
942 return nvenc_setup_hevc_config(avctx);
943 /* Earlier switch/case will return if unknown codec is passed. */
949 static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
951 NvencContext *ctx = avctx->priv_data;
952 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
953 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
955 NV_ENC_PRESET_CONFIG preset_config = { 0 };
956 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
957 AVCPBProperties *cpb_props;
961 ctx->encode_config.version = NV_ENC_CONFIG_VER;
962 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
964 ctx->init_encode_params.encodeHeight = avctx->height;
965 ctx->init_encode_params.encodeWidth = avctx->width;
967 ctx->init_encode_params.encodeConfig = &ctx->encode_config;
969 nvenc_map_preset(ctx);
971 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
972 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
974 nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder,
975 ctx->init_encode_params.encodeGUID,
976 ctx->init_encode_params.presetGUID,
978 if (nv_status != NV_ENC_SUCCESS)
979 return nvenc_print_error(avctx, nv_status, "Cannot get the preset configuration");
981 memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
983 ctx->encode_config.version = NV_ENC_CONFIG_VER;
985 if (avctx->sample_aspect_ratio.num && avctx->sample_aspect_ratio.den &&
986 (avctx->sample_aspect_ratio.num != 1 || avctx->sample_aspect_ratio.num != 1)) {
988 avctx->width * avctx->sample_aspect_ratio.num,
989 avctx->height * avctx->sample_aspect_ratio.den,
991 ctx->init_encode_params.darHeight = dh;
992 ctx->init_encode_params.darWidth = dw;
994 ctx->init_encode_params.darHeight = avctx->height;
995 ctx->init_encode_params.darWidth = avctx->width;
998 // De-compensate for hardware, dubiously, trying to compensate for
999 // playback at 704 pixel width.
1000 if (avctx->width == 720 &&
1001 (avctx->height == 480 || avctx->height == 576)) {
1003 ctx->init_encode_params.darWidth * 44,
1004 ctx->init_encode_params.darHeight * 45,
1006 ctx->init_encode_params.darHeight = dh;
1007 ctx->init_encode_params.darWidth = dw;
1010 ctx->init_encode_params.frameRateNum = avctx->time_base.den;
1011 ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
1013 ctx->init_encode_params.enableEncodeAsync = 0;
1014 ctx->init_encode_params.enablePTD = 1;
1016 if (avctx->gop_size > 0) {
1017 if (avctx->max_b_frames >= 0) {
1018 /* 0 is intra-only, 1 is I/P only, 2 is one B-Frame, 3 two B-frames, and so on. */
1019 ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
1022 ctx->encode_config.gopLength = avctx->gop_size;
1023 } else if (avctx->gop_size == 0) {
1024 ctx->encode_config.frameIntervalP = 0;
1025 ctx->encode_config.gopLength = 1;
1028 ctx->initial_pts[0] = AV_NOPTS_VALUE;
1029 ctx->initial_pts[1] = AV_NOPTS_VALUE;
1031 nvenc_setup_rate_control(avctx);
1033 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1034 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
1036 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
1039 res = nvenc_setup_codec_config(avctx);
1043 nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
1044 if (nv_status != NV_ENC_SUCCESS) {
1045 return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
1048 if (ctx->encode_config.frameIntervalP > 1)
1049 avctx->has_b_frames = 2;
1051 if (ctx->encode_config.rcParams.averageBitRate > 0)
1052 avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
1054 cpb_props = ff_add_cpb_side_data(avctx);
1056 return AVERROR(ENOMEM);
1057 cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
1058 cpb_props->avg_bitrate = avctx->bit_rate;
1059 cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
1064 static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
1066 NvencContext *ctx = avctx->priv_data;
1067 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1068 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1070 NVENCSTATUS nv_status;
1071 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
1072 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1074 switch (ctx->data_pix_fmt) {
1075 case AV_PIX_FMT_YUV420P:
1076 ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_YV12_PL;
1079 case AV_PIX_FMT_NV12:
1080 ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_NV12_PL;
1083 case AV_PIX_FMT_P010:
1084 ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1087 case AV_PIX_FMT_YUV444P:
1088 ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_YUV444_PL;
1091 case AV_PIX_FMT_YUV444P16:
1092 ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1095 case AV_PIX_FMT_0RGB32:
1096 ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_ARGB;
1099 case AV_PIX_FMT_0BGR32:
1100 ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_ABGR;
1104 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format\n");
1105 return AVERROR(EINVAL);
1108 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1109 ctx->surfaces[idx].in_ref = av_frame_alloc();
1110 if (!ctx->surfaces[idx].in_ref)
1111 return AVERROR(ENOMEM);
1113 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1114 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1115 allocSurf.width = (avctx->width + 31) & ~31;
1116 allocSurf.height = (avctx->height + 31) & ~31;
1117 allocSurf.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
1118 allocSurf.bufferFmt = ctx->surfaces[idx].format;
1120 nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
1121 if (nv_status != NV_ENC_SUCCESS) {
1122 return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
1125 ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
1126 ctx->surfaces[idx].width = allocSurf.width;
1127 ctx->surfaces[idx].height = allocSurf.height;
1130 ctx->surfaces[idx].lockCount = 0;
1132 /* 1MB is large enough to hold most output frames.
1133 * NVENC increases this automaticaly if it is not enough. */
1134 allocOut.size = 1024 * 1024;
1136 allocOut.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
1138 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
1139 if (nv_status != NV_ENC_SUCCESS) {
1140 int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
1141 if (avctx->pix_fmt != AV_PIX_FMT_CUDA)
1142 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
1143 av_frame_free(&ctx->surfaces[idx].in_ref);
1147 ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1148 ctx->surfaces[idx].size = allocOut.size;
1153 static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx)
1155 NvencContext *ctx = avctx->priv_data;
1157 int num_mbs = ((avctx->width + 15) >> 4) * ((avctx->height + 15) >> 4);
1158 ctx->nb_surfaces = FFMAX((num_mbs >= 8160) ? 32 : 48,
1160 ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
1163 ctx->surfaces = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->surfaces));
1165 return AVERROR(ENOMEM);
1167 ctx->timestamp_list = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
1168 if (!ctx->timestamp_list)
1169 return AVERROR(ENOMEM);
1170 ctx->output_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1171 if (!ctx->output_surface_queue)
1172 return AVERROR(ENOMEM);
1173 ctx->output_surface_ready_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1174 if (!ctx->output_surface_ready_queue)
1175 return AVERROR(ENOMEM);
1177 for (i = 0; i < ctx->nb_surfaces; i++) {
1178 if ((res = nvenc_alloc_surface(avctx, i)) < 0)
1185 static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
1187 NvencContext *ctx = avctx->priv_data;
1188 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1189 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1191 NVENCSTATUS nv_status;
1192 uint32_t outSize = 0;
1193 char tmpHeader[256];
1194 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1195 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1197 payload.spsppsBuffer = tmpHeader;
1198 payload.inBufferSize = sizeof(tmpHeader);
1199 payload.outSPSPPSPayloadSize = &outSize;
1201 nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
1202 if (nv_status != NV_ENC_SUCCESS) {
1203 return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
1206 avctx->extradata_size = outSize;
1207 avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
1209 if (!avctx->extradata) {
1210 return AVERROR(ENOMEM);
1213 memcpy(avctx->extradata, tmpHeader, outSize);
1218 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
1220 NvencContext *ctx = avctx->priv_data;
1221 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1222 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1225 /* the encoder has to be flushed before it can be closed */
1226 if (ctx->nvencoder) {
1227 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
1228 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
1230 p_nvenc->nvEncEncodePicture(ctx->nvencoder, ¶ms);
1233 av_fifo_freep(&ctx->timestamp_list);
1234 av_fifo_freep(&ctx->output_surface_ready_queue);
1235 av_fifo_freep(&ctx->output_surface_queue);
1237 if (ctx->surfaces && avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1238 for (i = 0; i < ctx->nb_surfaces; ++i) {
1239 if (ctx->surfaces[i].input_surface) {
1240 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->surfaces[i].in_map.mappedResource);
1243 for (i = 0; i < ctx->nb_registered_frames; i++) {
1244 if (ctx->registered_frames[i].regptr)
1245 p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1247 ctx->nb_registered_frames = 0;
1250 if (ctx->surfaces) {
1251 for (i = 0; i < ctx->nb_surfaces; ++i) {
1252 if (avctx->pix_fmt != AV_PIX_FMT_CUDA)
1253 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
1254 av_frame_free(&ctx->surfaces[i].in_ref);
1255 p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
1258 av_freep(&ctx->surfaces);
1259 ctx->nb_surfaces = 0;
1262 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1263 ctx->nvencoder = NULL;
1265 if (ctx->cu_context_internal)
1266 dl_fn->cu_ctx_destroy(ctx->cu_context_internal);
1267 ctx->cu_context = ctx->cu_context_internal = NULL;
1270 dlclose(dl_fn->nvenc);
1271 dl_fn->nvenc = NULL;
1273 dl_fn->nvenc_device_count = 0;
1277 dlclose(dl_fn->cuda);
1281 dl_fn->cu_init = NULL;
1282 dl_fn->cu_device_get_count = NULL;
1283 dl_fn->cu_device_get = NULL;
1284 dl_fn->cu_device_get_name = NULL;
1285 dl_fn->cu_device_compute_capability = NULL;
1286 dl_fn->cu_ctx_create = NULL;
1287 dl_fn->cu_ctx_pop_current = NULL;
1288 dl_fn->cu_ctx_destroy = NULL;
1290 av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
1295 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
1297 NvencContext *ctx = avctx->priv_data;
1300 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1301 AVHWFramesContext *frames_ctx;
1302 if (!avctx->hw_frames_ctx) {
1303 av_log(avctx, AV_LOG_ERROR,
1304 "hw_frames_ctx must be set when using GPU frames as input\n");
1305 return AVERROR(EINVAL);
1307 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1308 ctx->data_pix_fmt = frames_ctx->sw_format;
1310 ctx->data_pix_fmt = avctx->pix_fmt;
1313 if ((ret = nvenc_load_libraries(avctx)) < 0)
1316 if ((ret = nvenc_setup_device(avctx)) < 0)
1319 if ((ret = nvenc_setup_encoder(avctx)) < 0)
1322 if ((ret = nvenc_setup_surfaces(avctx)) < 0)
1325 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1326 if ((ret = nvenc_setup_extradata(avctx)) < 0)
1333 static NvencSurface *get_free_frame(NvencContext *ctx)
1337 for (i = 0; i < ctx->nb_surfaces; ++i) {
1338 if (!ctx->surfaces[i].lockCount) {
1339 ctx->surfaces[i].lockCount = 1;
1340 return &ctx->surfaces[i];
1347 static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *nv_surface,
1348 NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params, const AVFrame *frame)
1350 int dst_linesize[4] = {
1351 lock_buffer_params->pitch,
1352 lock_buffer_params->pitch,
1353 lock_buffer_params->pitch,
1354 lock_buffer_params->pitch
1356 uint8_t *dst_data[4];
1359 if (frame->format == AV_PIX_FMT_YUV420P)
1360 dst_linesize[1] = dst_linesize[2] >>= 1;
1362 ret = av_image_fill_pointers(dst_data, frame->format, nv_surface->height,
1363 lock_buffer_params->bufferDataPtr, dst_linesize);
1367 if (frame->format == AV_PIX_FMT_YUV420P)
1368 FFSWAP(uint8_t*, dst_data[1], dst_data[2]);
1370 av_image_copy(dst_data, dst_linesize,
1371 (const uint8_t**)frame->data, frame->linesize, frame->format,
1372 avctx->width, avctx->height);
1377 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1379 NvencContext *ctx = avctx->priv_data;
1380 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1381 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1385 if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1386 for (i = 0; i < ctx->nb_registered_frames; i++) {
1387 if (!ctx->registered_frames[i].mapped) {
1388 if (ctx->registered_frames[i].regptr) {
1389 p_nvenc->nvEncUnregisterResource(ctx->nvencoder,
1390 ctx->registered_frames[i].regptr);
1391 ctx->registered_frames[i].regptr = NULL;
1397 return ctx->nb_registered_frames++;
1400 av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1401 return AVERROR(ENOMEM);
1404 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1406 NvencContext *ctx = avctx->priv_data;
1407 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1408 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1410 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1411 NV_ENC_REGISTER_RESOURCE reg;
1414 for (i = 0; i < ctx->nb_registered_frames; i++) {
1415 if (ctx->registered_frames[i].ptr == (CUdeviceptr)frame->data[0])
1419 idx = nvenc_find_free_reg_resource(avctx);
1423 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1424 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1425 reg.width = frames_ctx->width;
1426 reg.height = frames_ctx->height;
1427 reg.bufferFormat = ctx->surfaces[0].format;
1428 reg.pitch = frame->linesize[0];
1429 reg.resourceToRegister = frame->data[0];
1431 ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, ®);
1432 if (ret != NV_ENC_SUCCESS) {
1433 nvenc_print_error(avctx, ret, "Error registering an input resource");
1434 return AVERROR_UNKNOWN;
1437 ctx->registered_frames[idx].ptr = (CUdeviceptr)frame->data[0];
1438 ctx->registered_frames[idx].regptr = reg.registeredResource;
1442 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1443 NvencSurface *nvenc_frame)
1445 NvencContext *ctx = avctx->priv_data;
1446 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1447 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1450 NVENCSTATUS nv_status;
1452 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1453 int reg_idx = nvenc_register_frame(avctx, frame);
1455 av_log(avctx, AV_LOG_ERROR, "Could not register an input CUDA frame\n");
1459 res = av_frame_ref(nvenc_frame->in_ref, frame);
1463 nvenc_frame->in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1464 nvenc_frame->in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1465 nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &nvenc_frame->in_map);
1466 if (nv_status != NV_ENC_SUCCESS) {
1467 av_frame_unref(nvenc_frame->in_ref);
1468 return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
1471 ctx->registered_frames[reg_idx].mapped = 1;
1472 nvenc_frame->reg_idx = reg_idx;
1473 nvenc_frame->input_surface = nvenc_frame->in_map.mappedResource;
1474 nvenc_frame->pitch = frame->linesize[0];
1477 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1479 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1480 lockBufferParams.inputBuffer = nvenc_frame->input_surface;
1482 nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
1483 if (nv_status != NV_ENC_SUCCESS) {
1484 return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
1487 nvenc_frame->pitch = lockBufferParams.pitch;
1488 res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
1490 nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
1491 if (nv_status != NV_ENC_SUCCESS) {
1492 return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
1499 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1500 NV_ENC_PIC_PARAMS *params)
1502 NvencContext *ctx = avctx->priv_data;
1504 switch (avctx->codec->id) {
1505 case AV_CODEC_ID_H264:
1506 params->codecPicParams.h264PicParams.sliceMode =
1507 ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1508 params->codecPicParams.h264PicParams.sliceModeData =
1509 ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1511 case AV_CODEC_ID_HEVC:
1512 params->codecPicParams.hevcPicParams.sliceMode =
1513 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1514 params->codecPicParams.hevcPicParams.sliceModeData =
1515 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1520 static inline void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
1522 av_fifo_generic_write(queue, ×tamp, sizeof(timestamp), NULL);
1525 static inline int64_t timestamp_queue_dequeue(AVFifoBuffer* queue)
1527 int64_t timestamp = AV_NOPTS_VALUE;
1528 if (av_fifo_size(queue) > 0)
1529 av_fifo_generic_read(queue, ×tamp, sizeof(timestamp), NULL);
1534 static int nvenc_set_timestamp(AVCodecContext *avctx,
1535 NV_ENC_LOCK_BITSTREAM *params,
1538 NvencContext *ctx = avctx->priv_data;
1540 pkt->pts = params->outputTimeStamp;
1542 /* generate the first dts by linearly extrapolating the
1543 * first two pts values to the past */
1544 if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
1545 ctx->initial_pts[1] != AV_NOPTS_VALUE) {
1546 int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
1549 if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
1550 (ts0 > 0 && ts1 < INT64_MIN + ts0))
1551 return AVERROR(ERANGE);
1554 if ((delta < 0 && ts0 > INT64_MAX + delta) ||
1555 (delta > 0 && ts0 < INT64_MIN + delta))
1556 return AVERROR(ERANGE);
1557 pkt->dts = ts0 - delta;
1559 ctx->first_packet_output = 1;
1563 pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
1568 static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
1570 NvencContext *ctx = avctx->priv_data;
1571 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1572 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1574 uint32_t slice_mode_data;
1575 uint32_t *slice_offsets = NULL;
1576 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1577 NVENCSTATUS nv_status;
1580 enum AVPictureType pict_type;
1582 switch (avctx->codec->id) {
1583 case AV_CODEC_ID_H264:
1584 slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1586 case AV_CODEC_ID_H265:
1587 slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1590 av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
1591 res = AVERROR(EINVAL);
1594 slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
1599 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1601 lock_params.doNotWait = 0;
1602 lock_params.outputBitstream = tmpoutsurf->output_surface;
1603 lock_params.sliceOffsets = slice_offsets;
1605 nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
1606 if (nv_status != NV_ENC_SUCCESS) {
1607 res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
1611 if (res = ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes,0)) {
1612 p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1616 memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1618 nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1619 if (nv_status != NV_ENC_SUCCESS)
1620 nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
1623 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1624 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, tmpoutsurf->in_map.mappedResource);
1625 av_frame_unref(tmpoutsurf->in_ref);
1626 ctx->registered_frames[tmpoutsurf->reg_idx].mapped = 0;
1628 tmpoutsurf->input_surface = NULL;
1631 switch (lock_params.pictureType) {
1632 case NV_ENC_PIC_TYPE_IDR:
1633 pkt->flags |= AV_PKT_FLAG_KEY;
1634 case NV_ENC_PIC_TYPE_I:
1635 pict_type = AV_PICTURE_TYPE_I;
1637 case NV_ENC_PIC_TYPE_P:
1638 pict_type = AV_PICTURE_TYPE_P;
1640 case NV_ENC_PIC_TYPE_B:
1641 pict_type = AV_PICTURE_TYPE_B;
1643 case NV_ENC_PIC_TYPE_BI:
1644 pict_type = AV_PICTURE_TYPE_BI;
1647 av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
1648 av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
1649 res = AVERROR_EXTERNAL;
1653 #if FF_API_CODED_FRAME
1654 FF_DISABLE_DEPRECATION_WARNINGS
1655 avctx->coded_frame->pict_type = pict_type;
1656 FF_ENABLE_DEPRECATION_WARNINGS
1659 ff_side_data_set_encoder_stats(pkt,
1660 (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
1662 res = nvenc_set_timestamp(avctx, &lock_params, pkt);
1666 av_free(slice_offsets);
1671 timestamp_queue_dequeue(ctx->timestamp_list);
1674 av_free(slice_offsets);
1679 static int output_ready(AVCodecContext *avctx, int flush)
1681 NvencContext *ctx = avctx->priv_data;
1682 int nb_ready, nb_pending;
1684 /* when B-frames are enabled, we wait for two initial timestamps to
1685 * calculate the first dts */
1686 if (!flush && avctx->max_b_frames > 0 &&
1687 (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
1690 nb_ready = av_fifo_size(ctx->output_surface_ready_queue) / sizeof(NvencSurface*);
1691 nb_pending = av_fifo_size(ctx->output_surface_queue) / sizeof(NvencSurface*);
1693 return nb_ready > 0;
1694 return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
1697 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1698 const AVFrame *frame, int *got_packet)
1700 NVENCSTATUS nv_status;
1701 NvencSurface *tmpoutsurf, *inSurf;
1704 NvencContext *ctx = avctx->priv_data;
1705 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1706 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1708 NV_ENC_PIC_PARAMS pic_params = { 0 };
1709 pic_params.version = NV_ENC_PIC_PARAMS_VER;
1712 inSurf = get_free_frame(ctx);
1714 av_log(avctx, AV_LOG_ERROR, "No free surfaces\n");
1718 res = nvenc_upload_frame(avctx, frame, inSurf);
1720 inSurf->lockCount = 0;
1724 pic_params.inputBuffer = inSurf->input_surface;
1725 pic_params.bufferFmt = inSurf->format;
1726 pic_params.inputWidth = avctx->width;
1727 pic_params.inputHeight = avctx->height;
1728 pic_params.inputPitch = inSurf->pitch;
1729 pic_params.outputBitstream = inSurf->output_surface;
1731 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1732 if (frame->top_field_first)
1733 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
1735 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
1737 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1740 pic_params.encodePicFlags = 0;
1741 pic_params.inputTimeStamp = frame->pts;
1743 nvenc_codec_specific_pic_params(avctx, &pic_params);
1745 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1748 nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
1749 if (nv_status != NV_ENC_SUCCESS &&
1750 nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
1751 return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
1754 av_fifo_generic_write(ctx->output_surface_queue, &inSurf, sizeof(inSurf), NULL);
1755 timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
1757 if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
1758 ctx->initial_pts[0] = frame->pts;
1759 else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
1760 ctx->initial_pts[1] = frame->pts;
1763 /* all the pending buffers are now ready for output */
1764 if (nv_status == NV_ENC_SUCCESS) {
1765 while (av_fifo_size(ctx->output_surface_queue) > 0) {
1766 av_fifo_generic_read(ctx->output_surface_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
1767 av_fifo_generic_write(ctx->output_surface_ready_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
1771 if (output_ready(avctx, !frame)) {
1772 av_fifo_generic_read(ctx->output_surface_ready_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
1774 res = process_output_surface(avctx, pkt, tmpoutsurf);
1779 av_assert0(tmpoutsurf->lockCount);
1780 tmpoutsurf->lockCount--;