2 * H.264/HEVC hardware encoding using nvidia nvenc
3 * Copyright (c) 2016 Timo Rothenpieler <timo@rothenpieler.org>
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 #include "libavutil/hwcontext_cuda.h"
27 #include "libavutil/hwcontext.h"
28 #include "libavutil/cuda_check.h"
29 #include "libavutil/imgutils.h"
30 #include "libavutil/avassert.h"
31 #include "libavutil/mem.h"
32 #include "libavutil/pixdesc.h"
35 #define CHECK_CU(x) FF_CUDA_CHECK_DL(avctx, dl_fn->cuda_dl, x)
37 #define NVENC_CAP 0x30
38 #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR || \
39 rc == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ || \
40 rc == NV_ENC_PARAMS_RC_CBR_HQ)
42 const enum AVPixelFormat ff_nvenc_pix_fmts[] = {
47 AV_PIX_FMT_P016, // Truncated to 10bits
48 AV_PIX_FMT_YUV444P16, // Truncated to 10bits
58 #define IS_10BIT(pix_fmt) (pix_fmt == AV_PIX_FMT_P010 || \
59 pix_fmt == AV_PIX_FMT_P016 || \
60 pix_fmt == AV_PIX_FMT_YUV444P16)
62 #define IS_YUV444(pix_fmt) (pix_fmt == AV_PIX_FMT_YUV444P || \
63 pix_fmt == AV_PIX_FMT_YUV444P16)
70 { NV_ENC_SUCCESS, 0, "success" },
71 { NV_ENC_ERR_NO_ENCODE_DEVICE, AVERROR(ENOENT), "no encode device" },
72 { NV_ENC_ERR_UNSUPPORTED_DEVICE, AVERROR(ENOSYS), "unsupported device" },
73 { NV_ENC_ERR_INVALID_ENCODERDEVICE, AVERROR(EINVAL), "invalid encoder device" },
74 { NV_ENC_ERR_INVALID_DEVICE, AVERROR(EINVAL), "invalid device" },
75 { NV_ENC_ERR_DEVICE_NOT_EXIST, AVERROR(EIO), "device does not exist" },
76 { NV_ENC_ERR_INVALID_PTR, AVERROR(EFAULT), "invalid ptr" },
77 { NV_ENC_ERR_INVALID_EVENT, AVERROR(EINVAL), "invalid event" },
78 { NV_ENC_ERR_INVALID_PARAM, AVERROR(EINVAL), "invalid param" },
79 { NV_ENC_ERR_INVALID_CALL, AVERROR(EINVAL), "invalid call" },
80 { NV_ENC_ERR_OUT_OF_MEMORY, AVERROR(ENOMEM), "out of memory" },
81 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED, AVERROR(EINVAL), "encoder not initialized" },
82 { NV_ENC_ERR_UNSUPPORTED_PARAM, AVERROR(ENOSYS), "unsupported param" },
83 { NV_ENC_ERR_LOCK_BUSY, AVERROR(EAGAIN), "lock busy" },
84 { NV_ENC_ERR_NOT_ENOUGH_BUFFER, AVERROR_BUFFER_TOO_SMALL, "not enough buffer"},
85 { NV_ENC_ERR_INVALID_VERSION, AVERROR(EINVAL), "invalid version" },
86 { NV_ENC_ERR_MAP_FAILED, AVERROR(EIO), "map failed" },
87 { NV_ENC_ERR_NEED_MORE_INPUT, AVERROR(EAGAIN), "need more input" },
88 { NV_ENC_ERR_ENCODER_BUSY, AVERROR(EAGAIN), "encoder busy" },
89 { NV_ENC_ERR_EVENT_NOT_REGISTERD, AVERROR(EBADF), "event not registered" },
90 { NV_ENC_ERR_GENERIC, AVERROR_UNKNOWN, "generic error" },
91 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY, AVERROR(EINVAL), "incompatible client key" },
92 { NV_ENC_ERR_UNIMPLEMENTED, AVERROR(ENOSYS), "unimplemented" },
93 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO), "resource register failed" },
94 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED, AVERROR(EBADF), "resource not registered" },
95 { NV_ENC_ERR_RESOURCE_NOT_MAPPED, AVERROR(EBADF), "resource not mapped" },
98 static int nvenc_map_error(NVENCSTATUS err, const char **desc)
101 for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
102 if (nvenc_errors[i].nverr == err) {
104 *desc = nvenc_errors[i].desc;
105 return nvenc_errors[i].averr;
109 *desc = "unknown error";
110 return AVERROR_UNKNOWN;
113 static int nvenc_print_error(void *log_ctx, NVENCSTATUS err,
114 const char *error_string)
118 ret = nvenc_map_error(err, &desc);
119 av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
123 static void nvenc_print_driver_requirement(AVCodecContext *avctx, int level)
125 #if NVENCAPI_CHECK_VERSION(8, 1)
126 # if defined(_WIN32) || defined(__CYGWIN__)
127 const char *minver = "390.77";
129 const char *minver = "390.25";
132 # if defined(_WIN32) || defined(__CYGWIN__)
133 const char *minver = "378.66";
135 const char *minver = "378.13";
138 av_log(avctx, level, "The minimum required Nvidia driver for nvenc is %s or newer\n", minver);
141 static av_cold int nvenc_load_libraries(AVCodecContext *avctx)
143 NvencContext *ctx = avctx->priv_data;
144 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
146 uint32_t nvenc_max_ver;
149 ret = cuda_load_functions(&dl_fn->cuda_dl, avctx);
153 ret = nvenc_load_functions(&dl_fn->nvenc_dl, avctx);
155 nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
159 err = dl_fn->nvenc_dl->NvEncodeAPIGetMaxSupportedVersion(&nvenc_max_ver);
160 if (err != NV_ENC_SUCCESS)
161 return nvenc_print_error(avctx, err, "Failed to query nvenc max version");
163 av_log(avctx, AV_LOG_VERBOSE, "Loaded Nvenc version %d.%d\n", nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
165 if ((NVENCAPI_MAJOR_VERSION << 4 | NVENCAPI_MINOR_VERSION) > nvenc_max_ver) {
166 av_log(avctx, AV_LOG_ERROR, "Driver does not support the required nvenc API version. "
167 "Required: %d.%d Found: %d.%d\n",
168 NVENCAPI_MAJOR_VERSION, NVENCAPI_MINOR_VERSION,
169 nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
170 nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
171 return AVERROR(ENOSYS);
174 dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
176 err = dl_fn->nvenc_dl->NvEncodeAPICreateInstance(&dl_fn->nvenc_funcs);
177 if (err != NV_ENC_SUCCESS)
178 return nvenc_print_error(avctx, err, "Failed to create nvenc instance");
180 av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
185 static int nvenc_push_context(AVCodecContext *avctx)
187 NvencContext *ctx = avctx->priv_data;
188 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
190 if (ctx->d3d11_device)
193 return CHECK_CU(dl_fn->cuda_dl->cuCtxPushCurrent(ctx->cu_context));
196 static int nvenc_pop_context(AVCodecContext *avctx)
198 NvencContext *ctx = avctx->priv_data;
199 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
202 if (ctx->d3d11_device)
205 return CHECK_CU(dl_fn->cuda_dl->cuCtxPopCurrent(&dummy));
208 static av_cold int nvenc_open_session(AVCodecContext *avctx)
210 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
211 NvencContext *ctx = avctx->priv_data;
212 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
215 params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
216 params.apiVersion = NVENCAPI_VERSION;
217 if (ctx->d3d11_device) {
218 params.device = ctx->d3d11_device;
219 params.deviceType = NV_ENC_DEVICE_TYPE_DIRECTX;
221 params.device = ctx->cu_context;
222 params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
225 ret = p_nvenc->nvEncOpenEncodeSessionEx(¶ms, &ctx->nvencoder);
226 if (ret != NV_ENC_SUCCESS) {
227 ctx->nvencoder = NULL;
228 return nvenc_print_error(avctx, ret, "OpenEncodeSessionEx failed");
234 static int nvenc_check_codec_support(AVCodecContext *avctx)
236 NvencContext *ctx = avctx->priv_data;
237 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
238 int i, ret, count = 0;
241 ret = p_nvenc->nvEncGetEncodeGUIDCount(ctx->nvencoder, &count);
243 if (ret != NV_ENC_SUCCESS || !count)
244 return AVERROR(ENOSYS);
246 guids = av_malloc(count * sizeof(GUID));
248 return AVERROR(ENOMEM);
250 ret = p_nvenc->nvEncGetEncodeGUIDs(ctx->nvencoder, guids, count, &count);
251 if (ret != NV_ENC_SUCCESS) {
252 ret = AVERROR(ENOSYS);
256 ret = AVERROR(ENOSYS);
257 for (i = 0; i < count; i++) {
258 if (!memcmp(&guids[i], &ctx->init_encode_params.encodeGUID, sizeof(*guids))) {
270 static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
272 NvencContext *ctx = avctx->priv_data;
273 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
274 NV_ENC_CAPS_PARAM params = { 0 };
277 params.version = NV_ENC_CAPS_PARAM_VER;
278 params.capsToQuery = cap;
280 ret = p_nvenc->nvEncGetEncodeCaps(ctx->nvencoder, ctx->init_encode_params.encodeGUID, ¶ms, &val);
282 if (ret == NV_ENC_SUCCESS)
287 static int nvenc_check_capabilities(AVCodecContext *avctx)
289 NvencContext *ctx = avctx->priv_data;
292 ret = nvenc_check_codec_support(avctx);
294 av_log(avctx, AV_LOG_VERBOSE, "Codec not supported\n");
298 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
299 if (IS_YUV444(ctx->data_pix_fmt) && ret <= 0) {
300 av_log(avctx, AV_LOG_VERBOSE, "YUV444P not supported\n");
301 return AVERROR(ENOSYS);
304 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOSSLESS_ENCODE);
305 if (ctx->preset >= PRESET_LOSSLESS_DEFAULT && ret <= 0) {
306 av_log(avctx, AV_LOG_VERBOSE, "Lossless encoding not supported\n");
307 return AVERROR(ENOSYS);
310 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
311 if (ret < avctx->width) {
312 av_log(avctx, AV_LOG_VERBOSE, "Width %d exceeds %d\n",
314 return AVERROR(ENOSYS);
317 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
318 if (ret < avctx->height) {
319 av_log(avctx, AV_LOG_VERBOSE, "Height %d exceeds %d\n",
321 return AVERROR(ENOSYS);
324 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
325 if (ret < avctx->max_b_frames) {
326 av_log(avctx, AV_LOG_VERBOSE, "Max B-frames %d exceed %d\n",
327 avctx->max_b_frames, ret);
329 return AVERROR(ENOSYS);
332 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_FIELD_ENCODING);
333 if (ret < 1 && avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
334 av_log(avctx, AV_LOG_VERBOSE,
335 "Interlaced encoding is not supported. Supported level: %d\n",
337 return AVERROR(ENOSYS);
340 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_10BIT_ENCODE);
341 if (IS_10BIT(ctx->data_pix_fmt) && ret <= 0) {
342 av_log(avctx, AV_LOG_VERBOSE, "10 bit encode not supported\n");
343 return AVERROR(ENOSYS);
346 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOOKAHEAD);
347 if (ctx->rc_lookahead > 0 && ret <= 0) {
348 av_log(avctx, AV_LOG_VERBOSE, "RC lookahead not supported\n");
349 return AVERROR(ENOSYS);
352 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_TEMPORAL_AQ);
353 if (ctx->temporal_aq > 0 && ret <= 0) {
354 av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ not supported\n");
355 return AVERROR(ENOSYS);
358 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_WEIGHTED_PREDICTION);
359 if (ctx->weighted_pred > 0 && ret <= 0) {
360 av_log (avctx, AV_LOG_VERBOSE, "Weighted Prediction not supported\n");
361 return AVERROR(ENOSYS);
364 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_CABAC);
365 if (ctx->coder == NV_ENC_H264_ENTROPY_CODING_MODE_CABAC && ret <= 0) {
366 av_log(avctx, AV_LOG_VERBOSE, "CABAC entropy coding not supported\n");
367 return AVERROR(ENOSYS);
370 #ifdef NVENC_HAVE_BFRAME_REF_MODE
371 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_BFRAME_REF_MODE);
372 if (ctx->b_ref_mode == NV_ENC_BFRAME_REF_MODE_EACH && ret != 1) {
373 av_log(avctx, AV_LOG_VERBOSE, "Each B frame as reference is not supported\n");
374 return AVERROR(ENOSYS);
375 } else if (ctx->b_ref_mode != NV_ENC_BFRAME_REF_MODE_DISABLED && ret == 0) {
376 av_log(avctx, AV_LOG_VERBOSE, "B frames as references are not supported\n");
377 return AVERROR(ENOSYS);
380 if (ctx->b_ref_mode != 0) {
381 av_log(avctx, AV_LOG_VERBOSE, "B frames as references need SDK 8.1 at build time\n");
382 return AVERROR(ENOSYS);
386 ctx->support_dyn_bitrate = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_DYN_BITRATE_CHANGE);
391 static av_cold int nvenc_check_device(AVCodecContext *avctx, int idx)
393 NvencContext *ctx = avctx->priv_data;
394 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
395 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
396 char name[128] = { 0};
397 int major, minor, ret;
399 int loglevel = AV_LOG_VERBOSE;
401 if (ctx->device == LIST_DEVICES)
402 loglevel = AV_LOG_INFO;
404 ret = CHECK_CU(dl_fn->cuda_dl->cuDeviceGet(&cu_device, idx));
408 ret = CHECK_CU(dl_fn->cuda_dl->cuDeviceGetName(name, sizeof(name), cu_device));
412 ret = CHECK_CU(dl_fn->cuda_dl->cuDeviceComputeCapability(&major, &minor, cu_device));
416 av_log(avctx, loglevel, "[ GPU #%d - < %s > has Compute SM %d.%d ]\n", idx, name, major, minor);
417 if (((major << 4) | minor) < NVENC_CAP) {
418 av_log(avctx, loglevel, "does not support NVENC\n");
422 if (ctx->device != idx && ctx->device != ANY_DEVICE)
425 ret = CHECK_CU(dl_fn->cuda_dl->cuCtxCreate(&ctx->cu_context_internal, 0, cu_device));
429 ctx->cu_context = ctx->cu_context_internal;
431 if ((ret = nvenc_pop_context(avctx)) < 0)
434 if ((ret = nvenc_open_session(avctx)) < 0)
437 if ((ret = nvenc_check_capabilities(avctx)) < 0)
440 av_log(avctx, loglevel, "supports NVENC\n");
442 dl_fn->nvenc_device_count++;
444 if (ctx->device == idx || ctx->device == ANY_DEVICE)
448 if ((ret = nvenc_push_context(avctx)) < 0)
451 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
452 ctx->nvencoder = NULL;
454 if ((ret = nvenc_pop_context(avctx)) < 0)
458 CHECK_CU(dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal));
459 ctx->cu_context_internal = NULL;
462 return AVERROR(ENOSYS);
465 static av_cold int nvenc_setup_device(AVCodecContext *avctx)
467 NvencContext *ctx = avctx->priv_data;
468 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
470 switch (avctx->codec->id) {
471 case AV_CODEC_ID_H264:
472 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
474 case AV_CODEC_ID_HEVC:
475 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
481 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11 || avctx->hw_frames_ctx || avctx->hw_device_ctx) {
482 AVHWFramesContext *frames_ctx;
483 AVHWDeviceContext *hwdev_ctx;
484 AVCUDADeviceContext *cuda_device_hwctx = NULL;
486 AVD3D11VADeviceContext *d3d11_device_hwctx = NULL;
490 if (avctx->hw_frames_ctx) {
491 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
492 if (frames_ctx->format == AV_PIX_FMT_CUDA)
493 cuda_device_hwctx = frames_ctx->device_ctx->hwctx;
495 else if (frames_ctx->format == AV_PIX_FMT_D3D11)
496 d3d11_device_hwctx = frames_ctx->device_ctx->hwctx;
499 return AVERROR(EINVAL);
500 } else if (avctx->hw_device_ctx) {
501 hwdev_ctx = (AVHWDeviceContext*)avctx->hw_device_ctx->data;
502 if (hwdev_ctx->type == AV_HWDEVICE_TYPE_CUDA)
503 cuda_device_hwctx = hwdev_ctx->hwctx;
505 else if (hwdev_ctx->type == AV_HWDEVICE_TYPE_D3D11VA)
506 d3d11_device_hwctx = hwdev_ctx->hwctx;
509 return AVERROR(EINVAL);
511 return AVERROR(EINVAL);
514 if (cuda_device_hwctx) {
515 ctx->cu_context = cuda_device_hwctx->cuda_ctx;
518 else if (d3d11_device_hwctx) {
519 ctx->d3d11_device = d3d11_device_hwctx->device;
520 ID3D11Device_AddRef(ctx->d3d11_device);
524 ret = nvenc_open_session(avctx);
528 ret = nvenc_check_capabilities(avctx);
530 av_log(avctx, AV_LOG_FATAL, "Provided device doesn't support required NVENC features\n");
534 int i, nb_devices = 0;
536 if (CHECK_CU(dl_fn->cuda_dl->cuInit(0)) < 0)
537 return AVERROR_UNKNOWN;
539 if (CHECK_CU(dl_fn->cuda_dl->cuDeviceGetCount(&nb_devices)) < 0)
540 return AVERROR_UNKNOWN;
543 av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
544 return AVERROR_EXTERNAL;
547 av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", nb_devices);
549 dl_fn->nvenc_device_count = 0;
550 for (i = 0; i < nb_devices; ++i) {
551 if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
555 if (ctx->device == LIST_DEVICES)
558 if (!dl_fn->nvenc_device_count) {
559 av_log(avctx, AV_LOG_FATAL, "No NVENC capable devices found\n");
560 return AVERROR_EXTERNAL;
563 av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->device, nb_devices);
564 return AVERROR(EINVAL);
570 typedef struct GUIDTuple {
575 #define PRESET_ALIAS(alias, name, ...) \
576 [PRESET_ ## alias] = { NV_ENC_PRESET_ ## name ## _GUID, __VA_ARGS__ }
578 #define PRESET(name, ...) PRESET_ALIAS(name, name, __VA_ARGS__)
580 static void nvenc_map_preset(NvencContext *ctx)
582 GUIDTuple presets[] = {
587 PRESET_ALIAS(SLOW, HQ, NVENC_TWO_PASSES),
588 PRESET_ALIAS(MEDIUM, HQ, NVENC_ONE_PASS),
589 PRESET_ALIAS(FAST, HP, NVENC_ONE_PASS),
590 PRESET(LOW_LATENCY_DEFAULT, NVENC_LOWLATENCY),
591 PRESET(LOW_LATENCY_HP, NVENC_LOWLATENCY),
592 PRESET(LOW_LATENCY_HQ, NVENC_LOWLATENCY),
593 PRESET(LOSSLESS_DEFAULT, NVENC_LOSSLESS),
594 PRESET(LOSSLESS_HP, NVENC_LOSSLESS),
597 GUIDTuple *t = &presets[ctx->preset];
599 ctx->init_encode_params.presetGUID = t->guid;
600 ctx->flags = t->flags;
606 static av_cold void set_constqp(AVCodecContext *avctx)
608 NvencContext *ctx = avctx->priv_data;
609 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
611 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
613 if (ctx->init_qp_p >= 0) {
614 rc->constQP.qpInterP = ctx->init_qp_p;
615 if (ctx->init_qp_i >= 0 && ctx->init_qp_b >= 0) {
616 rc->constQP.qpIntra = ctx->init_qp_i;
617 rc->constQP.qpInterB = ctx->init_qp_b;
618 } else if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
619 rc->constQP.qpIntra = av_clip(
620 rc->constQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
621 rc->constQP.qpInterB = av_clip(
622 rc->constQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
624 rc->constQP.qpIntra = rc->constQP.qpInterP;
625 rc->constQP.qpInterB = rc->constQP.qpInterP;
627 } else if (ctx->cqp >= 0) {
628 rc->constQP.qpInterP = rc->constQP.qpInterB = rc->constQP.qpIntra = ctx->cqp;
629 if (avctx->b_quant_factor != 0.0)
630 rc->constQP.qpInterB = av_clip(ctx->cqp * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
631 if (avctx->i_quant_factor != 0.0)
632 rc->constQP.qpIntra = av_clip(ctx->cqp * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
639 static av_cold void set_vbr(AVCodecContext *avctx)
641 NvencContext *ctx = avctx->priv_data;
642 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
645 if (avctx->qmin >= 0 && avctx->qmax >= 0) {
649 rc->minQP.qpInterB = avctx->qmin;
650 rc->minQP.qpInterP = avctx->qmin;
651 rc->minQP.qpIntra = avctx->qmin;
653 rc->maxQP.qpInterB = avctx->qmax;
654 rc->maxQP.qpInterP = avctx->qmax;
655 rc->maxQP.qpIntra = avctx->qmax;
657 qp_inter_p = (avctx->qmax + 3 * avctx->qmin) / 4; // biased towards Qmin
658 } else if (avctx->qmin >= 0) {
661 rc->minQP.qpInterB = avctx->qmin;
662 rc->minQP.qpInterP = avctx->qmin;
663 rc->minQP.qpIntra = avctx->qmin;
665 qp_inter_p = avctx->qmin;
667 qp_inter_p = 26; // default to 26
670 rc->enableInitialRCQP = 1;
672 if (ctx->init_qp_p < 0) {
673 rc->initialRCQP.qpInterP = qp_inter_p;
675 rc->initialRCQP.qpInterP = ctx->init_qp_p;
678 if (ctx->init_qp_i < 0) {
679 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
680 rc->initialRCQP.qpIntra = av_clip(
681 rc->initialRCQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
683 rc->initialRCQP.qpIntra = rc->initialRCQP.qpInterP;
686 rc->initialRCQP.qpIntra = ctx->init_qp_i;
689 if (ctx->init_qp_b < 0) {
690 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
691 rc->initialRCQP.qpInterB = av_clip(
692 rc->initialRCQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
694 rc->initialRCQP.qpInterB = rc->initialRCQP.qpInterP;
697 rc->initialRCQP.qpInterB = ctx->init_qp_b;
701 static av_cold void set_lossless(AVCodecContext *avctx)
703 NvencContext *ctx = avctx->priv_data;
704 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
706 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
707 rc->constQP.qpInterB = 0;
708 rc->constQP.qpInterP = 0;
709 rc->constQP.qpIntra = 0;
715 static void nvenc_override_rate_control(AVCodecContext *avctx)
717 NvencContext *ctx = avctx->priv_data;
718 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
721 case NV_ENC_PARAMS_RC_CONSTQP:
724 case NV_ENC_PARAMS_RC_VBR_MINQP:
725 if (avctx->qmin < 0) {
726 av_log(avctx, AV_LOG_WARNING,
727 "The variable bitrate rate-control requires "
728 "the 'qmin' option set.\n");
733 case NV_ENC_PARAMS_RC_VBR_HQ:
734 case NV_ENC_PARAMS_RC_VBR:
737 case NV_ENC_PARAMS_RC_CBR:
738 case NV_ENC_PARAMS_RC_CBR_HQ:
739 case NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ:
743 rc->rateControlMode = ctx->rc;
746 static av_cold int nvenc_recalc_surfaces(AVCodecContext *avctx)
748 NvencContext *ctx = avctx->priv_data;
749 // default minimum of 4 surfaces
750 // multiply by 2 for number of NVENCs on gpu (hardcode to 2)
751 // another multiply by 2 to avoid blocking next PBB group
752 int nb_surfaces = FFMAX(4, ctx->encode_config.frameIntervalP * 2 * 2);
755 if (ctx->rc_lookahead > 0) {
756 // +1 is to account for lkd_bound calculation later
757 // +4 is to allow sufficient pipelining with lookahead
758 nb_surfaces = FFMAX(1, FFMAX(nb_surfaces, ctx->rc_lookahead + ctx->encode_config.frameIntervalP + 1 + 4));
759 if (nb_surfaces > ctx->nb_surfaces && ctx->nb_surfaces > 0)
761 av_log(avctx, AV_LOG_WARNING,
762 "Defined rc_lookahead requires more surfaces, "
763 "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
765 ctx->nb_surfaces = FFMAX(nb_surfaces, ctx->nb_surfaces);
767 if (ctx->encode_config.frameIntervalP > 1 && ctx->nb_surfaces < nb_surfaces && ctx->nb_surfaces > 0)
769 av_log(avctx, AV_LOG_WARNING,
770 "Defined b-frame requires more surfaces, "
771 "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
772 ctx->nb_surfaces = FFMAX(ctx->nb_surfaces, nb_surfaces);
774 else if (ctx->nb_surfaces <= 0)
775 ctx->nb_surfaces = nb_surfaces;
776 // otherwise use user specified value
779 ctx->nb_surfaces = FFMAX(1, FFMIN(MAX_REGISTERED_FRAMES, ctx->nb_surfaces));
780 ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
785 static av_cold void nvenc_setup_rate_control(AVCodecContext *avctx)
787 NvencContext *ctx = avctx->priv_data;
789 if (avctx->global_quality > 0)
790 av_log(avctx, AV_LOG_WARNING, "Using global_quality with nvenc is deprecated. Use qp instead.\n");
792 if (ctx->cqp < 0 && avctx->global_quality > 0)
793 ctx->cqp = avctx->global_quality;
795 if (avctx->bit_rate > 0) {
796 ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
797 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
798 ctx->encode_config.rcParams.maxBitRate = ctx->encode_config.rcParams.averageBitRate;
801 if (avctx->rc_max_rate > 0)
802 ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
805 if (ctx->flags & NVENC_ONE_PASS)
807 if (ctx->flags & NVENC_TWO_PASSES)
810 if (ctx->twopass < 0)
811 ctx->twopass = (ctx->flags & NVENC_LOWLATENCY) != 0;
815 ctx->rc = NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ;
817 ctx->rc = NV_ENC_PARAMS_RC_CBR;
819 } else if (ctx->cqp >= 0) {
820 ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
821 } else if (ctx->twopass) {
822 ctx->rc = NV_ENC_PARAMS_RC_VBR_HQ;
823 } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
824 ctx->rc = NV_ENC_PARAMS_RC_VBR_MINQP;
828 if (ctx->rc >= 0 && ctx->rc & RC_MODE_DEPRECATED) {
829 av_log(avctx, AV_LOG_WARNING, "Specified rc mode is deprecated.\n");
830 av_log(avctx, AV_LOG_WARNING, "\tll_2pass_quality -> cbr_ld_hq\n");
831 av_log(avctx, AV_LOG_WARNING, "\tll_2pass_size -> cbr_hq\n");
832 av_log(avctx, AV_LOG_WARNING, "\tvbr_2pass -> vbr_hq\n");
833 av_log(avctx, AV_LOG_WARNING, "\tvbr_minqp -> (no replacement)\n");
835 ctx->rc &= ~RC_MODE_DEPRECATED;
838 if (ctx->flags & NVENC_LOSSLESS) {
840 } else if (ctx->rc >= 0) {
841 nvenc_override_rate_control(avctx);
843 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
847 if (avctx->rc_buffer_size > 0) {
848 ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
849 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
850 avctx->rc_buffer_size = ctx->encode_config.rcParams.vbvBufferSize = 2 * ctx->encode_config.rcParams.averageBitRate;
854 ctx->encode_config.rcParams.enableAQ = 1;
855 ctx->encode_config.rcParams.aqStrength = ctx->aq_strength;
856 av_log(avctx, AV_LOG_VERBOSE, "AQ enabled.\n");
859 if (ctx->temporal_aq) {
860 ctx->encode_config.rcParams.enableTemporalAQ = 1;
861 av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ enabled.\n");
864 if (ctx->rc_lookahead > 0) {
865 int lkd_bound = FFMIN(ctx->nb_surfaces, ctx->async_depth) -
866 ctx->encode_config.frameIntervalP - 4;
869 av_log(avctx, AV_LOG_WARNING,
870 "Lookahead not enabled. Increase buffer delay (-delay).\n");
872 ctx->encode_config.rcParams.enableLookahead = 1;
873 ctx->encode_config.rcParams.lookaheadDepth = av_clip(ctx->rc_lookahead, 0, lkd_bound);
874 ctx->encode_config.rcParams.disableIadapt = ctx->no_scenecut;
875 ctx->encode_config.rcParams.disableBadapt = !ctx->b_adapt;
876 av_log(avctx, AV_LOG_VERBOSE,
877 "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",
878 ctx->encode_config.rcParams.lookaheadDepth,
879 ctx->encode_config.rcParams.disableIadapt ? "disabled" : "enabled",
880 ctx->encode_config.rcParams.disableBadapt ? "disabled" : "enabled");
884 if (ctx->strict_gop) {
885 ctx->encode_config.rcParams.strictGOPTarget = 1;
886 av_log(avctx, AV_LOG_VERBOSE, "Strict GOP target enabled.\n");
890 ctx->encode_config.rcParams.enableNonRefP = 1;
892 if (ctx->zerolatency)
893 ctx->encode_config.rcParams.zeroReorderDelay = 1;
897 //convert from float to fixed point 8.8
898 int tmp_quality = (int)(ctx->quality * 256.0f);
899 ctx->encode_config.rcParams.targetQuality = (uint8_t)(tmp_quality >> 8);
900 ctx->encode_config.rcParams.targetQualityLSB = (uint8_t)(tmp_quality & 0xff);
904 static av_cold int nvenc_setup_h264_config(AVCodecContext *avctx)
906 NvencContext *ctx = avctx->priv_data;
907 NV_ENC_CONFIG *cc = &ctx->encode_config;
908 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
909 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
911 vui->colourMatrix = avctx->colorspace;
912 vui->colourPrimaries = avctx->color_primaries;
913 vui->transferCharacteristics = avctx->color_trc;
914 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
915 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
917 vui->colourDescriptionPresentFlag =
918 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
920 vui->videoSignalTypePresentFlag =
921 (vui->colourDescriptionPresentFlag
922 || vui->videoFormat != 5
923 || vui->videoFullRangeFlag != 0);
926 h264->sliceModeData = 1;
928 h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
929 h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
930 h264->outputAUD = ctx->aud;
932 if (avctx->refs >= 0) {
933 /* 0 means "let the hardware decide" */
934 h264->maxNumRefFrames = avctx->refs;
936 if (avctx->gop_size >= 0) {
937 h264->idrPeriod = cc->gopLength;
940 if (IS_CBR(cc->rcParams.rateControlMode)) {
941 h264->outputBufferingPeriodSEI = 1;
944 h264->outputPictureTimingSEI = 1;
946 if (cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ ||
947 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_HQ ||
948 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_VBR_HQ) {
949 h264->adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
950 h264->fmoMode = NV_ENC_H264_FMO_DISABLE;
953 if (ctx->flags & NVENC_LOSSLESS) {
954 h264->qpPrimeYZeroTransformBypassFlag = 1;
956 switch(ctx->profile) {
957 case NV_ENC_H264_PROFILE_BASELINE:
958 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
959 avctx->profile = FF_PROFILE_H264_BASELINE;
961 case NV_ENC_H264_PROFILE_MAIN:
962 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
963 avctx->profile = FF_PROFILE_H264_MAIN;
965 case NV_ENC_H264_PROFILE_HIGH:
966 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
967 avctx->profile = FF_PROFILE_H264_HIGH;
969 case NV_ENC_H264_PROFILE_HIGH_444P:
970 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
971 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
976 // force setting profile as high444p if input is AV_PIX_FMT_YUV444P
977 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P) {
978 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
979 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
982 h264->chromaFormatIDC = avctx->profile == FF_PROFILE_H264_HIGH_444_PREDICTIVE ? 3 : 1;
984 h264->level = ctx->level;
987 h264->entropyCodingMode = ctx->coder;
989 #ifdef NVENC_HAVE_BFRAME_REF_MODE
990 h264->useBFramesAsRef = ctx->b_ref_mode;
996 static av_cold int nvenc_setup_hevc_config(AVCodecContext *avctx)
998 NvencContext *ctx = avctx->priv_data;
999 NV_ENC_CONFIG *cc = &ctx->encode_config;
1000 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
1001 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
1003 vui->colourMatrix = avctx->colorspace;
1004 vui->colourPrimaries = avctx->color_primaries;
1005 vui->transferCharacteristics = avctx->color_trc;
1006 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
1007 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
1009 vui->colourDescriptionPresentFlag =
1010 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
1012 vui->videoSignalTypePresentFlag =
1013 (vui->colourDescriptionPresentFlag
1014 || vui->videoFormat != 5
1015 || vui->videoFullRangeFlag != 0);
1017 hevc->sliceMode = 3;
1018 hevc->sliceModeData = 1;
1020 hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
1021 hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
1022 hevc->outputAUD = ctx->aud;
1024 if (avctx->refs >= 0) {
1025 /* 0 means "let the hardware decide" */
1026 hevc->maxNumRefFramesInDPB = avctx->refs;
1028 if (avctx->gop_size >= 0) {
1029 hevc->idrPeriod = cc->gopLength;
1032 if (IS_CBR(cc->rcParams.rateControlMode)) {
1033 hevc->outputBufferingPeriodSEI = 1;
1036 hevc->outputPictureTimingSEI = 1;
1038 switch (ctx->profile) {
1039 case NV_ENC_HEVC_PROFILE_MAIN:
1040 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
1041 avctx->profile = FF_PROFILE_HEVC_MAIN;
1043 case NV_ENC_HEVC_PROFILE_MAIN_10:
1044 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1045 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
1047 case NV_ENC_HEVC_PROFILE_REXT:
1048 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1049 avctx->profile = FF_PROFILE_HEVC_REXT;
1053 // force setting profile as main10 if input is 10 bit
1054 if (IS_10BIT(ctx->data_pix_fmt)) {
1055 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1056 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
1059 // force setting profile as rext if input is yuv444
1060 if (IS_YUV444(ctx->data_pix_fmt)) {
1061 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1062 avctx->profile = FF_PROFILE_HEVC_REXT;
1065 hevc->chromaFormatIDC = IS_YUV444(ctx->data_pix_fmt) ? 3 : 1;
1067 hevc->pixelBitDepthMinus8 = IS_10BIT(ctx->data_pix_fmt) ? 2 : 0;
1069 hevc->level = ctx->level;
1071 hevc->tier = ctx->tier;
1076 static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx)
1078 switch (avctx->codec->id) {
1079 case AV_CODEC_ID_H264:
1080 return nvenc_setup_h264_config(avctx);
1081 case AV_CODEC_ID_HEVC:
1082 return nvenc_setup_hevc_config(avctx);
1083 /* Earlier switch/case will return if unknown codec is passed. */
1089 static void compute_dar(AVCodecContext *avctx, int *dw, int *dh) {
1095 if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0) {
1096 sw *= avctx->sample_aspect_ratio.num;
1097 sh *= avctx->sample_aspect_ratio.den;
1100 av_reduce(dw, dh, sw, sh, 1024 * 1024);
1103 static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
1105 NvencContext *ctx = avctx->priv_data;
1106 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1107 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1109 NV_ENC_PRESET_CONFIG preset_config = { 0 };
1110 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
1111 AVCPBProperties *cpb_props;
1115 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1116 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
1118 ctx->init_encode_params.encodeHeight = avctx->height;
1119 ctx->init_encode_params.encodeWidth = avctx->width;
1121 ctx->init_encode_params.encodeConfig = &ctx->encode_config;
1123 nvenc_map_preset(ctx);
1125 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
1126 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
1128 nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder,
1129 ctx->init_encode_params.encodeGUID,
1130 ctx->init_encode_params.presetGUID,
1132 if (nv_status != NV_ENC_SUCCESS)
1133 return nvenc_print_error(avctx, nv_status, "Cannot get the preset configuration");
1135 memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
1137 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1139 compute_dar(avctx, &dw, &dh);
1140 ctx->init_encode_params.darHeight = dh;
1141 ctx->init_encode_params.darWidth = dw;
1143 ctx->init_encode_params.frameRateNum = avctx->time_base.den;
1144 ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
1146 ctx->init_encode_params.enableEncodeAsync = 0;
1147 ctx->init_encode_params.enablePTD = 1;
1149 if (ctx->weighted_pred == 1)
1150 ctx->init_encode_params.enableWeightedPrediction = 1;
1152 if (ctx->bluray_compat) {
1154 avctx->refs = FFMIN(FFMAX(avctx->refs, 0), 6);
1155 avctx->max_b_frames = FFMIN(avctx->max_b_frames, 3);
1156 switch (avctx->codec->id) {
1157 case AV_CODEC_ID_H264:
1158 /* maximum level depends on used resolution */
1160 case AV_CODEC_ID_HEVC:
1161 ctx->level = NV_ENC_LEVEL_HEVC_51;
1162 ctx->tier = NV_ENC_TIER_HEVC_HIGH;
1167 if (avctx->gop_size > 0) {
1168 if (avctx->max_b_frames >= 0) {
1169 /* 0 is intra-only, 1 is I/P only, 2 is one B-Frame, 3 two B-frames, and so on. */
1170 ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
1173 ctx->encode_config.gopLength = avctx->gop_size;
1174 } else if (avctx->gop_size == 0) {
1175 ctx->encode_config.frameIntervalP = 0;
1176 ctx->encode_config.gopLength = 1;
1179 ctx->initial_pts[0] = AV_NOPTS_VALUE;
1180 ctx->initial_pts[1] = AV_NOPTS_VALUE;
1182 nvenc_recalc_surfaces(avctx);
1184 nvenc_setup_rate_control(avctx);
1186 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1187 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
1189 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
1192 res = nvenc_setup_codec_config(avctx);
1196 res = nvenc_push_context(avctx);
1200 nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
1202 res = nvenc_pop_context(avctx);
1206 if (nv_status != NV_ENC_SUCCESS) {
1207 return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
1210 if (ctx->encode_config.frameIntervalP > 1)
1211 avctx->has_b_frames = 2;
1213 if (ctx->encode_config.rcParams.averageBitRate > 0)
1214 avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
1216 cpb_props = ff_add_cpb_side_data(avctx);
1218 return AVERROR(ENOMEM);
1219 cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
1220 cpb_props->avg_bitrate = avctx->bit_rate;
1221 cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
1226 static NV_ENC_BUFFER_FORMAT nvenc_map_buffer_format(enum AVPixelFormat pix_fmt)
1229 case AV_PIX_FMT_YUV420P:
1230 return NV_ENC_BUFFER_FORMAT_YV12_PL;
1231 case AV_PIX_FMT_NV12:
1232 return NV_ENC_BUFFER_FORMAT_NV12_PL;
1233 case AV_PIX_FMT_P010:
1234 case AV_PIX_FMT_P016:
1235 return NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1236 case AV_PIX_FMT_YUV444P:
1237 return NV_ENC_BUFFER_FORMAT_YUV444_PL;
1238 case AV_PIX_FMT_YUV444P16:
1239 return NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1240 case AV_PIX_FMT_0RGB32:
1241 return NV_ENC_BUFFER_FORMAT_ARGB;
1242 case AV_PIX_FMT_0BGR32:
1243 return NV_ENC_BUFFER_FORMAT_ABGR;
1245 return NV_ENC_BUFFER_FORMAT_UNDEFINED;
1249 static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
1251 NvencContext *ctx = avctx->priv_data;
1252 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1253 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1254 NvencSurface* tmp_surface = &ctx->surfaces[idx];
1256 NVENCSTATUS nv_status;
1257 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
1258 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1260 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1261 ctx->surfaces[idx].in_ref = av_frame_alloc();
1262 if (!ctx->surfaces[idx].in_ref)
1263 return AVERROR(ENOMEM);
1265 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1267 ctx->surfaces[idx].format = nvenc_map_buffer_format(ctx->data_pix_fmt);
1268 if (ctx->surfaces[idx].format == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1269 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1270 av_get_pix_fmt_name(ctx->data_pix_fmt));
1271 return AVERROR(EINVAL);
1274 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1275 allocSurf.width = avctx->width;
1276 allocSurf.height = avctx->height;
1277 allocSurf.bufferFmt = ctx->surfaces[idx].format;
1279 nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
1280 if (nv_status != NV_ENC_SUCCESS) {
1281 return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
1284 ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
1285 ctx->surfaces[idx].width = allocSurf.width;
1286 ctx->surfaces[idx].height = allocSurf.height;
1289 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
1290 if (nv_status != NV_ENC_SUCCESS) {
1291 int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
1292 if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
1293 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
1294 av_frame_free(&ctx->surfaces[idx].in_ref);
1298 ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1299 ctx->surfaces[idx].size = allocOut.size;
1301 av_fifo_generic_write(ctx->unused_surface_queue, &tmp_surface, sizeof(tmp_surface), NULL);
1306 static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx)
1308 NvencContext *ctx = avctx->priv_data;
1309 int i, res = 0, res2;
1311 ctx->surfaces = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->surfaces));
1313 return AVERROR(ENOMEM);
1315 ctx->timestamp_list = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
1316 if (!ctx->timestamp_list)
1317 return AVERROR(ENOMEM);
1319 ctx->unused_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1320 if (!ctx->unused_surface_queue)
1321 return AVERROR(ENOMEM);
1323 ctx->output_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1324 if (!ctx->output_surface_queue)
1325 return AVERROR(ENOMEM);
1326 ctx->output_surface_ready_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1327 if (!ctx->output_surface_ready_queue)
1328 return AVERROR(ENOMEM);
1330 res = nvenc_push_context(avctx);
1334 for (i = 0; i < ctx->nb_surfaces; i++) {
1335 if ((res = nvenc_alloc_surface(avctx, i)) < 0)
1340 res2 = nvenc_pop_context(avctx);
1347 static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
1349 NvencContext *ctx = avctx->priv_data;
1350 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1351 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1353 NVENCSTATUS nv_status;
1354 uint32_t outSize = 0;
1355 char tmpHeader[256];
1356 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1357 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1359 payload.spsppsBuffer = tmpHeader;
1360 payload.inBufferSize = sizeof(tmpHeader);
1361 payload.outSPSPPSPayloadSize = &outSize;
1363 nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
1364 if (nv_status != NV_ENC_SUCCESS) {
1365 return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
1368 avctx->extradata_size = outSize;
1369 avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
1371 if (!avctx->extradata) {
1372 return AVERROR(ENOMEM);
1375 memcpy(avctx->extradata, tmpHeader, outSize);
1380 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
1382 NvencContext *ctx = avctx->priv_data;
1383 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1384 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1387 /* the encoder has to be flushed before it can be closed */
1388 if (ctx->nvencoder) {
1389 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
1390 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
1392 res = nvenc_push_context(avctx);
1396 p_nvenc->nvEncEncodePicture(ctx->nvencoder, ¶ms);
1399 av_fifo_freep(&ctx->timestamp_list);
1400 av_fifo_freep(&ctx->output_surface_ready_queue);
1401 av_fifo_freep(&ctx->output_surface_queue);
1402 av_fifo_freep(&ctx->unused_surface_queue);
1404 if (ctx->surfaces && (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11)) {
1405 for (i = 0; i < ctx->nb_registered_frames; i++) {
1406 if (ctx->registered_frames[i].mapped)
1407 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[i].in_map.mappedResource);
1408 if (ctx->registered_frames[i].regptr)
1409 p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1411 ctx->nb_registered_frames = 0;
1414 if (ctx->surfaces) {
1415 for (i = 0; i < ctx->nb_surfaces; ++i) {
1416 if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
1417 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
1418 av_frame_free(&ctx->surfaces[i].in_ref);
1419 p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
1422 av_freep(&ctx->surfaces);
1423 ctx->nb_surfaces = 0;
1425 if (ctx->nvencoder) {
1426 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1428 res = nvenc_pop_context(avctx);
1432 ctx->nvencoder = NULL;
1434 if (ctx->cu_context_internal)
1435 CHECK_CU(dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal));
1436 ctx->cu_context = ctx->cu_context_internal = NULL;
1439 if (ctx->d3d11_device) {
1440 ID3D11Device_Release(ctx->d3d11_device);
1441 ctx->d3d11_device = NULL;
1445 nvenc_free_functions(&dl_fn->nvenc_dl);
1446 cuda_free_functions(&dl_fn->cuda_dl);
1448 dl_fn->nvenc_device_count = 0;
1450 av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
1455 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
1457 NvencContext *ctx = avctx->priv_data;
1460 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1461 AVHWFramesContext *frames_ctx;
1462 if (!avctx->hw_frames_ctx) {
1463 av_log(avctx, AV_LOG_ERROR,
1464 "hw_frames_ctx must be set when using GPU frames as input\n");
1465 return AVERROR(EINVAL);
1467 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1468 if (frames_ctx->format != avctx->pix_fmt) {
1469 av_log(avctx, AV_LOG_ERROR,
1470 "hw_frames_ctx must match the GPU frame type\n");
1471 return AVERROR(EINVAL);
1473 ctx->data_pix_fmt = frames_ctx->sw_format;
1475 ctx->data_pix_fmt = avctx->pix_fmt;
1478 if ((ret = nvenc_load_libraries(avctx)) < 0)
1481 if ((ret = nvenc_setup_device(avctx)) < 0)
1484 if ((ret = nvenc_setup_encoder(avctx)) < 0)
1487 if ((ret = nvenc_setup_surfaces(avctx)) < 0)
1490 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1491 if ((ret = nvenc_setup_extradata(avctx)) < 0)
1498 static NvencSurface *get_free_frame(NvencContext *ctx)
1500 NvencSurface *tmp_surf;
1502 if (!(av_fifo_size(ctx->unused_surface_queue) > 0))
1506 av_fifo_generic_read(ctx->unused_surface_queue, &tmp_surf, sizeof(tmp_surf), NULL);
1510 static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *nv_surface,
1511 NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params, const AVFrame *frame)
1513 int dst_linesize[4] = {
1514 lock_buffer_params->pitch,
1515 lock_buffer_params->pitch,
1516 lock_buffer_params->pitch,
1517 lock_buffer_params->pitch
1519 uint8_t *dst_data[4];
1522 if (frame->format == AV_PIX_FMT_YUV420P)
1523 dst_linesize[1] = dst_linesize[2] >>= 1;
1525 ret = av_image_fill_pointers(dst_data, frame->format, nv_surface->height,
1526 lock_buffer_params->bufferDataPtr, dst_linesize);
1530 if (frame->format == AV_PIX_FMT_YUV420P)
1531 FFSWAP(uint8_t*, dst_data[1], dst_data[2]);
1533 av_image_copy(dst_data, dst_linesize,
1534 (const uint8_t**)frame->data, frame->linesize, frame->format,
1535 avctx->width, avctx->height);
1540 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1542 NvencContext *ctx = avctx->priv_data;
1543 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1544 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1545 NVENCSTATUS nv_status;
1549 if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1550 for (i = 0; i < ctx->nb_registered_frames; i++) {
1551 if (!ctx->registered_frames[i].mapped) {
1552 if (ctx->registered_frames[i].regptr) {
1553 nv_status = p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1554 if (nv_status != NV_ENC_SUCCESS)
1555 return nvenc_print_error(avctx, nv_status, "Failed unregistering unused input resource");
1556 ctx->registered_frames[i].ptr = NULL;
1557 ctx->registered_frames[i].regptr = NULL;
1563 return ctx->nb_registered_frames++;
1566 av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1567 return AVERROR(ENOMEM);
1570 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1572 NvencContext *ctx = avctx->priv_data;
1573 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1574 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1576 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frame->hw_frames_ctx->data;
1577 NV_ENC_REGISTER_RESOURCE reg;
1580 for (i = 0; i < ctx->nb_registered_frames; i++) {
1581 if (avctx->pix_fmt == AV_PIX_FMT_CUDA && ctx->registered_frames[i].ptr == frame->data[0])
1583 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])
1587 idx = nvenc_find_free_reg_resource(avctx);
1591 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1592 reg.width = frames_ctx->width;
1593 reg.height = frames_ctx->height;
1594 reg.pitch = frame->linesize[0];
1595 reg.resourceToRegister = frame->data[0];
1597 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1598 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1600 else if (avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1601 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX;
1602 reg.subResourceIndex = (intptr_t)frame->data[1];
1605 reg.bufferFormat = nvenc_map_buffer_format(frames_ctx->sw_format);
1606 if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1607 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1608 av_get_pix_fmt_name(frames_ctx->sw_format));
1609 return AVERROR(EINVAL);
1612 ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, ®);
1613 if (ret != NV_ENC_SUCCESS) {
1614 nvenc_print_error(avctx, ret, "Error registering an input resource");
1615 return AVERROR_UNKNOWN;
1618 ctx->registered_frames[idx].ptr = frame->data[0];
1619 ctx->registered_frames[idx].ptr_index = reg.subResourceIndex;
1620 ctx->registered_frames[idx].regptr = reg.registeredResource;
1624 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1625 NvencSurface *nvenc_frame)
1627 NvencContext *ctx = avctx->priv_data;
1628 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1629 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1632 NVENCSTATUS nv_status;
1634 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1635 int reg_idx = nvenc_register_frame(avctx, frame);
1637 av_log(avctx, AV_LOG_ERROR, "Could not register an input HW frame\n");
1641 res = av_frame_ref(nvenc_frame->in_ref, frame);
1645 if (!ctx->registered_frames[reg_idx].mapped) {
1646 ctx->registered_frames[reg_idx].in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1647 ctx->registered_frames[reg_idx].in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1648 nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &ctx->registered_frames[reg_idx].in_map);
1649 if (nv_status != NV_ENC_SUCCESS) {
1650 av_frame_unref(nvenc_frame->in_ref);
1651 return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
1655 ctx->registered_frames[reg_idx].mapped += 1;
1657 nvenc_frame->reg_idx = reg_idx;
1658 nvenc_frame->input_surface = ctx->registered_frames[reg_idx].in_map.mappedResource;
1659 nvenc_frame->format = ctx->registered_frames[reg_idx].in_map.mappedBufferFmt;
1660 nvenc_frame->pitch = frame->linesize[0];
1664 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1666 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1667 lockBufferParams.inputBuffer = nvenc_frame->input_surface;
1669 nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
1670 if (nv_status != NV_ENC_SUCCESS) {
1671 return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
1674 nvenc_frame->pitch = lockBufferParams.pitch;
1675 res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
1677 nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
1678 if (nv_status != NV_ENC_SUCCESS) {
1679 return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
1686 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1687 NV_ENC_PIC_PARAMS *params,
1688 NV_ENC_SEI_PAYLOAD *sei_data)
1690 NvencContext *ctx = avctx->priv_data;
1692 switch (avctx->codec->id) {
1693 case AV_CODEC_ID_H264:
1694 params->codecPicParams.h264PicParams.sliceMode =
1695 ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1696 params->codecPicParams.h264PicParams.sliceModeData =
1697 ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1699 params->codecPicParams.h264PicParams.seiPayloadArray = sei_data;
1700 params->codecPicParams.h264PicParams.seiPayloadArrayCnt = 1;
1704 case AV_CODEC_ID_HEVC:
1705 params->codecPicParams.hevcPicParams.sliceMode =
1706 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1707 params->codecPicParams.hevcPicParams.sliceModeData =
1708 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1710 params->codecPicParams.hevcPicParams.seiPayloadArray = sei_data;
1711 params->codecPicParams.hevcPicParams.seiPayloadArrayCnt = 1;
1718 static inline void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
1720 av_fifo_generic_write(queue, ×tamp, sizeof(timestamp), NULL);
1723 static inline int64_t timestamp_queue_dequeue(AVFifoBuffer* queue)
1725 int64_t timestamp = AV_NOPTS_VALUE;
1726 if (av_fifo_size(queue) > 0)
1727 av_fifo_generic_read(queue, ×tamp, sizeof(timestamp), NULL);
1732 static int nvenc_set_timestamp(AVCodecContext *avctx,
1733 NV_ENC_LOCK_BITSTREAM *params,
1736 NvencContext *ctx = avctx->priv_data;
1738 pkt->pts = params->outputTimeStamp;
1740 /* generate the first dts by linearly extrapolating the
1741 * first two pts values to the past */
1742 if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
1743 ctx->initial_pts[1] != AV_NOPTS_VALUE) {
1744 int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
1747 if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
1748 (ts0 > 0 && ts1 < INT64_MIN + ts0))
1749 return AVERROR(ERANGE);
1752 if ((delta < 0 && ts0 > INT64_MAX + delta) ||
1753 (delta > 0 && ts0 < INT64_MIN + delta))
1754 return AVERROR(ERANGE);
1755 pkt->dts = ts0 - delta;
1757 ctx->first_packet_output = 1;
1761 pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
1766 static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
1768 NvencContext *ctx = avctx->priv_data;
1769 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1770 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1772 uint32_t slice_mode_data;
1773 uint32_t *slice_offsets = NULL;
1774 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1775 NVENCSTATUS nv_status;
1778 enum AVPictureType pict_type;
1780 switch (avctx->codec->id) {
1781 case AV_CODEC_ID_H264:
1782 slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1784 case AV_CODEC_ID_H265:
1785 slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1788 av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
1789 res = AVERROR(EINVAL);
1792 slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
1794 if (!slice_offsets) {
1795 res = AVERROR(ENOMEM);
1799 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1801 lock_params.doNotWait = 0;
1802 lock_params.outputBitstream = tmpoutsurf->output_surface;
1803 lock_params.sliceOffsets = slice_offsets;
1805 nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
1806 if (nv_status != NV_ENC_SUCCESS) {
1807 res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
1811 if (res = ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes,0)) {
1812 p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1816 memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1818 nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1819 if (nv_status != NV_ENC_SUCCESS) {
1820 res = nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
1825 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1826 ctx->registered_frames[tmpoutsurf->reg_idx].mapped -= 1;
1827 if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped == 0) {
1828 nv_status = p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[tmpoutsurf->reg_idx].in_map.mappedResource);
1829 if (nv_status != NV_ENC_SUCCESS) {
1830 res = nvenc_print_error(avctx, nv_status, "Failed unmapping input resource");
1833 nv_status = p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[tmpoutsurf->reg_idx].regptr);
1834 if (nv_status != NV_ENC_SUCCESS) {
1835 res = nvenc_print_error(avctx, nv_status, "Failed unregistering input resource");
1838 ctx->registered_frames[tmpoutsurf->reg_idx].ptr = NULL;
1839 ctx->registered_frames[tmpoutsurf->reg_idx].regptr = NULL;
1840 } else if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped < 0) {
1845 av_frame_unref(tmpoutsurf->in_ref);
1847 tmpoutsurf->input_surface = NULL;
1850 switch (lock_params.pictureType) {
1851 case NV_ENC_PIC_TYPE_IDR:
1852 pkt->flags |= AV_PKT_FLAG_KEY;
1853 case NV_ENC_PIC_TYPE_I:
1854 pict_type = AV_PICTURE_TYPE_I;
1856 case NV_ENC_PIC_TYPE_P:
1857 pict_type = AV_PICTURE_TYPE_P;
1859 case NV_ENC_PIC_TYPE_B:
1860 pict_type = AV_PICTURE_TYPE_B;
1862 case NV_ENC_PIC_TYPE_BI:
1863 pict_type = AV_PICTURE_TYPE_BI;
1866 av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
1867 av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
1868 res = AVERROR_EXTERNAL;
1872 #if FF_API_CODED_FRAME
1873 FF_DISABLE_DEPRECATION_WARNINGS
1874 avctx->coded_frame->pict_type = pict_type;
1875 FF_ENABLE_DEPRECATION_WARNINGS
1878 ff_side_data_set_encoder_stats(pkt,
1879 (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
1881 res = nvenc_set_timestamp(avctx, &lock_params, pkt);
1885 av_free(slice_offsets);
1890 timestamp_queue_dequeue(ctx->timestamp_list);
1893 av_free(slice_offsets);
1898 static int output_ready(AVCodecContext *avctx, int flush)
1900 NvencContext *ctx = avctx->priv_data;
1901 int nb_ready, nb_pending;
1903 /* when B-frames are enabled, we wait for two initial timestamps to
1904 * calculate the first dts */
1905 if (!flush && avctx->max_b_frames > 0 &&
1906 (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
1909 nb_ready = av_fifo_size(ctx->output_surface_ready_queue) / sizeof(NvencSurface*);
1910 nb_pending = av_fifo_size(ctx->output_surface_queue) / sizeof(NvencSurface*);
1912 return nb_ready > 0;
1913 return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
1916 static void reconfig_encoder(AVCodecContext *avctx, const AVFrame *frame)
1918 NvencContext *ctx = avctx->priv_data;
1919 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
1922 NV_ENC_RECONFIGURE_PARAMS params = { 0 };
1923 int needs_reconfig = 0;
1924 int needs_encode_config = 0;
1925 int reconfig_bitrate = 0, reconfig_dar = 0;
1928 params.version = NV_ENC_RECONFIGURE_PARAMS_VER;
1929 params.reInitEncodeParams = ctx->init_encode_params;
1931 compute_dar(avctx, &dw, &dh);
1932 if (dw != ctx->init_encode_params.darWidth || dh != ctx->init_encode_params.darHeight) {
1933 av_log(avctx, AV_LOG_VERBOSE,
1934 "aspect ratio change (DAR): %d:%d -> %d:%d\n",
1935 ctx->init_encode_params.darWidth,
1936 ctx->init_encode_params.darHeight, dw, dh);
1938 params.reInitEncodeParams.darHeight = dh;
1939 params.reInitEncodeParams.darWidth = dw;
1945 if (ctx->rc != NV_ENC_PARAMS_RC_CONSTQP && ctx->support_dyn_bitrate) {
1946 if (avctx->bit_rate > 0 && params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate != avctx->bit_rate) {
1947 av_log(avctx, AV_LOG_VERBOSE,
1948 "avg bitrate change: %d -> %d\n",
1949 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate,
1950 (uint32_t)avctx->bit_rate);
1952 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate = avctx->bit_rate;
1953 reconfig_bitrate = 1;
1956 if (avctx->rc_max_rate > 0 && ctx->encode_config.rcParams.maxBitRate != avctx->rc_max_rate) {
1957 av_log(avctx, AV_LOG_VERBOSE,
1958 "max bitrate change: %d -> %d\n",
1959 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate,
1960 (uint32_t)avctx->rc_max_rate);
1962 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate = avctx->rc_max_rate;
1963 reconfig_bitrate = 1;
1966 if (avctx->rc_buffer_size > 0 && ctx->encode_config.rcParams.vbvBufferSize != avctx->rc_buffer_size) {
1967 av_log(avctx, AV_LOG_VERBOSE,
1968 "vbv buffer size change: %d -> %d\n",
1969 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize,
1970 avctx->rc_buffer_size);
1972 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize = avctx->rc_buffer_size;
1973 reconfig_bitrate = 1;
1976 if (reconfig_bitrate) {
1977 params.resetEncoder = 1;
1978 params.forceIDR = 1;
1980 needs_encode_config = 1;
1985 if (!needs_encode_config)
1986 params.reInitEncodeParams.encodeConfig = NULL;
1988 if (needs_reconfig) {
1989 ret = p_nvenc->nvEncReconfigureEncoder(ctx->nvencoder, ¶ms);
1990 if (ret != NV_ENC_SUCCESS) {
1991 nvenc_print_error(avctx, ret, "failed to reconfigure nvenc");
1994 ctx->init_encode_params.darHeight = dh;
1995 ctx->init_encode_params.darWidth = dw;
1998 if (reconfig_bitrate) {
1999 ctx->encode_config.rcParams.averageBitRate = params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate;
2000 ctx->encode_config.rcParams.maxBitRate = params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate;
2001 ctx->encode_config.rcParams.vbvBufferSize = params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize;
2008 int ff_nvenc_send_frame(AVCodecContext *avctx, const AVFrame *frame)
2010 NVENCSTATUS nv_status;
2011 NvencSurface *tmp_out_surf, *in_surf;
2013 NV_ENC_SEI_PAYLOAD *sei_data = NULL;
2016 NvencContext *ctx = avctx->priv_data;
2017 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
2018 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
2020 NV_ENC_PIC_PARAMS pic_params = { 0 };
2021 pic_params.version = NV_ENC_PIC_PARAMS_VER;
2023 if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
2024 return AVERROR(EINVAL);
2026 if (ctx->encoder_flushing) {
2027 if (avctx->internal->draining)
2030 ctx->encoder_flushing = 0;
2031 ctx->first_packet_output = 0;
2032 ctx->initial_pts[0] = AV_NOPTS_VALUE;
2033 ctx->initial_pts[1] = AV_NOPTS_VALUE;
2034 av_fifo_reset(ctx->timestamp_list);
2038 in_surf = get_free_frame(ctx);
2040 return AVERROR(EAGAIN);
2042 res = nvenc_push_context(avctx);
2046 reconfig_encoder(avctx, frame);
2048 res = nvenc_upload_frame(avctx, frame, in_surf);
2050 res2 = nvenc_pop_context(avctx);
2057 pic_params.inputBuffer = in_surf->input_surface;
2058 pic_params.bufferFmt = in_surf->format;
2059 pic_params.inputWidth = in_surf->width;
2060 pic_params.inputHeight = in_surf->height;
2061 pic_params.inputPitch = in_surf->pitch;
2062 pic_params.outputBitstream = in_surf->output_surface;
2064 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
2065 if (frame->top_field_first)
2066 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
2068 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
2070 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
2073 if (ctx->forced_idr >= 0 && frame->pict_type == AV_PICTURE_TYPE_I) {
2074 pic_params.encodePicFlags =
2075 ctx->forced_idr ? NV_ENC_PIC_FLAG_FORCEIDR : NV_ENC_PIC_FLAG_FORCEINTRA;
2077 pic_params.encodePicFlags = 0;
2080 pic_params.inputTimeStamp = frame->pts;
2082 if (ctx->a53_cc && av_frame_get_side_data(frame, AV_FRAME_DATA_A53_CC)) {
2083 if (ff_alloc_a53_sei(frame, sizeof(NV_ENC_SEI_PAYLOAD), (void**)&sei_data, &sei_size) < 0) {
2084 av_log(ctx, AV_LOG_ERROR, "Not enough memory for closed captions, skipping\n");
2088 sei_data->payloadSize = (uint32_t)sei_size;
2089 sei_data->payloadType = 4;
2090 sei_data->payload = (uint8_t*)(sei_data + 1);
2094 nvenc_codec_specific_pic_params(avctx, &pic_params, sei_data);
2096 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
2097 ctx->encoder_flushing = 1;
2100 res = nvenc_push_context(avctx);
2104 nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
2107 res = nvenc_pop_context(avctx);
2111 if (nv_status != NV_ENC_SUCCESS &&
2112 nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
2113 return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
2116 av_fifo_generic_write(ctx->output_surface_queue, &in_surf, sizeof(in_surf), NULL);
2117 timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
2119 if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
2120 ctx->initial_pts[0] = frame->pts;
2121 else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
2122 ctx->initial_pts[1] = frame->pts;
2125 /* all the pending buffers are now ready for output */
2126 if (nv_status == NV_ENC_SUCCESS) {
2127 while (av_fifo_size(ctx->output_surface_queue) > 0) {
2128 av_fifo_generic_read(ctx->output_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2129 av_fifo_generic_write(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2136 int ff_nvenc_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
2138 NvencSurface *tmp_out_surf;
2141 NvencContext *ctx = avctx->priv_data;
2143 if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
2144 return AVERROR(EINVAL);
2146 if (output_ready(avctx, ctx->encoder_flushing)) {
2147 av_fifo_generic_read(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2149 res = nvenc_push_context(avctx);
2153 res = process_output_surface(avctx, pkt, tmp_out_surf);
2155 res2 = nvenc_pop_context(avctx);
2162 av_fifo_generic_write(ctx->unused_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2163 } else if (ctx->encoder_flushing) {
2166 return AVERROR(EAGAIN);
2172 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
2173 const AVFrame *frame, int *got_packet)
2175 NvencContext *ctx = avctx->priv_data;
2178 if (!ctx->encoder_flushing) {
2179 res = ff_nvenc_send_frame(avctx, frame);
2184 res = ff_nvenc_receive_packet(avctx, pkt);
2185 if (res == AVERROR(EAGAIN) || res == AVERROR_EOF) {
2187 } else if (res < 0) {