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;
1073 #ifdef NVENC_HAVE_HEVC_BFRAME_REF_MODE
1074 hevc->useBFramesAsRef = ctx->b_ref_mode;
1080 static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx)
1082 switch (avctx->codec->id) {
1083 case AV_CODEC_ID_H264:
1084 return nvenc_setup_h264_config(avctx);
1085 case AV_CODEC_ID_HEVC:
1086 return nvenc_setup_hevc_config(avctx);
1087 /* Earlier switch/case will return if unknown codec is passed. */
1093 static void compute_dar(AVCodecContext *avctx, int *dw, int *dh) {
1099 if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0) {
1100 sw *= avctx->sample_aspect_ratio.num;
1101 sh *= avctx->sample_aspect_ratio.den;
1104 av_reduce(dw, dh, sw, sh, 1024 * 1024);
1107 static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
1109 NvencContext *ctx = avctx->priv_data;
1110 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1111 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1113 NV_ENC_PRESET_CONFIG preset_config = { 0 };
1114 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
1115 AVCPBProperties *cpb_props;
1119 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1120 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
1122 ctx->init_encode_params.encodeHeight = avctx->height;
1123 ctx->init_encode_params.encodeWidth = avctx->width;
1125 ctx->init_encode_params.encodeConfig = &ctx->encode_config;
1127 nvenc_map_preset(ctx);
1129 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
1130 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
1132 nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder,
1133 ctx->init_encode_params.encodeGUID,
1134 ctx->init_encode_params.presetGUID,
1136 if (nv_status != NV_ENC_SUCCESS)
1137 return nvenc_print_error(avctx, nv_status, "Cannot get the preset configuration");
1139 memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
1141 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1143 compute_dar(avctx, &dw, &dh);
1144 ctx->init_encode_params.darHeight = dh;
1145 ctx->init_encode_params.darWidth = dw;
1147 ctx->init_encode_params.frameRateNum = avctx->time_base.den;
1148 ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
1150 ctx->init_encode_params.enableEncodeAsync = 0;
1151 ctx->init_encode_params.enablePTD = 1;
1153 if (ctx->weighted_pred == 1)
1154 ctx->init_encode_params.enableWeightedPrediction = 1;
1156 if (ctx->bluray_compat) {
1158 avctx->refs = FFMIN(FFMAX(avctx->refs, 0), 6);
1159 avctx->max_b_frames = FFMIN(avctx->max_b_frames, 3);
1160 switch (avctx->codec->id) {
1161 case AV_CODEC_ID_H264:
1162 /* maximum level depends on used resolution */
1164 case AV_CODEC_ID_HEVC:
1165 ctx->level = NV_ENC_LEVEL_HEVC_51;
1166 ctx->tier = NV_ENC_TIER_HEVC_HIGH;
1171 if (avctx->gop_size > 0) {
1172 if (avctx->max_b_frames >= 0) {
1173 /* 0 is intra-only, 1 is I/P only, 2 is one B-Frame, 3 two B-frames, and so on. */
1174 ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
1177 ctx->encode_config.gopLength = avctx->gop_size;
1178 } else if (avctx->gop_size == 0) {
1179 ctx->encode_config.frameIntervalP = 0;
1180 ctx->encode_config.gopLength = 1;
1183 ctx->initial_pts[0] = AV_NOPTS_VALUE;
1184 ctx->initial_pts[1] = AV_NOPTS_VALUE;
1186 nvenc_recalc_surfaces(avctx);
1188 nvenc_setup_rate_control(avctx);
1190 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1191 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
1193 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
1196 res = nvenc_setup_codec_config(avctx);
1200 res = nvenc_push_context(avctx);
1204 nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
1206 res = nvenc_pop_context(avctx);
1210 if (nv_status != NV_ENC_SUCCESS) {
1211 return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
1214 if (ctx->encode_config.frameIntervalP > 1)
1215 avctx->has_b_frames = 2;
1217 if (ctx->encode_config.rcParams.averageBitRate > 0)
1218 avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
1220 cpb_props = ff_add_cpb_side_data(avctx);
1222 return AVERROR(ENOMEM);
1223 cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
1224 cpb_props->avg_bitrate = avctx->bit_rate;
1225 cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
1230 static NV_ENC_BUFFER_FORMAT nvenc_map_buffer_format(enum AVPixelFormat pix_fmt)
1233 case AV_PIX_FMT_YUV420P:
1234 return NV_ENC_BUFFER_FORMAT_YV12_PL;
1235 case AV_PIX_FMT_NV12:
1236 return NV_ENC_BUFFER_FORMAT_NV12_PL;
1237 case AV_PIX_FMT_P010:
1238 case AV_PIX_FMT_P016:
1239 return NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1240 case AV_PIX_FMT_YUV444P:
1241 return NV_ENC_BUFFER_FORMAT_YUV444_PL;
1242 case AV_PIX_FMT_YUV444P16:
1243 return NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1244 case AV_PIX_FMT_0RGB32:
1245 return NV_ENC_BUFFER_FORMAT_ARGB;
1246 case AV_PIX_FMT_0BGR32:
1247 return NV_ENC_BUFFER_FORMAT_ABGR;
1249 return NV_ENC_BUFFER_FORMAT_UNDEFINED;
1253 static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
1255 NvencContext *ctx = avctx->priv_data;
1256 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1257 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1258 NvencSurface* tmp_surface = &ctx->surfaces[idx];
1260 NVENCSTATUS nv_status;
1261 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
1262 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1264 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1265 ctx->surfaces[idx].in_ref = av_frame_alloc();
1266 if (!ctx->surfaces[idx].in_ref)
1267 return AVERROR(ENOMEM);
1269 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1271 ctx->surfaces[idx].format = nvenc_map_buffer_format(ctx->data_pix_fmt);
1272 if (ctx->surfaces[idx].format == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1273 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1274 av_get_pix_fmt_name(ctx->data_pix_fmt));
1275 return AVERROR(EINVAL);
1278 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1279 allocSurf.width = avctx->width;
1280 allocSurf.height = avctx->height;
1281 allocSurf.bufferFmt = ctx->surfaces[idx].format;
1283 nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
1284 if (nv_status != NV_ENC_SUCCESS) {
1285 return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
1288 ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
1289 ctx->surfaces[idx].width = allocSurf.width;
1290 ctx->surfaces[idx].height = allocSurf.height;
1293 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
1294 if (nv_status != NV_ENC_SUCCESS) {
1295 int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
1296 if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
1297 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
1298 av_frame_free(&ctx->surfaces[idx].in_ref);
1302 ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1303 ctx->surfaces[idx].size = allocOut.size;
1305 av_fifo_generic_write(ctx->unused_surface_queue, &tmp_surface, sizeof(tmp_surface), NULL);
1310 static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx)
1312 NvencContext *ctx = avctx->priv_data;
1313 int i, res = 0, res2;
1315 ctx->surfaces = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->surfaces));
1317 return AVERROR(ENOMEM);
1319 ctx->timestamp_list = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
1320 if (!ctx->timestamp_list)
1321 return AVERROR(ENOMEM);
1323 ctx->unused_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1324 if (!ctx->unused_surface_queue)
1325 return AVERROR(ENOMEM);
1327 ctx->output_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1328 if (!ctx->output_surface_queue)
1329 return AVERROR(ENOMEM);
1330 ctx->output_surface_ready_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1331 if (!ctx->output_surface_ready_queue)
1332 return AVERROR(ENOMEM);
1334 res = nvenc_push_context(avctx);
1338 for (i = 0; i < ctx->nb_surfaces; i++) {
1339 if ((res = nvenc_alloc_surface(avctx, i)) < 0)
1344 res2 = nvenc_pop_context(avctx);
1351 static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
1353 NvencContext *ctx = avctx->priv_data;
1354 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1355 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1357 NVENCSTATUS nv_status;
1358 uint32_t outSize = 0;
1359 char tmpHeader[256];
1360 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1361 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1363 payload.spsppsBuffer = tmpHeader;
1364 payload.inBufferSize = sizeof(tmpHeader);
1365 payload.outSPSPPSPayloadSize = &outSize;
1367 nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
1368 if (nv_status != NV_ENC_SUCCESS) {
1369 return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
1372 avctx->extradata_size = outSize;
1373 avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
1375 if (!avctx->extradata) {
1376 return AVERROR(ENOMEM);
1379 memcpy(avctx->extradata, tmpHeader, outSize);
1384 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
1386 NvencContext *ctx = avctx->priv_data;
1387 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1388 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1391 /* the encoder has to be flushed before it can be closed */
1392 if (ctx->nvencoder) {
1393 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
1394 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
1396 res = nvenc_push_context(avctx);
1400 p_nvenc->nvEncEncodePicture(ctx->nvencoder, ¶ms);
1403 av_fifo_freep(&ctx->timestamp_list);
1404 av_fifo_freep(&ctx->output_surface_ready_queue);
1405 av_fifo_freep(&ctx->output_surface_queue);
1406 av_fifo_freep(&ctx->unused_surface_queue);
1408 if (ctx->surfaces && (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11)) {
1409 for (i = 0; i < ctx->nb_registered_frames; i++) {
1410 if (ctx->registered_frames[i].mapped)
1411 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[i].in_map.mappedResource);
1412 if (ctx->registered_frames[i].regptr)
1413 p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1415 ctx->nb_registered_frames = 0;
1418 if (ctx->surfaces) {
1419 for (i = 0; i < ctx->nb_surfaces; ++i) {
1420 if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
1421 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
1422 av_frame_free(&ctx->surfaces[i].in_ref);
1423 p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
1426 av_freep(&ctx->surfaces);
1427 ctx->nb_surfaces = 0;
1429 if (ctx->nvencoder) {
1430 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1432 res = nvenc_pop_context(avctx);
1436 ctx->nvencoder = NULL;
1438 if (ctx->cu_context_internal)
1439 CHECK_CU(dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal));
1440 ctx->cu_context = ctx->cu_context_internal = NULL;
1443 if (ctx->d3d11_device) {
1444 ID3D11Device_Release(ctx->d3d11_device);
1445 ctx->d3d11_device = NULL;
1449 nvenc_free_functions(&dl_fn->nvenc_dl);
1450 cuda_free_functions(&dl_fn->cuda_dl);
1452 dl_fn->nvenc_device_count = 0;
1454 av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
1459 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
1461 NvencContext *ctx = avctx->priv_data;
1464 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1465 AVHWFramesContext *frames_ctx;
1466 if (!avctx->hw_frames_ctx) {
1467 av_log(avctx, AV_LOG_ERROR,
1468 "hw_frames_ctx must be set when using GPU frames as input\n");
1469 return AVERROR(EINVAL);
1471 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1472 if (frames_ctx->format != avctx->pix_fmt) {
1473 av_log(avctx, AV_LOG_ERROR,
1474 "hw_frames_ctx must match the GPU frame type\n");
1475 return AVERROR(EINVAL);
1477 ctx->data_pix_fmt = frames_ctx->sw_format;
1479 ctx->data_pix_fmt = avctx->pix_fmt;
1482 if ((ret = nvenc_load_libraries(avctx)) < 0)
1485 if ((ret = nvenc_setup_device(avctx)) < 0)
1488 if ((ret = nvenc_setup_encoder(avctx)) < 0)
1491 if ((ret = nvenc_setup_surfaces(avctx)) < 0)
1494 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1495 if ((ret = nvenc_setup_extradata(avctx)) < 0)
1502 static NvencSurface *get_free_frame(NvencContext *ctx)
1504 NvencSurface *tmp_surf;
1506 if (!(av_fifo_size(ctx->unused_surface_queue) > 0))
1510 av_fifo_generic_read(ctx->unused_surface_queue, &tmp_surf, sizeof(tmp_surf), NULL);
1514 static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *nv_surface,
1515 NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params, const AVFrame *frame)
1517 int dst_linesize[4] = {
1518 lock_buffer_params->pitch,
1519 lock_buffer_params->pitch,
1520 lock_buffer_params->pitch,
1521 lock_buffer_params->pitch
1523 uint8_t *dst_data[4];
1526 if (frame->format == AV_PIX_FMT_YUV420P)
1527 dst_linesize[1] = dst_linesize[2] >>= 1;
1529 ret = av_image_fill_pointers(dst_data, frame->format, nv_surface->height,
1530 lock_buffer_params->bufferDataPtr, dst_linesize);
1534 if (frame->format == AV_PIX_FMT_YUV420P)
1535 FFSWAP(uint8_t*, dst_data[1], dst_data[2]);
1537 av_image_copy(dst_data, dst_linesize,
1538 (const uint8_t**)frame->data, frame->linesize, frame->format,
1539 avctx->width, avctx->height);
1544 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1546 NvencContext *ctx = avctx->priv_data;
1547 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1548 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1549 NVENCSTATUS nv_status;
1553 if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1554 for (i = 0; i < ctx->nb_registered_frames; i++) {
1555 if (!ctx->registered_frames[i].mapped) {
1556 if (ctx->registered_frames[i].regptr) {
1557 nv_status = p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1558 if (nv_status != NV_ENC_SUCCESS)
1559 return nvenc_print_error(avctx, nv_status, "Failed unregistering unused input resource");
1560 ctx->registered_frames[i].ptr = NULL;
1561 ctx->registered_frames[i].regptr = NULL;
1567 return ctx->nb_registered_frames++;
1570 av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1571 return AVERROR(ENOMEM);
1574 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1576 NvencContext *ctx = avctx->priv_data;
1577 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1578 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1580 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frame->hw_frames_ctx->data;
1581 NV_ENC_REGISTER_RESOURCE reg;
1584 for (i = 0; i < ctx->nb_registered_frames; i++) {
1585 if (avctx->pix_fmt == AV_PIX_FMT_CUDA && ctx->registered_frames[i].ptr == frame->data[0])
1587 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])
1591 idx = nvenc_find_free_reg_resource(avctx);
1595 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1596 reg.width = frames_ctx->width;
1597 reg.height = frames_ctx->height;
1598 reg.pitch = frame->linesize[0];
1599 reg.resourceToRegister = frame->data[0];
1601 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1602 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1604 else if (avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1605 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX;
1606 reg.subResourceIndex = (intptr_t)frame->data[1];
1609 reg.bufferFormat = nvenc_map_buffer_format(frames_ctx->sw_format);
1610 if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1611 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1612 av_get_pix_fmt_name(frames_ctx->sw_format));
1613 return AVERROR(EINVAL);
1616 ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, ®);
1617 if (ret != NV_ENC_SUCCESS) {
1618 nvenc_print_error(avctx, ret, "Error registering an input resource");
1619 return AVERROR_UNKNOWN;
1622 ctx->registered_frames[idx].ptr = frame->data[0];
1623 ctx->registered_frames[idx].ptr_index = reg.subResourceIndex;
1624 ctx->registered_frames[idx].regptr = reg.registeredResource;
1628 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1629 NvencSurface *nvenc_frame)
1631 NvencContext *ctx = avctx->priv_data;
1632 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1633 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1636 NVENCSTATUS nv_status;
1638 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1639 int reg_idx = nvenc_register_frame(avctx, frame);
1641 av_log(avctx, AV_LOG_ERROR, "Could not register an input HW frame\n");
1645 res = av_frame_ref(nvenc_frame->in_ref, frame);
1649 if (!ctx->registered_frames[reg_idx].mapped) {
1650 ctx->registered_frames[reg_idx].in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1651 ctx->registered_frames[reg_idx].in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1652 nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &ctx->registered_frames[reg_idx].in_map);
1653 if (nv_status != NV_ENC_SUCCESS) {
1654 av_frame_unref(nvenc_frame->in_ref);
1655 return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
1659 ctx->registered_frames[reg_idx].mapped += 1;
1661 nvenc_frame->reg_idx = reg_idx;
1662 nvenc_frame->input_surface = ctx->registered_frames[reg_idx].in_map.mappedResource;
1663 nvenc_frame->format = ctx->registered_frames[reg_idx].in_map.mappedBufferFmt;
1664 nvenc_frame->pitch = frame->linesize[0];
1668 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1670 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1671 lockBufferParams.inputBuffer = nvenc_frame->input_surface;
1673 nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
1674 if (nv_status != NV_ENC_SUCCESS) {
1675 return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
1678 nvenc_frame->pitch = lockBufferParams.pitch;
1679 res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
1681 nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
1682 if (nv_status != NV_ENC_SUCCESS) {
1683 return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
1690 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1691 NV_ENC_PIC_PARAMS *params,
1692 NV_ENC_SEI_PAYLOAD *sei_data)
1694 NvencContext *ctx = avctx->priv_data;
1696 switch (avctx->codec->id) {
1697 case AV_CODEC_ID_H264:
1698 params->codecPicParams.h264PicParams.sliceMode =
1699 ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1700 params->codecPicParams.h264PicParams.sliceModeData =
1701 ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1703 params->codecPicParams.h264PicParams.seiPayloadArray = sei_data;
1704 params->codecPicParams.h264PicParams.seiPayloadArrayCnt = 1;
1708 case AV_CODEC_ID_HEVC:
1709 params->codecPicParams.hevcPicParams.sliceMode =
1710 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1711 params->codecPicParams.hevcPicParams.sliceModeData =
1712 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1714 params->codecPicParams.hevcPicParams.seiPayloadArray = sei_data;
1715 params->codecPicParams.hevcPicParams.seiPayloadArrayCnt = 1;
1722 static inline void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
1724 av_fifo_generic_write(queue, ×tamp, sizeof(timestamp), NULL);
1727 static inline int64_t timestamp_queue_dequeue(AVFifoBuffer* queue)
1729 int64_t timestamp = AV_NOPTS_VALUE;
1730 if (av_fifo_size(queue) > 0)
1731 av_fifo_generic_read(queue, ×tamp, sizeof(timestamp), NULL);
1736 static int nvenc_set_timestamp(AVCodecContext *avctx,
1737 NV_ENC_LOCK_BITSTREAM *params,
1740 NvencContext *ctx = avctx->priv_data;
1742 pkt->pts = params->outputTimeStamp;
1744 /* generate the first dts by linearly extrapolating the
1745 * first two pts values to the past */
1746 if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
1747 ctx->initial_pts[1] != AV_NOPTS_VALUE) {
1748 int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
1751 if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
1752 (ts0 > 0 && ts1 < INT64_MIN + ts0))
1753 return AVERROR(ERANGE);
1756 if ((delta < 0 && ts0 > INT64_MAX + delta) ||
1757 (delta > 0 && ts0 < INT64_MIN + delta))
1758 return AVERROR(ERANGE);
1759 pkt->dts = ts0 - delta;
1761 ctx->first_packet_output = 1;
1765 pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
1770 static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
1772 NvencContext *ctx = avctx->priv_data;
1773 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1774 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1776 uint32_t slice_mode_data;
1777 uint32_t *slice_offsets = NULL;
1778 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1779 NVENCSTATUS nv_status;
1782 enum AVPictureType pict_type;
1784 switch (avctx->codec->id) {
1785 case AV_CODEC_ID_H264:
1786 slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1788 case AV_CODEC_ID_H265:
1789 slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1792 av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
1793 res = AVERROR(EINVAL);
1796 slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
1798 if (!slice_offsets) {
1799 res = AVERROR(ENOMEM);
1803 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1805 lock_params.doNotWait = 0;
1806 lock_params.outputBitstream = tmpoutsurf->output_surface;
1807 lock_params.sliceOffsets = slice_offsets;
1809 nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
1810 if (nv_status != NV_ENC_SUCCESS) {
1811 res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
1815 if (res = ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes,0)) {
1816 p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1820 memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1822 nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1823 if (nv_status != NV_ENC_SUCCESS) {
1824 res = nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
1829 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1830 ctx->registered_frames[tmpoutsurf->reg_idx].mapped -= 1;
1831 if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped == 0) {
1832 nv_status = p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[tmpoutsurf->reg_idx].in_map.mappedResource);
1833 if (nv_status != NV_ENC_SUCCESS) {
1834 res = nvenc_print_error(avctx, nv_status, "Failed unmapping input resource");
1837 nv_status = p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[tmpoutsurf->reg_idx].regptr);
1838 if (nv_status != NV_ENC_SUCCESS) {
1839 res = nvenc_print_error(avctx, nv_status, "Failed unregistering input resource");
1842 ctx->registered_frames[tmpoutsurf->reg_idx].ptr = NULL;
1843 ctx->registered_frames[tmpoutsurf->reg_idx].regptr = NULL;
1844 } else if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped < 0) {
1849 av_frame_unref(tmpoutsurf->in_ref);
1851 tmpoutsurf->input_surface = NULL;
1854 switch (lock_params.pictureType) {
1855 case NV_ENC_PIC_TYPE_IDR:
1856 pkt->flags |= AV_PKT_FLAG_KEY;
1857 case NV_ENC_PIC_TYPE_I:
1858 pict_type = AV_PICTURE_TYPE_I;
1860 case NV_ENC_PIC_TYPE_P:
1861 pict_type = AV_PICTURE_TYPE_P;
1863 case NV_ENC_PIC_TYPE_B:
1864 pict_type = AV_PICTURE_TYPE_B;
1866 case NV_ENC_PIC_TYPE_BI:
1867 pict_type = AV_PICTURE_TYPE_BI;
1870 av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
1871 av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
1872 res = AVERROR_EXTERNAL;
1876 #if FF_API_CODED_FRAME
1877 FF_DISABLE_DEPRECATION_WARNINGS
1878 avctx->coded_frame->pict_type = pict_type;
1879 FF_ENABLE_DEPRECATION_WARNINGS
1882 ff_side_data_set_encoder_stats(pkt,
1883 (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
1885 res = nvenc_set_timestamp(avctx, &lock_params, pkt);
1889 av_free(slice_offsets);
1894 timestamp_queue_dequeue(ctx->timestamp_list);
1897 av_free(slice_offsets);
1902 static int output_ready(AVCodecContext *avctx, int flush)
1904 NvencContext *ctx = avctx->priv_data;
1905 int nb_ready, nb_pending;
1907 /* when B-frames are enabled, we wait for two initial timestamps to
1908 * calculate the first dts */
1909 if (!flush && avctx->max_b_frames > 0 &&
1910 (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
1913 nb_ready = av_fifo_size(ctx->output_surface_ready_queue) / sizeof(NvencSurface*);
1914 nb_pending = av_fifo_size(ctx->output_surface_queue) / sizeof(NvencSurface*);
1916 return nb_ready > 0;
1917 return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
1920 static void reconfig_encoder(AVCodecContext *avctx, const AVFrame *frame)
1922 NvencContext *ctx = avctx->priv_data;
1923 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
1926 NV_ENC_RECONFIGURE_PARAMS params = { 0 };
1927 int needs_reconfig = 0;
1928 int needs_encode_config = 0;
1929 int reconfig_bitrate = 0, reconfig_dar = 0;
1932 params.version = NV_ENC_RECONFIGURE_PARAMS_VER;
1933 params.reInitEncodeParams = ctx->init_encode_params;
1935 compute_dar(avctx, &dw, &dh);
1936 if (dw != ctx->init_encode_params.darWidth || dh != ctx->init_encode_params.darHeight) {
1937 av_log(avctx, AV_LOG_VERBOSE,
1938 "aspect ratio change (DAR): %d:%d -> %d:%d\n",
1939 ctx->init_encode_params.darWidth,
1940 ctx->init_encode_params.darHeight, dw, dh);
1942 params.reInitEncodeParams.darHeight = dh;
1943 params.reInitEncodeParams.darWidth = dw;
1949 if (ctx->rc != NV_ENC_PARAMS_RC_CONSTQP && ctx->support_dyn_bitrate) {
1950 if (avctx->bit_rate > 0 && params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate != avctx->bit_rate) {
1951 av_log(avctx, AV_LOG_VERBOSE,
1952 "avg bitrate change: %d -> %d\n",
1953 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate,
1954 (uint32_t)avctx->bit_rate);
1956 params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate = avctx->bit_rate;
1957 reconfig_bitrate = 1;
1960 if (avctx->rc_max_rate > 0 && ctx->encode_config.rcParams.maxBitRate != avctx->rc_max_rate) {
1961 av_log(avctx, AV_LOG_VERBOSE,
1962 "max bitrate change: %d -> %d\n",
1963 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate,
1964 (uint32_t)avctx->rc_max_rate);
1966 params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate = avctx->rc_max_rate;
1967 reconfig_bitrate = 1;
1970 if (avctx->rc_buffer_size > 0 && ctx->encode_config.rcParams.vbvBufferSize != avctx->rc_buffer_size) {
1971 av_log(avctx, AV_LOG_VERBOSE,
1972 "vbv buffer size change: %d -> %d\n",
1973 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize,
1974 avctx->rc_buffer_size);
1976 params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize = avctx->rc_buffer_size;
1977 reconfig_bitrate = 1;
1980 if (reconfig_bitrate) {
1981 params.resetEncoder = 1;
1982 params.forceIDR = 1;
1984 needs_encode_config = 1;
1989 if (!needs_encode_config)
1990 params.reInitEncodeParams.encodeConfig = NULL;
1992 if (needs_reconfig) {
1993 ret = p_nvenc->nvEncReconfigureEncoder(ctx->nvencoder, ¶ms);
1994 if (ret != NV_ENC_SUCCESS) {
1995 nvenc_print_error(avctx, ret, "failed to reconfigure nvenc");
1998 ctx->init_encode_params.darHeight = dh;
1999 ctx->init_encode_params.darWidth = dw;
2002 if (reconfig_bitrate) {
2003 ctx->encode_config.rcParams.averageBitRate = params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate;
2004 ctx->encode_config.rcParams.maxBitRate = params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate;
2005 ctx->encode_config.rcParams.vbvBufferSize = params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize;
2012 int ff_nvenc_send_frame(AVCodecContext *avctx, const AVFrame *frame)
2014 NVENCSTATUS nv_status;
2015 NvencSurface *tmp_out_surf, *in_surf;
2017 NV_ENC_SEI_PAYLOAD *sei_data = NULL;
2020 NvencContext *ctx = avctx->priv_data;
2021 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
2022 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
2024 NV_ENC_PIC_PARAMS pic_params = { 0 };
2025 pic_params.version = NV_ENC_PIC_PARAMS_VER;
2027 if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
2028 return AVERROR(EINVAL);
2030 if (ctx->encoder_flushing) {
2031 if (avctx->internal->draining)
2034 ctx->encoder_flushing = 0;
2035 ctx->first_packet_output = 0;
2036 ctx->initial_pts[0] = AV_NOPTS_VALUE;
2037 ctx->initial_pts[1] = AV_NOPTS_VALUE;
2038 av_fifo_reset(ctx->timestamp_list);
2042 in_surf = get_free_frame(ctx);
2044 return AVERROR(EAGAIN);
2046 res = nvenc_push_context(avctx);
2050 reconfig_encoder(avctx, frame);
2052 res = nvenc_upload_frame(avctx, frame, in_surf);
2054 res2 = nvenc_pop_context(avctx);
2061 pic_params.inputBuffer = in_surf->input_surface;
2062 pic_params.bufferFmt = in_surf->format;
2063 pic_params.inputWidth = in_surf->width;
2064 pic_params.inputHeight = in_surf->height;
2065 pic_params.inputPitch = in_surf->pitch;
2066 pic_params.outputBitstream = in_surf->output_surface;
2068 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
2069 if (frame->top_field_first)
2070 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
2072 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
2074 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
2077 if (ctx->forced_idr >= 0 && frame->pict_type == AV_PICTURE_TYPE_I) {
2078 pic_params.encodePicFlags =
2079 ctx->forced_idr ? NV_ENC_PIC_FLAG_FORCEIDR : NV_ENC_PIC_FLAG_FORCEINTRA;
2081 pic_params.encodePicFlags = 0;
2084 pic_params.inputTimeStamp = frame->pts;
2086 if (ctx->a53_cc && av_frame_get_side_data(frame, AV_FRAME_DATA_A53_CC)) {
2087 if (ff_alloc_a53_sei(frame, sizeof(NV_ENC_SEI_PAYLOAD), (void**)&sei_data, &sei_size) < 0) {
2088 av_log(ctx, AV_LOG_ERROR, "Not enough memory for closed captions, skipping\n");
2092 sei_data->payloadSize = (uint32_t)sei_size;
2093 sei_data->payloadType = 4;
2094 sei_data->payload = (uint8_t*)(sei_data + 1);
2098 nvenc_codec_specific_pic_params(avctx, &pic_params, sei_data);
2100 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
2101 ctx->encoder_flushing = 1;
2104 res = nvenc_push_context(avctx);
2108 nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
2111 res = nvenc_pop_context(avctx);
2115 if (nv_status != NV_ENC_SUCCESS &&
2116 nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
2117 return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
2120 av_fifo_generic_write(ctx->output_surface_queue, &in_surf, sizeof(in_surf), NULL);
2121 timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
2123 if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
2124 ctx->initial_pts[0] = frame->pts;
2125 else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
2126 ctx->initial_pts[1] = frame->pts;
2129 /* all the pending buffers are now ready for output */
2130 if (nv_status == NV_ENC_SUCCESS) {
2131 while (av_fifo_size(ctx->output_surface_queue) > 0) {
2132 av_fifo_generic_read(ctx->output_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2133 av_fifo_generic_write(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2140 int ff_nvenc_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
2142 NvencSurface *tmp_out_surf;
2145 NvencContext *ctx = avctx->priv_data;
2147 if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
2148 return AVERROR(EINVAL);
2150 if (output_ready(avctx, ctx->encoder_flushing)) {
2151 av_fifo_generic_read(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2153 res = nvenc_push_context(avctx);
2157 res = process_output_surface(avctx, pkt, tmp_out_surf);
2159 res2 = nvenc_pop_context(avctx);
2166 av_fifo_generic_write(ctx->unused_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2167 } else if (ctx->encoder_flushing) {
2170 return AVERROR(EAGAIN);
2176 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
2177 const AVFrame *frame, int *got_packet)
2179 NvencContext *ctx = avctx->priv_data;
2182 if (!ctx->encoder_flushing) {
2183 res = ff_nvenc_send_frame(avctx, frame);
2188 res = ff_nvenc_receive_packet(avctx, pkt);
2189 if (res == AVERROR(EAGAIN) || res == AVERROR_EOF) {
2191 } else if (res < 0) {