2 * H.264/HEVC hardware encoding using nvidia nvenc
3 * Copyright (c) 2016 Timo Rothenpieler <timo@rothenpieler.org>
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 #include "libavutil/hwcontext_cuda.h"
27 #include "libavutil/hwcontext.h"
28 #include "libavutil/imgutils.h"
29 #include "libavutil/avassert.h"
30 #include "libavutil/mem.h"
31 #include "libavutil/pixdesc.h"
34 #define NVENC_CAP 0x30
35 #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR || \
36 rc == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ || \
37 rc == NV_ENC_PARAMS_RC_CBR_HQ)
39 const enum AVPixelFormat ff_nvenc_pix_fmts[] = {
44 AV_PIX_FMT_P016, // Truncated to 10bits
45 AV_PIX_FMT_YUV444P16, // Truncated to 10bits
55 #define IS_10BIT(pix_fmt) (pix_fmt == AV_PIX_FMT_P010 || \
56 pix_fmt == AV_PIX_FMT_P016 || \
57 pix_fmt == AV_PIX_FMT_YUV444P16)
59 #define IS_YUV444(pix_fmt) (pix_fmt == AV_PIX_FMT_YUV444P || \
60 pix_fmt == AV_PIX_FMT_YUV444P16)
67 { NV_ENC_SUCCESS, 0, "success" },
68 { NV_ENC_ERR_NO_ENCODE_DEVICE, AVERROR(ENOENT), "no encode device" },
69 { NV_ENC_ERR_UNSUPPORTED_DEVICE, AVERROR(ENOSYS), "unsupported device" },
70 { NV_ENC_ERR_INVALID_ENCODERDEVICE, AVERROR(EINVAL), "invalid encoder device" },
71 { NV_ENC_ERR_INVALID_DEVICE, AVERROR(EINVAL), "invalid device" },
72 { NV_ENC_ERR_DEVICE_NOT_EXIST, AVERROR(EIO), "device does not exist" },
73 { NV_ENC_ERR_INVALID_PTR, AVERROR(EFAULT), "invalid ptr" },
74 { NV_ENC_ERR_INVALID_EVENT, AVERROR(EINVAL), "invalid event" },
75 { NV_ENC_ERR_INVALID_PARAM, AVERROR(EINVAL), "invalid param" },
76 { NV_ENC_ERR_INVALID_CALL, AVERROR(EINVAL), "invalid call" },
77 { NV_ENC_ERR_OUT_OF_MEMORY, AVERROR(ENOMEM), "out of memory" },
78 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED, AVERROR(EINVAL), "encoder not initialized" },
79 { NV_ENC_ERR_UNSUPPORTED_PARAM, AVERROR(ENOSYS), "unsupported param" },
80 { NV_ENC_ERR_LOCK_BUSY, AVERROR(EAGAIN), "lock busy" },
81 { NV_ENC_ERR_NOT_ENOUGH_BUFFER, AVERROR_BUFFER_TOO_SMALL, "not enough buffer"},
82 { NV_ENC_ERR_INVALID_VERSION, AVERROR(EINVAL), "invalid version" },
83 { NV_ENC_ERR_MAP_FAILED, AVERROR(EIO), "map failed" },
84 { NV_ENC_ERR_NEED_MORE_INPUT, AVERROR(EAGAIN), "need more input" },
85 { NV_ENC_ERR_ENCODER_BUSY, AVERROR(EAGAIN), "encoder busy" },
86 { NV_ENC_ERR_EVENT_NOT_REGISTERD, AVERROR(EBADF), "event not registered" },
87 { NV_ENC_ERR_GENERIC, AVERROR_UNKNOWN, "generic error" },
88 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY, AVERROR(EINVAL), "incompatible client key" },
89 { NV_ENC_ERR_UNIMPLEMENTED, AVERROR(ENOSYS), "unimplemented" },
90 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO), "resource register failed" },
91 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED, AVERROR(EBADF), "resource not registered" },
92 { NV_ENC_ERR_RESOURCE_NOT_MAPPED, AVERROR(EBADF), "resource not mapped" },
95 static int nvenc_map_error(NVENCSTATUS err, const char **desc)
98 for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
99 if (nvenc_errors[i].nverr == err) {
101 *desc = nvenc_errors[i].desc;
102 return nvenc_errors[i].averr;
106 *desc = "unknown error";
107 return AVERROR_UNKNOWN;
110 static int nvenc_print_error(void *log_ctx, NVENCSTATUS err,
111 const char *error_string)
115 ret = nvenc_map_error(err, &desc);
116 av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
120 static void nvenc_print_driver_requirement(AVCodecContext *avctx, int level)
122 #if NVENCAPI_CHECK_VERSION(8, 1)
123 # if defined(_WIN32) || defined(__CYGWIN__)
124 const char *minver = "390.77";
126 const char *minver = "390.25";
129 # if defined(_WIN32) || defined(__CYGWIN__)
130 const char *minver = "378.66";
132 const char *minver = "378.13";
135 av_log(avctx, level, "The minimum required Nvidia driver for nvenc is %s or newer\n", minver);
138 static av_cold int nvenc_load_libraries(AVCodecContext *avctx)
140 NvencContext *ctx = avctx->priv_data;
141 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
143 uint32_t nvenc_max_ver;
146 ret = cuda_load_functions(&dl_fn->cuda_dl, avctx);
150 ret = nvenc_load_functions(&dl_fn->nvenc_dl, avctx);
152 nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
156 err = dl_fn->nvenc_dl->NvEncodeAPIGetMaxSupportedVersion(&nvenc_max_ver);
157 if (err != NV_ENC_SUCCESS)
158 return nvenc_print_error(avctx, err, "Failed to query nvenc max version");
160 av_log(avctx, AV_LOG_VERBOSE, "Loaded Nvenc version %d.%d\n", nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
162 if ((NVENCAPI_MAJOR_VERSION << 4 | NVENCAPI_MINOR_VERSION) > nvenc_max_ver) {
163 av_log(avctx, AV_LOG_ERROR, "Driver does not support the required nvenc API version. "
164 "Required: %d.%d Found: %d.%d\n",
165 NVENCAPI_MAJOR_VERSION, NVENCAPI_MINOR_VERSION,
166 nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
167 nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
168 return AVERROR(ENOSYS);
171 dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
173 err = dl_fn->nvenc_dl->NvEncodeAPICreateInstance(&dl_fn->nvenc_funcs);
174 if (err != NV_ENC_SUCCESS)
175 return nvenc_print_error(avctx, err, "Failed to create nvenc instance");
177 av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
182 static int nvenc_push_context(AVCodecContext *avctx)
184 NvencContext *ctx = avctx->priv_data;
185 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
188 if (ctx->d3d11_device)
191 cu_res = dl_fn->cuda_dl->cuCtxPushCurrent(ctx->cu_context);
192 if (cu_res != CUDA_SUCCESS) {
193 av_log(avctx, AV_LOG_ERROR, "cuCtxPushCurrent failed\n");
194 return AVERROR_EXTERNAL;
200 static int nvenc_pop_context(AVCodecContext *avctx)
202 NvencContext *ctx = avctx->priv_data;
203 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
207 if (ctx->d3d11_device)
210 cu_res = dl_fn->cuda_dl->cuCtxPopCurrent(&dummy);
211 if (cu_res != CUDA_SUCCESS) {
212 av_log(avctx, AV_LOG_ERROR, "cuCtxPopCurrent failed\n");
213 return AVERROR_EXTERNAL;
219 static av_cold int nvenc_open_session(AVCodecContext *avctx)
221 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
222 NvencContext *ctx = avctx->priv_data;
223 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
226 params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
227 params.apiVersion = NVENCAPI_VERSION;
228 if (ctx->d3d11_device) {
229 params.device = ctx->d3d11_device;
230 params.deviceType = NV_ENC_DEVICE_TYPE_DIRECTX;
232 params.device = ctx->cu_context;
233 params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
236 ret = p_nvenc->nvEncOpenEncodeSessionEx(¶ms, &ctx->nvencoder);
237 if (ret != NV_ENC_SUCCESS) {
238 ctx->nvencoder = NULL;
239 return nvenc_print_error(avctx, ret, "OpenEncodeSessionEx failed");
245 static int nvenc_check_codec_support(AVCodecContext *avctx)
247 NvencContext *ctx = avctx->priv_data;
248 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
249 int i, ret, count = 0;
252 ret = p_nvenc->nvEncGetEncodeGUIDCount(ctx->nvencoder, &count);
254 if (ret != NV_ENC_SUCCESS || !count)
255 return AVERROR(ENOSYS);
257 guids = av_malloc(count * sizeof(GUID));
259 return AVERROR(ENOMEM);
261 ret = p_nvenc->nvEncGetEncodeGUIDs(ctx->nvencoder, guids, count, &count);
262 if (ret != NV_ENC_SUCCESS) {
263 ret = AVERROR(ENOSYS);
267 ret = AVERROR(ENOSYS);
268 for (i = 0; i < count; i++) {
269 if (!memcmp(&guids[i], &ctx->init_encode_params.encodeGUID, sizeof(*guids))) {
281 static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
283 NvencContext *ctx = avctx->priv_data;
284 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
285 NV_ENC_CAPS_PARAM params = { 0 };
288 params.version = NV_ENC_CAPS_PARAM_VER;
289 params.capsToQuery = cap;
291 ret = p_nvenc->nvEncGetEncodeCaps(ctx->nvencoder, ctx->init_encode_params.encodeGUID, ¶ms, &val);
293 if (ret == NV_ENC_SUCCESS)
298 static int nvenc_check_capabilities(AVCodecContext *avctx)
300 NvencContext *ctx = avctx->priv_data;
303 ret = nvenc_check_codec_support(avctx);
305 av_log(avctx, AV_LOG_VERBOSE, "Codec not supported\n");
309 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
310 if (IS_YUV444(ctx->data_pix_fmt) && ret <= 0) {
311 av_log(avctx, AV_LOG_VERBOSE, "YUV444P not supported\n");
312 return AVERROR(ENOSYS);
315 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOSSLESS_ENCODE);
316 if (ctx->preset >= PRESET_LOSSLESS_DEFAULT && ret <= 0) {
317 av_log(avctx, AV_LOG_VERBOSE, "Lossless encoding not supported\n");
318 return AVERROR(ENOSYS);
321 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
322 if (ret < avctx->width) {
323 av_log(avctx, AV_LOG_VERBOSE, "Width %d exceeds %d\n",
325 return AVERROR(ENOSYS);
328 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
329 if (ret < avctx->height) {
330 av_log(avctx, AV_LOG_VERBOSE, "Height %d exceeds %d\n",
332 return AVERROR(ENOSYS);
335 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
336 if (ret < avctx->max_b_frames) {
337 av_log(avctx, AV_LOG_VERBOSE, "Max B-frames %d exceed %d\n",
338 avctx->max_b_frames, ret);
340 return AVERROR(ENOSYS);
343 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_FIELD_ENCODING);
344 if (ret < 1 && avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
345 av_log(avctx, AV_LOG_VERBOSE,
346 "Interlaced encoding is not supported. Supported level: %d\n",
348 return AVERROR(ENOSYS);
351 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_10BIT_ENCODE);
352 if (IS_10BIT(ctx->data_pix_fmt) && ret <= 0) {
353 av_log(avctx, AV_LOG_VERBOSE, "10 bit encode not supported\n");
354 return AVERROR(ENOSYS);
357 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOOKAHEAD);
358 if (ctx->rc_lookahead > 0 && ret <= 0) {
359 av_log(avctx, AV_LOG_VERBOSE, "RC lookahead not supported\n");
360 return AVERROR(ENOSYS);
363 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_TEMPORAL_AQ);
364 if (ctx->temporal_aq > 0 && ret <= 0) {
365 av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ not supported\n");
366 return AVERROR(ENOSYS);
369 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_WEIGHTED_PREDICTION);
370 if (ctx->weighted_pred > 0 && ret <= 0) {
371 av_log (avctx, AV_LOG_VERBOSE, "Weighted Prediction not supported\n");
372 return AVERROR(ENOSYS);
375 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_CABAC);
376 if (ctx->coder == NV_ENC_H264_ENTROPY_CODING_MODE_CABAC && ret <= 0) {
377 av_log(avctx, AV_LOG_VERBOSE, "CABAC entropy coding not supported\n");
378 return AVERROR(ENOSYS);
381 #ifdef NVENC_HAVE_BFRAME_REF_MODE
382 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_BFRAME_REF_MODE);
383 if (ctx->b_ref_mode == NV_ENC_BFRAME_REF_MODE_EACH && ret != 1) {
384 av_log(avctx, AV_LOG_VERBOSE, "Each B frame as reference is not supported\n");
385 return AVERROR(ENOSYS);
386 } else if (ctx->b_ref_mode != NV_ENC_BFRAME_REF_MODE_DISABLED && ret == 0) {
387 av_log(avctx, AV_LOG_VERBOSE, "B frames as references are not supported\n");
388 return AVERROR(ENOSYS);
391 if (ctx->b_ref_mode != 0) {
392 av_log(avctx, AV_LOG_VERBOSE, "B frames as references need SDK 8.1 at build time\n");
393 return AVERROR(ENOSYS);
397 ctx->support_dyn_bitrate = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_DYN_BITRATE_CHANGE);
402 static av_cold int nvenc_check_device(AVCodecContext *avctx, int idx)
404 NvencContext *ctx = avctx->priv_data;
405 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
406 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
407 char name[128] = { 0};
408 int major, minor, ret;
411 int loglevel = AV_LOG_VERBOSE;
413 if (ctx->device == LIST_DEVICES)
414 loglevel = AV_LOG_INFO;
416 cu_res = dl_fn->cuda_dl->cuDeviceGet(&cu_device, idx);
417 if (cu_res != CUDA_SUCCESS) {
418 av_log(avctx, AV_LOG_ERROR,
419 "Cannot access the CUDA device %d\n",
424 cu_res = dl_fn->cuda_dl->cuDeviceGetName(name, sizeof(name), cu_device);
425 if (cu_res != CUDA_SUCCESS) {
426 av_log(avctx, AV_LOG_ERROR, "cuDeviceGetName failed on device %d\n", idx);
430 cu_res = dl_fn->cuda_dl->cuDeviceComputeCapability(&major, &minor, cu_device);
431 if (cu_res != CUDA_SUCCESS) {
432 av_log(avctx, AV_LOG_ERROR, "cuDeviceComputeCapability failed on device %d\n", idx);
436 av_log(avctx, loglevel, "[ GPU #%d - < %s > has Compute SM %d.%d ]\n", idx, name, major, minor);
437 if (((major << 4) | minor) < NVENC_CAP) {
438 av_log(avctx, loglevel, "does not support NVENC\n");
442 if (ctx->device != idx && ctx->device != ANY_DEVICE)
445 cu_res = dl_fn->cuda_dl->cuCtxCreate(&ctx->cu_context_internal, 0, cu_device);
446 if (cu_res != CUDA_SUCCESS) {
447 av_log(avctx, AV_LOG_FATAL, "Failed creating CUDA context for NVENC: 0x%x\n", (int)cu_res);
451 ctx->cu_context = ctx->cu_context_internal;
453 if ((ret = nvenc_pop_context(avctx)) < 0)
456 if ((ret = nvenc_open_session(avctx)) < 0)
459 if ((ret = nvenc_check_capabilities(avctx)) < 0)
462 av_log(avctx, loglevel, "supports NVENC\n");
464 dl_fn->nvenc_device_count++;
466 if (ctx->device == idx || ctx->device == ANY_DEVICE)
470 if ((ret = nvenc_push_context(avctx)) < 0)
473 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
474 ctx->nvencoder = NULL;
476 if ((ret = nvenc_pop_context(avctx)) < 0)
480 dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal);
481 ctx->cu_context_internal = NULL;
484 return AVERROR(ENOSYS);
487 static av_cold int nvenc_setup_device(AVCodecContext *avctx)
489 NvencContext *ctx = avctx->priv_data;
490 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
492 switch (avctx->codec->id) {
493 case AV_CODEC_ID_H264:
494 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
496 case AV_CODEC_ID_HEVC:
497 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
503 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11 || avctx->hw_frames_ctx || avctx->hw_device_ctx) {
504 AVHWFramesContext *frames_ctx;
505 AVHWDeviceContext *hwdev_ctx;
506 AVCUDADeviceContext *cuda_device_hwctx = NULL;
508 AVD3D11VADeviceContext *d3d11_device_hwctx = NULL;
512 if (avctx->hw_frames_ctx) {
513 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
514 if (frames_ctx->format == AV_PIX_FMT_CUDA)
515 cuda_device_hwctx = frames_ctx->device_ctx->hwctx;
517 else if (frames_ctx->format == AV_PIX_FMT_D3D11)
518 d3d11_device_hwctx = frames_ctx->device_ctx->hwctx;
521 return AVERROR(EINVAL);
522 } else if (avctx->hw_device_ctx) {
523 hwdev_ctx = (AVHWDeviceContext*)avctx->hw_device_ctx->data;
524 if (hwdev_ctx->type == AV_HWDEVICE_TYPE_CUDA)
525 cuda_device_hwctx = hwdev_ctx->hwctx;
527 else if (hwdev_ctx->type == AV_HWDEVICE_TYPE_D3D11VA)
528 d3d11_device_hwctx = hwdev_ctx->hwctx;
531 return AVERROR(EINVAL);
533 return AVERROR(EINVAL);
536 if (cuda_device_hwctx) {
537 ctx->cu_context = cuda_device_hwctx->cuda_ctx;
540 else if (d3d11_device_hwctx) {
541 ctx->d3d11_device = d3d11_device_hwctx->device;
542 ID3D11Device_AddRef(ctx->d3d11_device);
546 ret = nvenc_open_session(avctx);
550 ret = nvenc_check_capabilities(avctx);
552 av_log(avctx, AV_LOG_FATAL, "Provided device doesn't support required NVENC features\n");
556 int i, nb_devices = 0;
558 if ((dl_fn->cuda_dl->cuInit(0)) != CUDA_SUCCESS) {
559 av_log(avctx, AV_LOG_ERROR,
560 "Cannot init CUDA\n");
561 return AVERROR_UNKNOWN;
564 if ((dl_fn->cuda_dl->cuDeviceGetCount(&nb_devices)) != CUDA_SUCCESS) {
565 av_log(avctx, AV_LOG_ERROR,
566 "Cannot enumerate the CUDA devices\n");
567 return AVERROR_UNKNOWN;
571 av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
572 return AVERROR_EXTERNAL;
575 av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", nb_devices);
577 dl_fn->nvenc_device_count = 0;
578 for (i = 0; i < nb_devices; ++i) {
579 if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
583 if (ctx->device == LIST_DEVICES)
586 if (!dl_fn->nvenc_device_count) {
587 av_log(avctx, AV_LOG_FATAL, "No NVENC capable devices found\n");
588 return AVERROR_EXTERNAL;
591 av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->device, nb_devices);
592 return AVERROR(EINVAL);
598 typedef struct GUIDTuple {
603 #define PRESET_ALIAS(alias, name, ...) \
604 [PRESET_ ## alias] = { NV_ENC_PRESET_ ## name ## _GUID, __VA_ARGS__ }
606 #define PRESET(name, ...) PRESET_ALIAS(name, name, __VA_ARGS__)
608 static void nvenc_map_preset(NvencContext *ctx)
610 GUIDTuple presets[] = {
615 PRESET_ALIAS(SLOW, HQ, NVENC_TWO_PASSES),
616 PRESET_ALIAS(MEDIUM, HQ, NVENC_ONE_PASS),
617 PRESET_ALIAS(FAST, HP, NVENC_ONE_PASS),
618 PRESET(LOW_LATENCY_DEFAULT, NVENC_LOWLATENCY),
619 PRESET(LOW_LATENCY_HP, NVENC_LOWLATENCY),
620 PRESET(LOW_LATENCY_HQ, NVENC_LOWLATENCY),
621 PRESET(LOSSLESS_DEFAULT, NVENC_LOSSLESS),
622 PRESET(LOSSLESS_HP, NVENC_LOSSLESS),
625 GUIDTuple *t = &presets[ctx->preset];
627 ctx->init_encode_params.presetGUID = t->guid;
628 ctx->flags = t->flags;
634 static av_cold void set_constqp(AVCodecContext *avctx)
636 NvencContext *ctx = avctx->priv_data;
637 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
639 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
641 if (ctx->init_qp_p >= 0) {
642 rc->constQP.qpInterP = ctx->init_qp_p;
643 if (ctx->init_qp_i >= 0 && ctx->init_qp_b >= 0) {
644 rc->constQP.qpIntra = ctx->init_qp_i;
645 rc->constQP.qpInterB = ctx->init_qp_b;
646 } else if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
647 rc->constQP.qpIntra = av_clip(
648 rc->constQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
649 rc->constQP.qpInterB = av_clip(
650 rc->constQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
652 rc->constQP.qpIntra = rc->constQP.qpInterP;
653 rc->constQP.qpInterB = rc->constQP.qpInterP;
655 } else if (ctx->cqp >= 0) {
656 rc->constQP.qpInterP = rc->constQP.qpInterB = rc->constQP.qpIntra = ctx->cqp;
657 if (avctx->b_quant_factor != 0.0)
658 rc->constQP.qpInterB = av_clip(ctx->cqp * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
659 if (avctx->i_quant_factor != 0.0)
660 rc->constQP.qpIntra = av_clip(ctx->cqp * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
667 static av_cold void set_vbr(AVCodecContext *avctx)
669 NvencContext *ctx = avctx->priv_data;
670 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
673 if (avctx->qmin >= 0 && avctx->qmax >= 0) {
677 rc->minQP.qpInterB = avctx->qmin;
678 rc->minQP.qpInterP = avctx->qmin;
679 rc->minQP.qpIntra = avctx->qmin;
681 rc->maxQP.qpInterB = avctx->qmax;
682 rc->maxQP.qpInterP = avctx->qmax;
683 rc->maxQP.qpIntra = avctx->qmax;
685 qp_inter_p = (avctx->qmax + 3 * avctx->qmin) / 4; // biased towards Qmin
686 } else if (avctx->qmin >= 0) {
689 rc->minQP.qpInterB = avctx->qmin;
690 rc->minQP.qpInterP = avctx->qmin;
691 rc->minQP.qpIntra = avctx->qmin;
693 qp_inter_p = avctx->qmin;
695 qp_inter_p = 26; // default to 26
698 rc->enableInitialRCQP = 1;
700 if (ctx->init_qp_p < 0) {
701 rc->initialRCQP.qpInterP = qp_inter_p;
703 rc->initialRCQP.qpInterP = ctx->init_qp_p;
706 if (ctx->init_qp_i < 0) {
707 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
708 rc->initialRCQP.qpIntra = av_clip(
709 rc->initialRCQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
711 rc->initialRCQP.qpIntra = rc->initialRCQP.qpInterP;
714 rc->initialRCQP.qpIntra = ctx->init_qp_i;
717 if (ctx->init_qp_b < 0) {
718 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
719 rc->initialRCQP.qpInterB = av_clip(
720 rc->initialRCQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
722 rc->initialRCQP.qpInterB = rc->initialRCQP.qpInterP;
725 rc->initialRCQP.qpInterB = ctx->init_qp_b;
729 static av_cold void set_lossless(AVCodecContext *avctx)
731 NvencContext *ctx = avctx->priv_data;
732 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
734 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
735 rc->constQP.qpInterB = 0;
736 rc->constQP.qpInterP = 0;
737 rc->constQP.qpIntra = 0;
743 static void nvenc_override_rate_control(AVCodecContext *avctx)
745 NvencContext *ctx = avctx->priv_data;
746 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
749 case NV_ENC_PARAMS_RC_CONSTQP:
752 case NV_ENC_PARAMS_RC_VBR_MINQP:
753 if (avctx->qmin < 0) {
754 av_log(avctx, AV_LOG_WARNING,
755 "The variable bitrate rate-control requires "
756 "the 'qmin' option set.\n");
761 case NV_ENC_PARAMS_RC_VBR_HQ:
762 case NV_ENC_PARAMS_RC_VBR:
765 case NV_ENC_PARAMS_RC_CBR:
766 case NV_ENC_PARAMS_RC_CBR_HQ:
767 case NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ:
771 rc->rateControlMode = ctx->rc;
774 static av_cold int nvenc_recalc_surfaces(AVCodecContext *avctx)
776 NvencContext *ctx = avctx->priv_data;
777 // default minimum of 4 surfaces
778 // multiply by 2 for number of NVENCs on gpu (hardcode to 2)
779 // another multiply by 2 to avoid blocking next PBB group
780 int nb_surfaces = FFMAX(4, ctx->encode_config.frameIntervalP * 2 * 2);
783 if (ctx->rc_lookahead > 0) {
784 // +1 is to account for lkd_bound calculation later
785 // +4 is to allow sufficient pipelining with lookahead
786 nb_surfaces = FFMAX(1, FFMAX(nb_surfaces, ctx->rc_lookahead + ctx->encode_config.frameIntervalP + 1 + 4));
787 if (nb_surfaces > ctx->nb_surfaces && ctx->nb_surfaces > 0)
789 av_log(avctx, AV_LOG_WARNING,
790 "Defined rc_lookahead requires more surfaces, "
791 "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
793 ctx->nb_surfaces = FFMAX(nb_surfaces, ctx->nb_surfaces);
795 if (ctx->encode_config.frameIntervalP > 1 && ctx->nb_surfaces < nb_surfaces && ctx->nb_surfaces > 0)
797 av_log(avctx, AV_LOG_WARNING,
798 "Defined b-frame requires more surfaces, "
799 "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
800 ctx->nb_surfaces = FFMAX(ctx->nb_surfaces, nb_surfaces);
802 else if (ctx->nb_surfaces <= 0)
803 ctx->nb_surfaces = nb_surfaces;
804 // otherwise use user specified value
807 ctx->nb_surfaces = FFMAX(1, FFMIN(MAX_REGISTERED_FRAMES, ctx->nb_surfaces));
808 ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
813 static av_cold void nvenc_setup_rate_control(AVCodecContext *avctx)
815 NvencContext *ctx = avctx->priv_data;
817 if (avctx->global_quality > 0)
818 av_log(avctx, AV_LOG_WARNING, "Using global_quality with nvenc is deprecated. Use qp instead.\n");
820 if (ctx->cqp < 0 && avctx->global_quality > 0)
821 ctx->cqp = avctx->global_quality;
823 if (avctx->bit_rate > 0) {
824 ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
825 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
826 ctx->encode_config.rcParams.maxBitRate = ctx->encode_config.rcParams.averageBitRate;
829 if (avctx->rc_max_rate > 0)
830 ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
833 if (ctx->flags & NVENC_ONE_PASS)
835 if (ctx->flags & NVENC_TWO_PASSES)
838 if (ctx->twopass < 0)
839 ctx->twopass = (ctx->flags & NVENC_LOWLATENCY) != 0;
843 ctx->rc = NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ;
845 ctx->rc = NV_ENC_PARAMS_RC_CBR;
847 } else if (ctx->cqp >= 0) {
848 ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
849 } else if (ctx->twopass) {
850 ctx->rc = NV_ENC_PARAMS_RC_VBR_HQ;
851 } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
852 ctx->rc = NV_ENC_PARAMS_RC_VBR_MINQP;
856 if (ctx->rc >= 0 && ctx->rc & RC_MODE_DEPRECATED) {
857 av_log(avctx, AV_LOG_WARNING, "Specified rc mode is deprecated.\n");
858 av_log(avctx, AV_LOG_WARNING, "\tll_2pass_quality -> cbr_ld_hq\n");
859 av_log(avctx, AV_LOG_WARNING, "\tll_2pass_size -> cbr_hq\n");
860 av_log(avctx, AV_LOG_WARNING, "\tvbr_2pass -> vbr_hq\n");
861 av_log(avctx, AV_LOG_WARNING, "\tvbr_minqp -> (no replacement)\n");
863 ctx->rc &= ~RC_MODE_DEPRECATED;
866 if (ctx->flags & NVENC_LOSSLESS) {
868 } else if (ctx->rc >= 0) {
869 nvenc_override_rate_control(avctx);
871 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
875 if (avctx->rc_buffer_size > 0) {
876 ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
877 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
878 avctx->rc_buffer_size = ctx->encode_config.rcParams.vbvBufferSize = 2 * ctx->encode_config.rcParams.averageBitRate;
882 ctx->encode_config.rcParams.enableAQ = 1;
883 ctx->encode_config.rcParams.aqStrength = ctx->aq_strength;
884 av_log(avctx, AV_LOG_VERBOSE, "AQ enabled.\n");
887 if (ctx->temporal_aq) {
888 ctx->encode_config.rcParams.enableTemporalAQ = 1;
889 av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ enabled.\n");
892 if (ctx->rc_lookahead > 0) {
893 int lkd_bound = FFMIN(ctx->nb_surfaces, ctx->async_depth) -
894 ctx->encode_config.frameIntervalP - 4;
897 av_log(avctx, AV_LOG_WARNING,
898 "Lookahead not enabled. Increase buffer delay (-delay).\n");
900 ctx->encode_config.rcParams.enableLookahead = 1;
901 ctx->encode_config.rcParams.lookaheadDepth = av_clip(ctx->rc_lookahead, 0, lkd_bound);
902 ctx->encode_config.rcParams.disableIadapt = ctx->no_scenecut;
903 ctx->encode_config.rcParams.disableBadapt = !ctx->b_adapt;
904 av_log(avctx, AV_LOG_VERBOSE,
905 "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",
906 ctx->encode_config.rcParams.lookaheadDepth,
907 ctx->encode_config.rcParams.disableIadapt ? "disabled" : "enabled",
908 ctx->encode_config.rcParams.disableBadapt ? "disabled" : "enabled");
912 if (ctx->strict_gop) {
913 ctx->encode_config.rcParams.strictGOPTarget = 1;
914 av_log(avctx, AV_LOG_VERBOSE, "Strict GOP target enabled.\n");
918 ctx->encode_config.rcParams.enableNonRefP = 1;
920 if (ctx->zerolatency)
921 ctx->encode_config.rcParams.zeroReorderDelay = 1;
925 //convert from float to fixed point 8.8
926 int tmp_quality = (int)(ctx->quality * 256.0f);
927 ctx->encode_config.rcParams.targetQuality = (uint8_t)(tmp_quality >> 8);
928 ctx->encode_config.rcParams.targetQualityLSB = (uint8_t)(tmp_quality & 0xff);
932 static av_cold int nvenc_setup_h264_config(AVCodecContext *avctx)
934 NvencContext *ctx = avctx->priv_data;
935 NV_ENC_CONFIG *cc = &ctx->encode_config;
936 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
937 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
939 vui->colourMatrix = avctx->colorspace;
940 vui->colourPrimaries = avctx->color_primaries;
941 vui->transferCharacteristics = avctx->color_trc;
942 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
943 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
945 vui->colourDescriptionPresentFlag =
946 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
948 vui->videoSignalTypePresentFlag =
949 (vui->colourDescriptionPresentFlag
950 || vui->videoFormat != 5
951 || vui->videoFullRangeFlag != 0);
954 h264->sliceModeData = 1;
956 h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
957 h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
958 h264->outputAUD = ctx->aud;
960 if (avctx->refs >= 0) {
961 /* 0 means "let the hardware decide" */
962 h264->maxNumRefFrames = avctx->refs;
964 if (avctx->gop_size >= 0) {
965 h264->idrPeriod = cc->gopLength;
968 if (IS_CBR(cc->rcParams.rateControlMode)) {
969 h264->outputBufferingPeriodSEI = 1;
972 h264->outputPictureTimingSEI = 1;
974 if (cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ ||
975 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_HQ ||
976 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_VBR_HQ) {
977 h264->adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
978 h264->fmoMode = NV_ENC_H264_FMO_DISABLE;
981 if (ctx->flags & NVENC_LOSSLESS) {
982 h264->qpPrimeYZeroTransformBypassFlag = 1;
984 switch(ctx->profile) {
985 case NV_ENC_H264_PROFILE_BASELINE:
986 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
987 avctx->profile = FF_PROFILE_H264_BASELINE;
989 case NV_ENC_H264_PROFILE_MAIN:
990 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
991 avctx->profile = FF_PROFILE_H264_MAIN;
993 case NV_ENC_H264_PROFILE_HIGH:
994 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
995 avctx->profile = FF_PROFILE_H264_HIGH;
997 case NV_ENC_H264_PROFILE_HIGH_444P:
998 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
999 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
1004 // force setting profile as high444p if input is AV_PIX_FMT_YUV444P
1005 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P) {
1006 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1007 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
1010 h264->chromaFormatIDC = avctx->profile == FF_PROFILE_H264_HIGH_444_PREDICTIVE ? 3 : 1;
1012 h264->level = ctx->level;
1014 if (ctx->coder >= 0)
1015 h264->entropyCodingMode = ctx->coder;
1017 #ifdef NVENC_HAVE_BFRAME_REF_MODE
1018 h264->useBFramesAsRef = ctx->b_ref_mode;
1024 static av_cold int nvenc_setup_hevc_config(AVCodecContext *avctx)
1026 NvencContext *ctx = avctx->priv_data;
1027 NV_ENC_CONFIG *cc = &ctx->encode_config;
1028 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
1029 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
1031 vui->colourMatrix = avctx->colorspace;
1032 vui->colourPrimaries = avctx->color_primaries;
1033 vui->transferCharacteristics = avctx->color_trc;
1034 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
1035 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
1037 vui->colourDescriptionPresentFlag =
1038 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
1040 vui->videoSignalTypePresentFlag =
1041 (vui->colourDescriptionPresentFlag
1042 || vui->videoFormat != 5
1043 || vui->videoFullRangeFlag != 0);
1045 hevc->sliceMode = 3;
1046 hevc->sliceModeData = 1;
1048 hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
1049 hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
1050 hevc->outputAUD = ctx->aud;
1052 if (avctx->refs >= 0) {
1053 /* 0 means "let the hardware decide" */
1054 hevc->maxNumRefFramesInDPB = avctx->refs;
1056 if (avctx->gop_size >= 0) {
1057 hevc->idrPeriod = cc->gopLength;
1060 if (IS_CBR(cc->rcParams.rateControlMode)) {
1061 hevc->outputBufferingPeriodSEI = 1;
1064 hevc->outputPictureTimingSEI = 1;
1066 switch (ctx->profile) {
1067 case NV_ENC_HEVC_PROFILE_MAIN:
1068 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
1069 avctx->profile = FF_PROFILE_HEVC_MAIN;
1071 case NV_ENC_HEVC_PROFILE_MAIN_10:
1072 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1073 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
1075 case NV_ENC_HEVC_PROFILE_REXT:
1076 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1077 avctx->profile = FF_PROFILE_HEVC_REXT;
1081 // force setting profile as main10 if input is 10 bit
1082 if (IS_10BIT(ctx->data_pix_fmt)) {
1083 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1084 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
1087 // force setting profile as rext if input is yuv444
1088 if (IS_YUV444(ctx->data_pix_fmt)) {
1089 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1090 avctx->profile = FF_PROFILE_HEVC_REXT;
1093 hevc->chromaFormatIDC = IS_YUV444(ctx->data_pix_fmt) ? 3 : 1;
1095 hevc->pixelBitDepthMinus8 = IS_10BIT(ctx->data_pix_fmt) ? 2 : 0;
1097 hevc->level = ctx->level;
1099 hevc->tier = ctx->tier;
1104 static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx)
1106 switch (avctx->codec->id) {
1107 case AV_CODEC_ID_H264:
1108 return nvenc_setup_h264_config(avctx);
1109 case AV_CODEC_ID_HEVC:
1110 return nvenc_setup_hevc_config(avctx);
1111 /* Earlier switch/case will return if unknown codec is passed. */
1117 static void compute_dar(AVCodecContext *avctx, int *dw, int *dh) {
1123 if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0) {
1124 sw *= avctx->sample_aspect_ratio.num;
1125 sh *= avctx->sample_aspect_ratio.den;
1128 av_reduce(dw, dh, sw, sh, 1024 * 1024);
1131 static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
1133 NvencContext *ctx = avctx->priv_data;
1134 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1135 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1137 NV_ENC_PRESET_CONFIG preset_config = { 0 };
1138 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
1139 AVCPBProperties *cpb_props;
1143 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1144 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
1146 ctx->init_encode_params.encodeHeight = avctx->height;
1147 ctx->init_encode_params.encodeWidth = avctx->width;
1149 ctx->init_encode_params.encodeConfig = &ctx->encode_config;
1151 nvenc_map_preset(ctx);
1153 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
1154 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
1156 nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder,
1157 ctx->init_encode_params.encodeGUID,
1158 ctx->init_encode_params.presetGUID,
1160 if (nv_status != NV_ENC_SUCCESS)
1161 return nvenc_print_error(avctx, nv_status, "Cannot get the preset configuration");
1163 memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
1165 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1167 compute_dar(avctx, &dw, &dh);
1168 ctx->init_encode_params.darHeight = dh;
1169 ctx->init_encode_params.darWidth = dw;
1171 ctx->init_encode_params.frameRateNum = avctx->time_base.den;
1172 ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
1174 ctx->init_encode_params.enableEncodeAsync = 0;
1175 ctx->init_encode_params.enablePTD = 1;
1177 if (ctx->weighted_pred == 1)
1178 ctx->init_encode_params.enableWeightedPrediction = 1;
1180 if (ctx->bluray_compat) {
1182 avctx->refs = FFMIN(FFMAX(avctx->refs, 0), 6);
1183 avctx->max_b_frames = FFMIN(avctx->max_b_frames, 3);
1184 switch (avctx->codec->id) {
1185 case AV_CODEC_ID_H264:
1186 /* maximum level depends on used resolution */
1188 case AV_CODEC_ID_HEVC:
1189 ctx->level = NV_ENC_LEVEL_HEVC_51;
1190 ctx->tier = NV_ENC_TIER_HEVC_HIGH;
1195 if (avctx->gop_size > 0) {
1196 if (avctx->max_b_frames >= 0) {
1197 /* 0 is intra-only, 1 is I/P only, 2 is one B-Frame, 3 two B-frames, and so on. */
1198 ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
1201 ctx->encode_config.gopLength = avctx->gop_size;
1202 } else if (avctx->gop_size == 0) {
1203 ctx->encode_config.frameIntervalP = 0;
1204 ctx->encode_config.gopLength = 1;
1207 ctx->initial_pts[0] = AV_NOPTS_VALUE;
1208 ctx->initial_pts[1] = AV_NOPTS_VALUE;
1210 nvenc_recalc_surfaces(avctx);
1212 nvenc_setup_rate_control(avctx);
1214 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1215 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
1217 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
1220 res = nvenc_setup_codec_config(avctx);
1224 res = nvenc_push_context(avctx);
1228 nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
1230 res = nvenc_pop_context(avctx);
1234 if (nv_status != NV_ENC_SUCCESS) {
1235 return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
1238 if (ctx->encode_config.frameIntervalP > 1)
1239 avctx->has_b_frames = 2;
1241 if (ctx->encode_config.rcParams.averageBitRate > 0)
1242 avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
1244 cpb_props = ff_add_cpb_side_data(avctx);
1246 return AVERROR(ENOMEM);
1247 cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
1248 cpb_props->avg_bitrate = avctx->bit_rate;
1249 cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
1254 static NV_ENC_BUFFER_FORMAT nvenc_map_buffer_format(enum AVPixelFormat pix_fmt)
1257 case AV_PIX_FMT_YUV420P:
1258 return NV_ENC_BUFFER_FORMAT_YV12_PL;
1259 case AV_PIX_FMT_NV12:
1260 return NV_ENC_BUFFER_FORMAT_NV12_PL;
1261 case AV_PIX_FMT_P010:
1262 case AV_PIX_FMT_P016:
1263 return NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1264 case AV_PIX_FMT_YUV444P:
1265 return NV_ENC_BUFFER_FORMAT_YUV444_PL;
1266 case AV_PIX_FMT_YUV444P16:
1267 return NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1268 case AV_PIX_FMT_0RGB32:
1269 return NV_ENC_BUFFER_FORMAT_ARGB;
1270 case AV_PIX_FMT_0BGR32:
1271 return NV_ENC_BUFFER_FORMAT_ABGR;
1273 return NV_ENC_BUFFER_FORMAT_UNDEFINED;
1277 static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
1279 NvencContext *ctx = avctx->priv_data;
1280 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1281 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1282 NvencSurface* tmp_surface = &ctx->surfaces[idx];
1284 NVENCSTATUS nv_status;
1285 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
1286 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1288 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1289 ctx->surfaces[idx].in_ref = av_frame_alloc();
1290 if (!ctx->surfaces[idx].in_ref)
1291 return AVERROR(ENOMEM);
1293 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1295 ctx->surfaces[idx].format = nvenc_map_buffer_format(ctx->data_pix_fmt);
1296 if (ctx->surfaces[idx].format == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1297 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1298 av_get_pix_fmt_name(ctx->data_pix_fmt));
1299 return AVERROR(EINVAL);
1302 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1303 allocSurf.width = avctx->width;
1304 allocSurf.height = avctx->height;
1305 allocSurf.bufferFmt = ctx->surfaces[idx].format;
1307 nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
1308 if (nv_status != NV_ENC_SUCCESS) {
1309 return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
1312 ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
1313 ctx->surfaces[idx].width = allocSurf.width;
1314 ctx->surfaces[idx].height = allocSurf.height;
1317 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
1318 if (nv_status != NV_ENC_SUCCESS) {
1319 int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
1320 if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
1321 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
1322 av_frame_free(&ctx->surfaces[idx].in_ref);
1326 ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1327 ctx->surfaces[idx].size = allocOut.size;
1329 av_fifo_generic_write(ctx->unused_surface_queue, &tmp_surface, sizeof(tmp_surface), NULL);
1334 static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx)
1336 NvencContext *ctx = avctx->priv_data;
1337 int i, res = 0, res2;
1339 ctx->surfaces = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->surfaces));
1341 return AVERROR(ENOMEM);
1343 ctx->timestamp_list = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
1344 if (!ctx->timestamp_list)
1345 return AVERROR(ENOMEM);
1347 ctx->unused_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1348 if (!ctx->unused_surface_queue)
1349 return AVERROR(ENOMEM);
1351 ctx->output_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1352 if (!ctx->output_surface_queue)
1353 return AVERROR(ENOMEM);
1354 ctx->output_surface_ready_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1355 if (!ctx->output_surface_ready_queue)
1356 return AVERROR(ENOMEM);
1358 res = nvenc_push_context(avctx);
1362 for (i = 0; i < ctx->nb_surfaces; i++) {
1363 if ((res = nvenc_alloc_surface(avctx, i)) < 0)
1368 res2 = nvenc_pop_context(avctx);
1375 static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
1377 NvencContext *ctx = avctx->priv_data;
1378 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1379 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1381 NVENCSTATUS nv_status;
1382 uint32_t outSize = 0;
1383 char tmpHeader[256];
1384 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1385 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1387 payload.spsppsBuffer = tmpHeader;
1388 payload.inBufferSize = sizeof(tmpHeader);
1389 payload.outSPSPPSPayloadSize = &outSize;
1391 nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
1392 if (nv_status != NV_ENC_SUCCESS) {
1393 return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
1396 avctx->extradata_size = outSize;
1397 avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
1399 if (!avctx->extradata) {
1400 return AVERROR(ENOMEM);
1403 memcpy(avctx->extradata, tmpHeader, outSize);
1408 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
1410 NvencContext *ctx = avctx->priv_data;
1411 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1412 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1415 /* the encoder has to be flushed before it can be closed */
1416 if (ctx->nvencoder) {
1417 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
1418 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
1420 res = nvenc_push_context(avctx);
1424 p_nvenc->nvEncEncodePicture(ctx->nvencoder, ¶ms);
1427 av_fifo_freep(&ctx->timestamp_list);
1428 av_fifo_freep(&ctx->output_surface_ready_queue);
1429 av_fifo_freep(&ctx->output_surface_queue);
1430 av_fifo_freep(&ctx->unused_surface_queue);
1432 if (ctx->surfaces && (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11)) {
1433 for (i = 0; i < ctx->nb_registered_frames; i++) {
1434 if (ctx->registered_frames[i].mapped)
1435 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[i].in_map.mappedResource);
1436 if (ctx->registered_frames[i].regptr)
1437 p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1439 ctx->nb_registered_frames = 0;
1442 if (ctx->surfaces) {
1443 for (i = 0; i < ctx->nb_surfaces; ++i) {
1444 if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
1445 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
1446 av_frame_free(&ctx->surfaces[i].in_ref);
1447 p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
1450 av_freep(&ctx->surfaces);
1451 ctx->nb_surfaces = 0;
1453 if (ctx->nvencoder) {
1454 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1456 res = nvenc_pop_context(avctx);
1460 ctx->nvencoder = NULL;
1462 if (ctx->cu_context_internal)
1463 dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal);
1464 ctx->cu_context = ctx->cu_context_internal = NULL;
1467 if (ctx->d3d11_device) {
1468 ID3D11Device_Release(ctx->d3d11_device);
1469 ctx->d3d11_device = NULL;
1473 nvenc_free_functions(&dl_fn->nvenc_dl);
1474 cuda_free_functions(&dl_fn->cuda_dl);
1476 dl_fn->nvenc_device_count = 0;
1478 av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
1483 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
1485 NvencContext *ctx = avctx->priv_data;
1488 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1489 AVHWFramesContext *frames_ctx;
1490 if (!avctx->hw_frames_ctx) {
1491 av_log(avctx, AV_LOG_ERROR,
1492 "hw_frames_ctx must be set when using GPU frames as input\n");
1493 return AVERROR(EINVAL);
1495 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1496 if (frames_ctx->format != avctx->pix_fmt) {
1497 av_log(avctx, AV_LOG_ERROR,
1498 "hw_frames_ctx must match the GPU frame type\n");
1499 return AVERROR(EINVAL);
1501 ctx->data_pix_fmt = frames_ctx->sw_format;
1503 ctx->data_pix_fmt = avctx->pix_fmt;
1506 if ((ret = nvenc_load_libraries(avctx)) < 0)
1509 if ((ret = nvenc_setup_device(avctx)) < 0)
1512 if ((ret = nvenc_setup_encoder(avctx)) < 0)
1515 if ((ret = nvenc_setup_surfaces(avctx)) < 0)
1518 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1519 if ((ret = nvenc_setup_extradata(avctx)) < 0)
1526 static NvencSurface *get_free_frame(NvencContext *ctx)
1528 NvencSurface *tmp_surf;
1530 if (!(av_fifo_size(ctx->unused_surface_queue) > 0))
1534 av_fifo_generic_read(ctx->unused_surface_queue, &tmp_surf, sizeof(tmp_surf), NULL);
1538 static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *nv_surface,
1539 NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params, const AVFrame *frame)
1541 int dst_linesize[4] = {
1542 lock_buffer_params->pitch,
1543 lock_buffer_params->pitch,
1544 lock_buffer_params->pitch,
1545 lock_buffer_params->pitch
1547 uint8_t *dst_data[4];
1550 if (frame->format == AV_PIX_FMT_YUV420P)
1551 dst_linesize[1] = dst_linesize[2] >>= 1;
1553 ret = av_image_fill_pointers(dst_data, frame->format, nv_surface->height,
1554 lock_buffer_params->bufferDataPtr, dst_linesize);
1558 if (frame->format == AV_PIX_FMT_YUV420P)
1559 FFSWAP(uint8_t*, dst_data[1], dst_data[2]);
1561 av_image_copy(dst_data, dst_linesize,
1562 (const uint8_t**)frame->data, frame->linesize, frame->format,
1563 avctx->width, avctx->height);
1568 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
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;
1573 NVENCSTATUS nv_status;
1577 if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1578 for (i = 0; i < ctx->nb_registered_frames; i++) {
1579 if (!ctx->registered_frames[i].mapped) {
1580 if (ctx->registered_frames[i].regptr) {
1581 nv_status = p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1582 if (nv_status != NV_ENC_SUCCESS)
1583 return nvenc_print_error(avctx, nv_status, "Failed unregistering unused input resource");
1584 ctx->registered_frames[i].ptr = NULL;
1585 ctx->registered_frames[i].regptr = NULL;
1591 return ctx->nb_registered_frames++;
1594 av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1595 return AVERROR(ENOMEM);
1598 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1600 NvencContext *ctx = avctx->priv_data;
1601 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1602 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1604 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frame->hw_frames_ctx->data;
1605 NV_ENC_REGISTER_RESOURCE reg;
1608 for (i = 0; i < ctx->nb_registered_frames; i++) {
1609 if (avctx->pix_fmt == AV_PIX_FMT_CUDA && ctx->registered_frames[i].ptr == frame->data[0])
1611 else if (avctx->pix_fmt == AV_PIX_FMT_D3D11 && ctx->registered_frames[i].ptr == frame->data[0] && ctx->registered_frames[i].ptr_index == (intptr_t)frame->data[1])
1615 idx = nvenc_find_free_reg_resource(avctx);
1619 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1620 reg.width = frames_ctx->width;
1621 reg.height = frames_ctx->height;
1622 reg.pitch = frame->linesize[0];
1623 reg.resourceToRegister = frame->data[0];
1625 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1626 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1628 else if (avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1629 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX;
1630 reg.subResourceIndex = (intptr_t)frame->data[1];
1633 reg.bufferFormat = nvenc_map_buffer_format(frames_ctx->sw_format);
1634 if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1635 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1636 av_get_pix_fmt_name(frames_ctx->sw_format));
1637 return AVERROR(EINVAL);
1640 ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, ®);
1641 if (ret != NV_ENC_SUCCESS) {
1642 nvenc_print_error(avctx, ret, "Error registering an input resource");
1643 return AVERROR_UNKNOWN;
1646 ctx->registered_frames[idx].ptr = frame->data[0];
1647 ctx->registered_frames[idx].ptr_index = reg.subResourceIndex;
1648 ctx->registered_frames[idx].regptr = reg.registeredResource;
1652 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1653 NvencSurface *nvenc_frame)
1655 NvencContext *ctx = avctx->priv_data;
1656 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1657 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1660 NVENCSTATUS nv_status;
1662 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1663 int reg_idx = nvenc_register_frame(avctx, frame);
1665 av_log(avctx, AV_LOG_ERROR, "Could not register an input HW frame\n");
1669 res = av_frame_ref(nvenc_frame->in_ref, frame);
1673 if (!ctx->registered_frames[reg_idx].mapped) {
1674 ctx->registered_frames[reg_idx].in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1675 ctx->registered_frames[reg_idx].in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1676 nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &ctx->registered_frames[reg_idx].in_map);
1677 if (nv_status != NV_ENC_SUCCESS) {
1678 av_frame_unref(nvenc_frame->in_ref);
1679 return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
1683 ctx->registered_frames[reg_idx].mapped += 1;
1685 nvenc_frame->reg_idx = reg_idx;
1686 nvenc_frame->input_surface = ctx->registered_frames[reg_idx].in_map.mappedResource;
1687 nvenc_frame->format = ctx->registered_frames[reg_idx].in_map.mappedBufferFmt;
1688 nvenc_frame->pitch = frame->linesize[0];
1692 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1694 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1695 lockBufferParams.inputBuffer = nvenc_frame->input_surface;
1697 nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
1698 if (nv_status != NV_ENC_SUCCESS) {
1699 return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
1702 nvenc_frame->pitch = lockBufferParams.pitch;
1703 res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
1705 nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
1706 if (nv_status != NV_ENC_SUCCESS) {
1707 return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
1714 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1715 NV_ENC_PIC_PARAMS *params,
1716 NV_ENC_SEI_PAYLOAD *sei_data)
1718 NvencContext *ctx = avctx->priv_data;
1720 switch (avctx->codec->id) {
1721 case AV_CODEC_ID_H264:
1722 params->codecPicParams.h264PicParams.sliceMode =
1723 ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1724 params->codecPicParams.h264PicParams.sliceModeData =
1725 ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1727 params->codecPicParams.h264PicParams.seiPayloadArray = sei_data;
1728 params->codecPicParams.h264PicParams.seiPayloadArrayCnt = 1;
1732 case AV_CODEC_ID_HEVC:
1733 params->codecPicParams.hevcPicParams.sliceMode =
1734 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1735 params->codecPicParams.hevcPicParams.sliceModeData =
1736 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1738 params->codecPicParams.hevcPicParams.seiPayloadArray = sei_data;
1739 params->codecPicParams.hevcPicParams.seiPayloadArrayCnt = 1;
1746 static inline void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
1748 av_fifo_generic_write(queue, ×tamp, sizeof(timestamp), NULL);
1751 static inline int64_t timestamp_queue_dequeue(AVFifoBuffer* queue)
1753 int64_t timestamp = AV_NOPTS_VALUE;
1754 if (av_fifo_size(queue) > 0)
1755 av_fifo_generic_read(queue, ×tamp, sizeof(timestamp), NULL);
1760 static int nvenc_set_timestamp(AVCodecContext *avctx,
1761 NV_ENC_LOCK_BITSTREAM *params,
1764 NvencContext *ctx = avctx->priv_data;
1766 pkt->pts = params->outputTimeStamp;
1768 /* generate the first dts by linearly extrapolating the
1769 * first two pts values to the past */
1770 if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
1771 ctx->initial_pts[1] != AV_NOPTS_VALUE) {
1772 int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
1775 if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
1776 (ts0 > 0 && ts1 < INT64_MIN + ts0))
1777 return AVERROR(ERANGE);
1780 if ((delta < 0 && ts0 > INT64_MAX + delta) ||
1781 (delta > 0 && ts0 < INT64_MIN + delta))
1782 return AVERROR(ERANGE);
1783 pkt->dts = ts0 - delta;
1785 ctx->first_packet_output = 1;
1789 pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
1794 static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
1796 NvencContext *ctx = avctx->priv_data;
1797 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1798 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1800 uint32_t slice_mode_data;
1801 uint32_t *slice_offsets = NULL;
1802 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1803 NVENCSTATUS nv_status;
1806 enum AVPictureType pict_type;
1808 switch (avctx->codec->id) {
1809 case AV_CODEC_ID_H264:
1810 slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1812 case AV_CODEC_ID_H265:
1813 slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1816 av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
1817 res = AVERROR(EINVAL);
1820 slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
1822 if (!slice_offsets) {
1823 res = AVERROR(ENOMEM);
1827 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1829 lock_params.doNotWait = 0;
1830 lock_params.outputBitstream = tmpoutsurf->output_surface;
1831 lock_params.sliceOffsets = slice_offsets;
1833 nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
1834 if (nv_status != NV_ENC_SUCCESS) {
1835 res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
1839 if (res = ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes,0)) {
1840 p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1844 memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1846 nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1847 if (nv_status != NV_ENC_SUCCESS) {
1848 res = nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
1853 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1854 ctx->registered_frames[tmpoutsurf->reg_idx].mapped -= 1;
1855 if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped == 0) {
1856 nv_status = p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[tmpoutsurf->reg_idx].in_map.mappedResource);
1857 if (nv_status != NV_ENC_SUCCESS) {
1858 res = nvenc_print_error(avctx, nv_status, "Failed unmapping input resource");
1861 nv_status = p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[tmpoutsurf->reg_idx].regptr);
1862 if (nv_status != NV_ENC_SUCCESS) {
1863 res = nvenc_print_error(avctx, nv_status, "Failed unregistering input resource");
1866 ctx->registered_frames[tmpoutsurf->reg_idx].ptr = NULL;
1867 ctx->registered_frames[tmpoutsurf->reg_idx].regptr = NULL;
1868 } else if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped < 0) {
1873 av_frame_unref(tmpoutsurf->in_ref);
1875 tmpoutsurf->input_surface = NULL;
1878 switch (lock_params.pictureType) {
1879 case NV_ENC_PIC_TYPE_IDR:
1880 pkt->flags |= AV_PKT_FLAG_KEY;
1881 case NV_ENC_PIC_TYPE_I:
1882 pict_type = AV_PICTURE_TYPE_I;
1884 case NV_ENC_PIC_TYPE_P:
1885 pict_type = AV_PICTURE_TYPE_P;
1887 case NV_ENC_PIC_TYPE_B:
1888 pict_type = AV_PICTURE_TYPE_B;
1890 case NV_ENC_PIC_TYPE_BI:
1891 pict_type = AV_PICTURE_TYPE_BI;
1894 av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
1895 av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
1896 res = AVERROR_EXTERNAL;
1900 #if FF_API_CODED_FRAME
1901 FF_DISABLE_DEPRECATION_WARNINGS
1902 avctx->coded_frame->pict_type = pict_type;
1903 FF_ENABLE_DEPRECATION_WARNINGS
1906 ff_side_data_set_encoder_stats(pkt,
1907 (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
1909 res = nvenc_set_timestamp(avctx, &lock_params, pkt);
1913 av_free(slice_offsets);
1918 timestamp_queue_dequeue(ctx->timestamp_list);
1921 av_free(slice_offsets);
1926 static int output_ready(AVCodecContext *avctx, int flush)
1928 NvencContext *ctx = avctx->priv_data;
1929 int nb_ready, nb_pending;
1931 /* when B-frames are enabled, we wait for two initial timestamps to
1932 * calculate the first dts */
1933 if (!flush && avctx->max_b_frames > 0 &&
1934 (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
1937 nb_ready = av_fifo_size(ctx->output_surface_ready_queue) / sizeof(NvencSurface*);
1938 nb_pending = av_fifo_size(ctx->output_surface_queue) / sizeof(NvencSurface*);
1940 return nb_ready > 0;
1941 return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
1944 static void reconfig_encoder(AVCodecContext *avctx, const AVFrame *frame)
1946 NvencContext *ctx = avctx->priv_data;
1947 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
1950 NV_ENC_RECONFIGURE_PARAMS params = { 0 };
1951 int needs_reconfig = 0;
1952 int needs_encode_config = 0;
1953 int reconfig_bitrate = 0, reconfig_dar = 0;
1956 params.version = NV_ENC_RECONFIGURE_PARAMS_VER;
1957 params.reInitEncodeParams = ctx->init_encode_params;
1959 compute_dar(avctx, &dw, &dh);
1960 if (dw != ctx->init_encode_params.darWidth || dh != ctx->init_encode_params.darHeight) {
1961 av_log(avctx, AV_LOG_VERBOSE,
1962 "aspect ratio change (DAR): %d:%d -> %d:%d\n",
1963 ctx->init_encode_params.darWidth,
1964 ctx->init_encode_params.darHeight, dw, dh);
1966 params.reInitEncodeParams.darHeight = dh;
1967 params.reInitEncodeParams.darWidth = dw;
1973 if (ctx->rc != NV_ENC_PARAMS_RC_CONSTQP && ctx->support_dyn_bitrate) {
1974 if (avctx->bit_rate > 0 && params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate != avctx->bit_rate) {
1975 av_log(avctx, AV_LOG_VERBOSE,
1976 "avg bitrate change: %d -> %d\n",
1977 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate,
1978 (uint32_t)avctx->bit_rate);
1980 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate = avctx->bit_rate;
1981 reconfig_bitrate = 1;
1984 if (avctx->rc_max_rate > 0 && ctx->encode_config.rcParams.maxBitRate != avctx->rc_max_rate) {
1985 av_log(avctx, AV_LOG_VERBOSE,
1986 "max bitrate change: %d -> %d\n",
1987 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate,
1988 (uint32_t)avctx->rc_max_rate);
1990 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate = avctx->rc_max_rate;
1991 reconfig_bitrate = 1;
1994 if (avctx->rc_buffer_size > 0 && ctx->encode_config.rcParams.vbvBufferSize != avctx->rc_buffer_size) {
1995 av_log(avctx, AV_LOG_VERBOSE,
1996 "vbv buffer size change: %d -> %d\n",
1997 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize,
1998 avctx->rc_buffer_size);
2000 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize = avctx->rc_buffer_size;
2001 reconfig_bitrate = 1;
2004 if (reconfig_bitrate) {
2005 params.resetEncoder = 1;
2006 params.forceIDR = 1;
2008 needs_encode_config = 1;
2013 if (!needs_encode_config)
2014 params.reInitEncodeParams.encodeConfig = NULL;
2016 if (needs_reconfig) {
2017 ret = p_nvenc->nvEncReconfigureEncoder(ctx->nvencoder, ¶ms);
2018 if (ret != NV_ENC_SUCCESS) {
2019 nvenc_print_error(avctx, ret, "failed to reconfigure nvenc");
2022 ctx->init_encode_params.darHeight = dh;
2023 ctx->init_encode_params.darWidth = dw;
2026 if (reconfig_bitrate) {
2027 ctx->encode_config.rcParams.averageBitRate = params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate;
2028 ctx->encode_config.rcParams.maxBitRate = params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate;
2029 ctx->encode_config.rcParams.vbvBufferSize = params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize;
2036 int ff_nvenc_send_frame(AVCodecContext *avctx, const AVFrame *frame)
2038 NVENCSTATUS nv_status;
2039 NvencSurface *tmp_out_surf, *in_surf;
2041 NV_ENC_SEI_PAYLOAD *sei_data = NULL;
2044 NvencContext *ctx = avctx->priv_data;
2045 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
2046 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
2048 NV_ENC_PIC_PARAMS pic_params = { 0 };
2049 pic_params.version = NV_ENC_PIC_PARAMS_VER;
2051 if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
2052 return AVERROR(EINVAL);
2054 if (ctx->encoder_flushing) {
2055 if (avctx->internal->draining)
2058 ctx->encoder_flushing = 0;
2059 ctx->first_packet_output = 0;
2060 ctx->initial_pts[0] = AV_NOPTS_VALUE;
2061 ctx->initial_pts[1] = AV_NOPTS_VALUE;
2062 av_fifo_reset(ctx->timestamp_list);
2066 in_surf = get_free_frame(ctx);
2068 return AVERROR(EAGAIN);
2070 res = nvenc_push_context(avctx);
2074 reconfig_encoder(avctx, frame);
2076 res = nvenc_upload_frame(avctx, frame, in_surf);
2078 res2 = nvenc_pop_context(avctx);
2085 pic_params.inputBuffer = in_surf->input_surface;
2086 pic_params.bufferFmt = in_surf->format;
2087 pic_params.inputWidth = in_surf->width;
2088 pic_params.inputHeight = in_surf->height;
2089 pic_params.inputPitch = in_surf->pitch;
2090 pic_params.outputBitstream = in_surf->output_surface;
2092 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
2093 if (frame->top_field_first)
2094 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
2096 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
2098 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
2101 if (ctx->forced_idr >= 0 && frame->pict_type == AV_PICTURE_TYPE_I) {
2102 pic_params.encodePicFlags =
2103 ctx->forced_idr ? NV_ENC_PIC_FLAG_FORCEIDR : NV_ENC_PIC_FLAG_FORCEINTRA;
2105 pic_params.encodePicFlags = 0;
2108 pic_params.inputTimeStamp = frame->pts;
2110 if (ctx->a53_cc && av_frame_get_side_data(frame, AV_FRAME_DATA_A53_CC)) {
2111 if (ff_alloc_a53_sei(frame, sizeof(NV_ENC_SEI_PAYLOAD), (void**)&sei_data, &sei_size) < 0) {
2112 av_log(ctx, AV_LOG_ERROR, "Not enough memory for closed captions, skipping\n");
2116 sei_data->payloadSize = (uint32_t)sei_size;
2117 sei_data->payloadType = 4;
2118 sei_data->payload = (uint8_t*)(sei_data + 1);
2122 nvenc_codec_specific_pic_params(avctx, &pic_params, sei_data);
2124 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
2125 ctx->encoder_flushing = 1;
2128 res = nvenc_push_context(avctx);
2132 nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
2135 res = nvenc_pop_context(avctx);
2139 if (nv_status != NV_ENC_SUCCESS &&
2140 nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
2141 return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
2144 av_fifo_generic_write(ctx->output_surface_queue, &in_surf, sizeof(in_surf), NULL);
2145 timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
2147 if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
2148 ctx->initial_pts[0] = frame->pts;
2149 else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
2150 ctx->initial_pts[1] = frame->pts;
2153 /* all the pending buffers are now ready for output */
2154 if (nv_status == NV_ENC_SUCCESS) {
2155 while (av_fifo_size(ctx->output_surface_queue) > 0) {
2156 av_fifo_generic_read(ctx->output_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2157 av_fifo_generic_write(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2164 int ff_nvenc_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
2166 NvencSurface *tmp_out_surf;
2169 NvencContext *ctx = avctx->priv_data;
2171 if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
2172 return AVERROR(EINVAL);
2174 if (output_ready(avctx, ctx->encoder_flushing)) {
2175 av_fifo_generic_read(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2177 res = nvenc_push_context(avctx);
2181 res = process_output_surface(avctx, pkt, tmp_out_surf);
2183 res2 = nvenc_pop_context(avctx);
2190 av_fifo_generic_write(ctx->unused_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2191 } else if (ctx->encoder_flushing) {
2194 return AVERROR(EAGAIN);
2200 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
2201 const AVFrame *frame, int *got_packet)
2203 NvencContext *ctx = avctx->priv_data;
2206 if (!ctx->encoder_flushing) {
2207 res = ff_nvenc_send_frame(avctx, frame);
2212 res = ff_nvenc_receive_packet(avctx, pkt);
2213 if (res == AVERROR(EAGAIN) || res == AVERROR_EOF) {
2215 } else if (res < 0) {