2 * H.264/HEVC hardware encoding using nvidia nvenc
3 * Copyright (c) 2016 Timo Rothenpieler <timo@rothenpieler.org>
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 #include "libavutil/hwcontext_cuda.h"
27 #include "libavutil/hwcontext.h"
28 #include "libavutil/imgutils.h"
29 #include "libavutil/avassert.h"
30 #include "libavutil/mem.h"
31 #include "libavutil/pixdesc.h"
34 #define NVENC_CAP 0x30
35 #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR || \
36 rc == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ || \
37 rc == NV_ENC_PARAMS_RC_CBR_HQ)
39 const enum AVPixelFormat ff_nvenc_pix_fmts[] = {
44 AV_PIX_FMT_P016, // Truncated to 10bits
45 AV_PIX_FMT_YUV444P16, // Truncated to 10bits
55 #define IS_10BIT(pix_fmt) (pix_fmt == AV_PIX_FMT_P010 || \
56 pix_fmt == AV_PIX_FMT_P016 || \
57 pix_fmt == AV_PIX_FMT_YUV444P16)
59 #define IS_YUV444(pix_fmt) (pix_fmt == AV_PIX_FMT_YUV444P || \
60 pix_fmt == AV_PIX_FMT_YUV444P16)
67 { NV_ENC_SUCCESS, 0, "success" },
68 { NV_ENC_ERR_NO_ENCODE_DEVICE, AVERROR(ENOENT), "no encode device" },
69 { NV_ENC_ERR_UNSUPPORTED_DEVICE, AVERROR(ENOSYS), "unsupported device" },
70 { NV_ENC_ERR_INVALID_ENCODERDEVICE, AVERROR(EINVAL), "invalid encoder device" },
71 { NV_ENC_ERR_INVALID_DEVICE, AVERROR(EINVAL), "invalid device" },
72 { NV_ENC_ERR_DEVICE_NOT_EXIST, AVERROR(EIO), "device does not exist" },
73 { NV_ENC_ERR_INVALID_PTR, AVERROR(EFAULT), "invalid ptr" },
74 { NV_ENC_ERR_INVALID_EVENT, AVERROR(EINVAL), "invalid event" },
75 { NV_ENC_ERR_INVALID_PARAM, AVERROR(EINVAL), "invalid param" },
76 { NV_ENC_ERR_INVALID_CALL, AVERROR(EINVAL), "invalid call" },
77 { NV_ENC_ERR_OUT_OF_MEMORY, AVERROR(ENOMEM), "out of memory" },
78 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED, AVERROR(EINVAL), "encoder not initialized" },
79 { NV_ENC_ERR_UNSUPPORTED_PARAM, AVERROR(ENOSYS), "unsupported param" },
80 { NV_ENC_ERR_LOCK_BUSY, AVERROR(EAGAIN), "lock busy" },
81 { NV_ENC_ERR_NOT_ENOUGH_BUFFER, AVERROR_BUFFER_TOO_SMALL, "not enough buffer"},
82 { NV_ENC_ERR_INVALID_VERSION, AVERROR(EINVAL), "invalid version" },
83 { NV_ENC_ERR_MAP_FAILED, AVERROR(EIO), "map failed" },
84 { NV_ENC_ERR_NEED_MORE_INPUT, AVERROR(EAGAIN), "need more input" },
85 { NV_ENC_ERR_ENCODER_BUSY, AVERROR(EAGAIN), "encoder busy" },
86 { NV_ENC_ERR_EVENT_NOT_REGISTERD, AVERROR(EBADF), "event not registered" },
87 { NV_ENC_ERR_GENERIC, AVERROR_UNKNOWN, "generic error" },
88 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY, AVERROR(EINVAL), "incompatible client key" },
89 { NV_ENC_ERR_UNIMPLEMENTED, AVERROR(ENOSYS), "unimplemented" },
90 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO), "resource register failed" },
91 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED, AVERROR(EBADF), "resource not registered" },
92 { NV_ENC_ERR_RESOURCE_NOT_MAPPED, AVERROR(EBADF), "resource not mapped" },
95 static int nvenc_map_error(NVENCSTATUS err, const char **desc)
98 for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
99 if (nvenc_errors[i].nverr == err) {
101 *desc = nvenc_errors[i].desc;
102 return nvenc_errors[i].averr;
106 *desc = "unknown error";
107 return AVERROR_UNKNOWN;
110 static int nvenc_print_error(void *log_ctx, NVENCSTATUS err,
111 const char *error_string)
115 ret = nvenc_map_error(err, &desc);
116 av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
120 static void nvenc_print_driver_requirement(AVCodecContext *avctx, int level)
122 #if defined(_WIN32) || defined(__CYGWIN__)
123 const char *minver = "378.66";
125 const char *minver = "378.13";
127 av_log(avctx, level, "The minimum required Nvidia driver for nvenc is %s or newer\n", minver);
130 static av_cold int nvenc_load_libraries(AVCodecContext *avctx)
132 NvencContext *ctx = avctx->priv_data;
133 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
135 uint32_t nvenc_max_ver;
138 ret = cuda_load_functions(&dl_fn->cuda_dl, avctx);
142 ret = nvenc_load_functions(&dl_fn->nvenc_dl, avctx);
144 nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
148 err = dl_fn->nvenc_dl->NvEncodeAPIGetMaxSupportedVersion(&nvenc_max_ver);
149 if (err != NV_ENC_SUCCESS)
150 return nvenc_print_error(avctx, err, "Failed to query nvenc max version");
152 av_log(avctx, AV_LOG_VERBOSE, "Loaded Nvenc version %d.%d\n", nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
154 if ((NVENCAPI_MAJOR_VERSION << 4 | NVENCAPI_MINOR_VERSION) > nvenc_max_ver) {
155 av_log(avctx, AV_LOG_ERROR, "Driver does not support the required nvenc API version. "
156 "Required: %d.%d Found: %d.%d\n",
157 NVENCAPI_MAJOR_VERSION, NVENCAPI_MINOR_VERSION,
158 nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
159 nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
160 return AVERROR(ENOSYS);
163 dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
165 err = dl_fn->nvenc_dl->NvEncodeAPICreateInstance(&dl_fn->nvenc_funcs);
166 if (err != NV_ENC_SUCCESS)
167 return nvenc_print_error(avctx, err, "Failed to create nvenc instance");
169 av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
174 static int nvenc_push_context(AVCodecContext *avctx)
176 NvencContext *ctx = avctx->priv_data;
177 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
180 if (ctx->d3d11_device)
183 cu_res = dl_fn->cuda_dl->cuCtxPushCurrent(ctx->cu_context);
184 if (cu_res != CUDA_SUCCESS) {
185 av_log(avctx, AV_LOG_ERROR, "cuCtxPushCurrent failed\n");
186 return AVERROR_EXTERNAL;
192 static int nvenc_pop_context(AVCodecContext *avctx)
194 NvencContext *ctx = avctx->priv_data;
195 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
199 if (ctx->d3d11_device)
202 cu_res = dl_fn->cuda_dl->cuCtxPopCurrent(&dummy);
203 if (cu_res != CUDA_SUCCESS) {
204 av_log(avctx, AV_LOG_ERROR, "cuCtxPopCurrent failed\n");
205 return AVERROR_EXTERNAL;
211 static av_cold int nvenc_open_session(AVCodecContext *avctx)
213 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
214 NvencContext *ctx = avctx->priv_data;
215 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
218 params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
219 params.apiVersion = NVENCAPI_VERSION;
220 if (ctx->d3d11_device) {
221 params.device = ctx->d3d11_device;
222 params.deviceType = NV_ENC_DEVICE_TYPE_DIRECTX;
224 params.device = ctx->cu_context;
225 params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
228 ret = p_nvenc->nvEncOpenEncodeSessionEx(¶ms, &ctx->nvencoder);
229 if (ret != NV_ENC_SUCCESS) {
230 ctx->nvencoder = NULL;
231 return nvenc_print_error(avctx, ret, "OpenEncodeSessionEx failed");
237 static int nvenc_check_codec_support(AVCodecContext *avctx)
239 NvencContext *ctx = avctx->priv_data;
240 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
241 int i, ret, count = 0;
244 ret = p_nvenc->nvEncGetEncodeGUIDCount(ctx->nvencoder, &count);
246 if (ret != NV_ENC_SUCCESS || !count)
247 return AVERROR(ENOSYS);
249 guids = av_malloc(count * sizeof(GUID));
251 return AVERROR(ENOMEM);
253 ret = p_nvenc->nvEncGetEncodeGUIDs(ctx->nvencoder, guids, count, &count);
254 if (ret != NV_ENC_SUCCESS) {
255 ret = AVERROR(ENOSYS);
259 ret = AVERROR(ENOSYS);
260 for (i = 0; i < count; i++) {
261 if (!memcmp(&guids[i], &ctx->init_encode_params.encodeGUID, sizeof(*guids))) {
273 static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
275 NvencContext *ctx = avctx->priv_data;
276 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
277 NV_ENC_CAPS_PARAM params = { 0 };
280 params.version = NV_ENC_CAPS_PARAM_VER;
281 params.capsToQuery = cap;
283 ret = p_nvenc->nvEncGetEncodeCaps(ctx->nvencoder, ctx->init_encode_params.encodeGUID, ¶ms, &val);
285 if (ret == NV_ENC_SUCCESS)
290 static int nvenc_check_capabilities(AVCodecContext *avctx)
292 NvencContext *ctx = avctx->priv_data;
295 ret = nvenc_check_codec_support(avctx);
297 av_log(avctx, AV_LOG_VERBOSE, "Codec not supported\n");
301 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
302 if (IS_YUV444(ctx->data_pix_fmt) && ret <= 0) {
303 av_log(avctx, AV_LOG_VERBOSE, "YUV444P not supported\n");
304 return AVERROR(ENOSYS);
307 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOSSLESS_ENCODE);
308 if (ctx->preset >= PRESET_LOSSLESS_DEFAULT && ret <= 0) {
309 av_log(avctx, AV_LOG_VERBOSE, "Lossless encoding not supported\n");
310 return AVERROR(ENOSYS);
313 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
314 if (ret < avctx->width) {
315 av_log(avctx, AV_LOG_VERBOSE, "Width %d exceeds %d\n",
317 return AVERROR(ENOSYS);
320 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
321 if (ret < avctx->height) {
322 av_log(avctx, AV_LOG_VERBOSE, "Height %d exceeds %d\n",
324 return AVERROR(ENOSYS);
327 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
328 if (ret < avctx->max_b_frames) {
329 av_log(avctx, AV_LOG_VERBOSE, "Max B-frames %d exceed %d\n",
330 avctx->max_b_frames, ret);
332 return AVERROR(ENOSYS);
335 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_FIELD_ENCODING);
336 if (ret < 1 && avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
337 av_log(avctx, AV_LOG_VERBOSE,
338 "Interlaced encoding is not supported. Supported level: %d\n",
340 return AVERROR(ENOSYS);
343 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_10BIT_ENCODE);
344 if (IS_10BIT(ctx->data_pix_fmt) && ret <= 0) {
345 av_log(avctx, AV_LOG_VERBOSE, "10 bit encode not supported\n");
346 return AVERROR(ENOSYS);
349 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOOKAHEAD);
350 if (ctx->rc_lookahead > 0 && ret <= 0) {
351 av_log(avctx, AV_LOG_VERBOSE, "RC lookahead not supported\n");
352 return AVERROR(ENOSYS);
355 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_TEMPORAL_AQ);
356 if (ctx->temporal_aq > 0 && ret <= 0) {
357 av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ not supported\n");
358 return AVERROR(ENOSYS);
361 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_WEIGHTED_PREDICTION);
362 if (ctx->weighted_pred > 0 && ret <= 0) {
363 av_log (avctx, AV_LOG_VERBOSE, "Weighted Prediction not supported\n");
364 return AVERROR(ENOSYS);
367 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_CABAC);
368 if (ctx->coder == NV_ENC_H264_ENTROPY_CODING_MODE_CABAC && ret <= 0) {
369 av_log(avctx, AV_LOG_VERBOSE, "CABAC entropy coding not supported\n");
370 return AVERROR(ENOSYS);
376 static av_cold int nvenc_check_device(AVCodecContext *avctx, int idx)
378 NvencContext *ctx = avctx->priv_data;
379 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
380 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
381 char name[128] = { 0};
382 int major, minor, ret;
385 int loglevel = AV_LOG_VERBOSE;
387 if (ctx->device == LIST_DEVICES)
388 loglevel = AV_LOG_INFO;
390 cu_res = dl_fn->cuda_dl->cuDeviceGet(&cu_device, idx);
391 if (cu_res != CUDA_SUCCESS) {
392 av_log(avctx, AV_LOG_ERROR,
393 "Cannot access the CUDA device %d\n",
398 cu_res = dl_fn->cuda_dl->cuDeviceGetName(name, sizeof(name), cu_device);
399 if (cu_res != CUDA_SUCCESS) {
400 av_log(avctx, AV_LOG_ERROR, "cuDeviceGetName failed on device %d\n", idx);
404 cu_res = dl_fn->cuda_dl->cuDeviceComputeCapability(&major, &minor, cu_device);
405 if (cu_res != CUDA_SUCCESS) {
406 av_log(avctx, AV_LOG_ERROR, "cuDeviceComputeCapability failed on device %d\n", idx);
410 av_log(avctx, loglevel, "[ GPU #%d - < %s > has Compute SM %d.%d ]\n", idx, name, major, minor);
411 if (((major << 4) | minor) < NVENC_CAP) {
412 av_log(avctx, loglevel, "does not support NVENC\n");
416 if (ctx->device != idx && ctx->device != ANY_DEVICE)
419 cu_res = dl_fn->cuda_dl->cuCtxCreate(&ctx->cu_context_internal, 0, cu_device);
420 if (cu_res != CUDA_SUCCESS) {
421 av_log(avctx, AV_LOG_FATAL, "Failed creating CUDA context for NVENC: 0x%x\n", (int)cu_res);
425 ctx->cu_context = ctx->cu_context_internal;
427 if ((ret = nvenc_pop_context(avctx)) < 0)
430 if ((ret = nvenc_open_session(avctx)) < 0)
433 if ((ret = nvenc_check_capabilities(avctx)) < 0)
436 av_log(avctx, loglevel, "supports NVENC\n");
438 dl_fn->nvenc_device_count++;
440 if (ctx->device == idx || ctx->device == ANY_DEVICE)
444 if ((ret = nvenc_push_context(avctx)) < 0)
447 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
448 ctx->nvencoder = NULL;
450 if ((ret = nvenc_pop_context(avctx)) < 0)
454 dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal);
455 ctx->cu_context_internal = NULL;
458 return AVERROR(ENOSYS);
461 static av_cold int nvenc_setup_device(AVCodecContext *avctx)
463 NvencContext *ctx = avctx->priv_data;
464 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
466 switch (avctx->codec->id) {
467 case AV_CODEC_ID_H264:
468 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
470 case AV_CODEC_ID_HEVC:
471 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
477 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11 || avctx->hw_frames_ctx || avctx->hw_device_ctx) {
478 AVHWFramesContext *frames_ctx;
479 AVHWDeviceContext *hwdev_ctx;
480 AVCUDADeviceContext *cuda_device_hwctx = NULL;
482 AVD3D11VADeviceContext *d3d11_device_hwctx = NULL;
486 if (avctx->hw_frames_ctx) {
487 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
488 if (frames_ctx->format == AV_PIX_FMT_CUDA)
489 cuda_device_hwctx = frames_ctx->device_ctx->hwctx;
491 else if (frames_ctx->format == AV_PIX_FMT_D3D11)
492 d3d11_device_hwctx = frames_ctx->device_ctx->hwctx;
495 return AVERROR(EINVAL);
496 } else if (avctx->hw_device_ctx) {
497 hwdev_ctx = (AVHWDeviceContext*)avctx->hw_device_ctx->data;
498 if (hwdev_ctx->type == AV_HWDEVICE_TYPE_CUDA)
499 cuda_device_hwctx = hwdev_ctx->hwctx;
501 else if (hwdev_ctx->type == AV_HWDEVICE_TYPE_D3D11VA)
502 d3d11_device_hwctx = hwdev_ctx->hwctx;
505 return AVERROR(EINVAL);
507 return AVERROR(EINVAL);
510 if (cuda_device_hwctx) {
511 ctx->cu_context = cuda_device_hwctx->cuda_ctx;
514 else if (d3d11_device_hwctx) {
515 ctx->d3d11_device = d3d11_device_hwctx->device;
516 ID3D11Device_AddRef(ctx->d3d11_device);
520 ret = nvenc_open_session(avctx);
524 ret = nvenc_check_capabilities(avctx);
526 av_log(avctx, AV_LOG_FATAL, "Provided device doesn't support required NVENC features\n");
530 int i, nb_devices = 0;
532 if ((dl_fn->cuda_dl->cuInit(0)) != CUDA_SUCCESS) {
533 av_log(avctx, AV_LOG_ERROR,
534 "Cannot init CUDA\n");
535 return AVERROR_UNKNOWN;
538 if ((dl_fn->cuda_dl->cuDeviceGetCount(&nb_devices)) != CUDA_SUCCESS) {
539 av_log(avctx, AV_LOG_ERROR,
540 "Cannot enumerate the CUDA devices\n");
541 return AVERROR_UNKNOWN;
545 av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
546 return AVERROR_EXTERNAL;
549 av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", nb_devices);
551 dl_fn->nvenc_device_count = 0;
552 for (i = 0; i < nb_devices; ++i) {
553 if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
557 if (ctx->device == LIST_DEVICES)
560 if (!dl_fn->nvenc_device_count) {
561 av_log(avctx, AV_LOG_FATAL, "No NVENC capable devices found\n");
562 return AVERROR_EXTERNAL;
565 av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->device, nb_devices);
566 return AVERROR(EINVAL);
572 typedef struct GUIDTuple {
577 #define PRESET_ALIAS(alias, name, ...) \
578 [PRESET_ ## alias] = { NV_ENC_PRESET_ ## name ## _GUID, __VA_ARGS__ }
580 #define PRESET(name, ...) PRESET_ALIAS(name, name, __VA_ARGS__)
582 static void nvenc_map_preset(NvencContext *ctx)
584 GUIDTuple presets[] = {
589 PRESET_ALIAS(SLOW, HQ, NVENC_TWO_PASSES),
590 PRESET_ALIAS(MEDIUM, HQ, NVENC_ONE_PASS),
591 PRESET_ALIAS(FAST, HP, NVENC_ONE_PASS),
592 PRESET(LOW_LATENCY_DEFAULT, NVENC_LOWLATENCY),
593 PRESET(LOW_LATENCY_HP, NVENC_LOWLATENCY),
594 PRESET(LOW_LATENCY_HQ, NVENC_LOWLATENCY),
595 PRESET(LOSSLESS_DEFAULT, NVENC_LOSSLESS),
596 PRESET(LOSSLESS_HP, NVENC_LOSSLESS),
599 GUIDTuple *t = &presets[ctx->preset];
601 ctx->init_encode_params.presetGUID = t->guid;
602 ctx->flags = t->flags;
608 static av_cold void set_constqp(AVCodecContext *avctx)
610 NvencContext *ctx = avctx->priv_data;
611 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
613 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
615 if (ctx->init_qp_p >= 0) {
616 rc->constQP.qpInterP = ctx->init_qp_p;
617 if (ctx->init_qp_i >= 0 && ctx->init_qp_b >= 0) {
618 rc->constQP.qpIntra = ctx->init_qp_i;
619 rc->constQP.qpInterB = ctx->init_qp_b;
620 } else if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
621 rc->constQP.qpIntra = av_clip(
622 rc->constQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
623 rc->constQP.qpInterB = av_clip(
624 rc->constQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
626 rc->constQP.qpIntra = rc->constQP.qpInterP;
627 rc->constQP.qpInterB = rc->constQP.qpInterP;
629 } else if (ctx->cqp >= 0) {
630 rc->constQP.qpInterP = rc->constQP.qpInterB = rc->constQP.qpIntra = ctx->cqp;
631 if (avctx->b_quant_factor != 0.0)
632 rc->constQP.qpInterB = av_clip(ctx->cqp * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
633 if (avctx->i_quant_factor != 0.0)
634 rc->constQP.qpIntra = av_clip(ctx->cqp * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
641 static av_cold void set_vbr(AVCodecContext *avctx)
643 NvencContext *ctx = avctx->priv_data;
644 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
647 if (avctx->qmin >= 0 && avctx->qmax >= 0) {
651 rc->minQP.qpInterB = avctx->qmin;
652 rc->minQP.qpInterP = avctx->qmin;
653 rc->minQP.qpIntra = avctx->qmin;
655 rc->maxQP.qpInterB = avctx->qmax;
656 rc->maxQP.qpInterP = avctx->qmax;
657 rc->maxQP.qpIntra = avctx->qmax;
659 qp_inter_p = (avctx->qmax + 3 * avctx->qmin) / 4; // biased towards Qmin
660 } else if (avctx->qmin >= 0) {
663 rc->minQP.qpInterB = avctx->qmin;
664 rc->minQP.qpInterP = avctx->qmin;
665 rc->minQP.qpIntra = avctx->qmin;
667 qp_inter_p = avctx->qmin;
669 qp_inter_p = 26; // default to 26
672 rc->enableInitialRCQP = 1;
674 if (ctx->init_qp_p < 0) {
675 rc->initialRCQP.qpInterP = qp_inter_p;
677 rc->initialRCQP.qpInterP = ctx->init_qp_p;
680 if (ctx->init_qp_i < 0) {
681 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
682 rc->initialRCQP.qpIntra = av_clip(
683 rc->initialRCQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
685 rc->initialRCQP.qpIntra = rc->initialRCQP.qpInterP;
688 rc->initialRCQP.qpIntra = ctx->init_qp_i;
691 if (ctx->init_qp_b < 0) {
692 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
693 rc->initialRCQP.qpInterB = av_clip(
694 rc->initialRCQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
696 rc->initialRCQP.qpInterB = rc->initialRCQP.qpInterP;
699 rc->initialRCQP.qpInterB = ctx->init_qp_b;
703 static av_cold void set_lossless(AVCodecContext *avctx)
705 NvencContext *ctx = avctx->priv_data;
706 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
708 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
709 rc->constQP.qpInterB = 0;
710 rc->constQP.qpInterP = 0;
711 rc->constQP.qpIntra = 0;
717 static void nvenc_override_rate_control(AVCodecContext *avctx)
719 NvencContext *ctx = avctx->priv_data;
720 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
723 case NV_ENC_PARAMS_RC_CONSTQP:
726 case NV_ENC_PARAMS_RC_VBR_MINQP:
727 if (avctx->qmin < 0) {
728 av_log(avctx, AV_LOG_WARNING,
729 "The variable bitrate rate-control requires "
730 "the 'qmin' option set.\n");
735 case NV_ENC_PARAMS_RC_VBR_HQ:
736 case NV_ENC_PARAMS_RC_VBR:
739 case NV_ENC_PARAMS_RC_CBR:
740 case NV_ENC_PARAMS_RC_CBR_HQ:
741 case NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ:
745 rc->rateControlMode = ctx->rc;
748 static av_cold int nvenc_recalc_surfaces(AVCodecContext *avctx)
750 NvencContext *ctx = avctx->priv_data;
751 // default minimum of 4 surfaces
752 // multiply by 2 for number of NVENCs on gpu (hardcode to 2)
753 // another multiply by 2 to avoid blocking next PBB group
754 int nb_surfaces = FFMAX(4, ctx->encode_config.frameIntervalP * 2 * 2);
757 if (ctx->rc_lookahead > 0) {
758 // +1 is to account for lkd_bound calculation later
759 // +4 is to allow sufficient pipelining with lookahead
760 nb_surfaces = FFMAX(1, FFMAX(nb_surfaces, ctx->rc_lookahead + ctx->encode_config.frameIntervalP + 1 + 4));
761 if (nb_surfaces > ctx->nb_surfaces && ctx->nb_surfaces > 0)
763 av_log(avctx, AV_LOG_WARNING,
764 "Defined rc_lookahead requires more surfaces, "
765 "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
767 ctx->nb_surfaces = FFMAX(nb_surfaces, ctx->nb_surfaces);
769 if (ctx->encode_config.frameIntervalP > 1 && ctx->nb_surfaces < nb_surfaces && ctx->nb_surfaces > 0)
771 av_log(avctx, AV_LOG_WARNING,
772 "Defined b-frame requires more surfaces, "
773 "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
774 ctx->nb_surfaces = FFMAX(ctx->nb_surfaces, nb_surfaces);
776 else if (ctx->nb_surfaces <= 0)
777 ctx->nb_surfaces = nb_surfaces;
778 // otherwise use user specified value
781 ctx->nb_surfaces = FFMAX(1, FFMIN(MAX_REGISTERED_FRAMES, ctx->nb_surfaces));
782 ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
787 static av_cold void nvenc_setup_rate_control(AVCodecContext *avctx)
789 NvencContext *ctx = avctx->priv_data;
791 if (avctx->global_quality > 0)
792 av_log(avctx, AV_LOG_WARNING, "Using global_quality with nvenc is deprecated. Use qp instead.\n");
794 if (ctx->cqp < 0 && avctx->global_quality > 0)
795 ctx->cqp = avctx->global_quality;
797 if (avctx->bit_rate > 0) {
798 ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
799 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
800 ctx->encode_config.rcParams.maxBitRate = ctx->encode_config.rcParams.averageBitRate;
803 if (avctx->rc_max_rate > 0)
804 ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
807 if (ctx->flags & NVENC_ONE_PASS)
809 if (ctx->flags & NVENC_TWO_PASSES)
812 if (ctx->twopass < 0)
813 ctx->twopass = (ctx->flags & NVENC_LOWLATENCY) != 0;
817 ctx->rc = NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ;
819 ctx->rc = NV_ENC_PARAMS_RC_CBR;
821 } else if (ctx->cqp >= 0) {
822 ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
823 } else if (ctx->twopass) {
824 ctx->rc = NV_ENC_PARAMS_RC_VBR_HQ;
825 } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
826 ctx->rc = NV_ENC_PARAMS_RC_VBR_MINQP;
830 if (ctx->rc >= 0 && ctx->rc & RC_MODE_DEPRECATED) {
831 av_log(avctx, AV_LOG_WARNING, "Specified rc mode is deprecated.\n");
832 av_log(avctx, AV_LOG_WARNING, "\tll_2pass_quality -> cbr_ld_hq\n");
833 av_log(avctx, AV_LOG_WARNING, "\tll_2pass_size -> cbr_hq\n");
834 av_log(avctx, AV_LOG_WARNING, "\tvbr_2pass -> vbr_hq\n");
835 av_log(avctx, AV_LOG_WARNING, "\tvbr_minqp -> (no replacement)\n");
837 ctx->rc &= ~RC_MODE_DEPRECATED;
840 if (ctx->flags & NVENC_LOSSLESS) {
842 } else if (ctx->rc >= 0) {
843 nvenc_override_rate_control(avctx);
845 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
849 if (avctx->rc_buffer_size > 0) {
850 ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
851 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
852 ctx->encode_config.rcParams.vbvBufferSize = 2 * ctx->encode_config.rcParams.averageBitRate;
856 ctx->encode_config.rcParams.enableAQ = 1;
857 ctx->encode_config.rcParams.aqStrength = ctx->aq_strength;
858 av_log(avctx, AV_LOG_VERBOSE, "AQ enabled.\n");
861 if (ctx->temporal_aq) {
862 ctx->encode_config.rcParams.enableTemporalAQ = 1;
863 av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ enabled.\n");
866 if (ctx->rc_lookahead > 0) {
867 int lkd_bound = FFMIN(ctx->nb_surfaces, ctx->async_depth) -
868 ctx->encode_config.frameIntervalP - 4;
871 av_log(avctx, AV_LOG_WARNING,
872 "Lookahead not enabled. Increase buffer delay (-delay).\n");
874 ctx->encode_config.rcParams.enableLookahead = 1;
875 ctx->encode_config.rcParams.lookaheadDepth = av_clip(ctx->rc_lookahead, 0, lkd_bound);
876 ctx->encode_config.rcParams.disableIadapt = ctx->no_scenecut;
877 ctx->encode_config.rcParams.disableBadapt = !ctx->b_adapt;
878 av_log(avctx, AV_LOG_VERBOSE,
879 "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",
880 ctx->encode_config.rcParams.lookaheadDepth,
881 ctx->encode_config.rcParams.disableIadapt ? "disabled" : "enabled",
882 ctx->encode_config.rcParams.disableBadapt ? "disabled" : "enabled");
886 if (ctx->strict_gop) {
887 ctx->encode_config.rcParams.strictGOPTarget = 1;
888 av_log(avctx, AV_LOG_VERBOSE, "Strict GOP target enabled.\n");
892 ctx->encode_config.rcParams.enableNonRefP = 1;
894 if (ctx->zerolatency)
895 ctx->encode_config.rcParams.zeroReorderDelay = 1;
899 //convert from float to fixed point 8.8
900 int tmp_quality = (int)(ctx->quality * 256.0f);
901 ctx->encode_config.rcParams.targetQuality = (uint8_t)(tmp_quality >> 8);
902 ctx->encode_config.rcParams.targetQualityLSB = (uint8_t)(tmp_quality & 0xff);
906 static av_cold int nvenc_setup_h264_config(AVCodecContext *avctx)
908 NvencContext *ctx = avctx->priv_data;
909 NV_ENC_CONFIG *cc = &ctx->encode_config;
910 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
911 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
913 vui->colourMatrix = avctx->colorspace;
914 vui->colourPrimaries = avctx->color_primaries;
915 vui->transferCharacteristics = avctx->color_trc;
916 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
917 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
919 vui->colourDescriptionPresentFlag =
920 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
922 vui->videoSignalTypePresentFlag =
923 (vui->colourDescriptionPresentFlag
924 || vui->videoFormat != 5
925 || vui->videoFullRangeFlag != 0);
928 h264->sliceModeData = 1;
930 h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
931 h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
932 h264->outputAUD = ctx->aud;
934 if (avctx->refs >= 0) {
935 /* 0 means "let the hardware decide" */
936 h264->maxNumRefFrames = avctx->refs;
938 if (avctx->gop_size >= 0) {
939 h264->idrPeriod = cc->gopLength;
942 if (IS_CBR(cc->rcParams.rateControlMode)) {
943 h264->outputBufferingPeriodSEI = 1;
946 h264->outputPictureTimingSEI = 1;
948 if (cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ ||
949 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_HQ ||
950 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_VBR_HQ) {
951 h264->adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
952 h264->fmoMode = NV_ENC_H264_FMO_DISABLE;
955 if (ctx->flags & NVENC_LOSSLESS) {
956 h264->qpPrimeYZeroTransformBypassFlag = 1;
958 switch(ctx->profile) {
959 case NV_ENC_H264_PROFILE_BASELINE:
960 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
961 avctx->profile = FF_PROFILE_H264_BASELINE;
963 case NV_ENC_H264_PROFILE_MAIN:
964 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
965 avctx->profile = FF_PROFILE_H264_MAIN;
967 case NV_ENC_H264_PROFILE_HIGH:
968 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
969 avctx->profile = FF_PROFILE_H264_HIGH;
971 case NV_ENC_H264_PROFILE_HIGH_444P:
972 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
973 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
978 // force setting profile as high444p if input is AV_PIX_FMT_YUV444P
979 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P) {
980 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
981 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
984 h264->chromaFormatIDC = avctx->profile == FF_PROFILE_H264_HIGH_444_PREDICTIVE ? 3 : 1;
986 h264->level = ctx->level;
989 h264->entropyCodingMode = ctx->coder;
994 static av_cold int nvenc_setup_hevc_config(AVCodecContext *avctx)
996 NvencContext *ctx = avctx->priv_data;
997 NV_ENC_CONFIG *cc = &ctx->encode_config;
998 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
999 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
1001 vui->colourMatrix = avctx->colorspace;
1002 vui->colourPrimaries = avctx->color_primaries;
1003 vui->transferCharacteristics = avctx->color_trc;
1004 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
1005 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
1007 vui->colourDescriptionPresentFlag =
1008 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
1010 vui->videoSignalTypePresentFlag =
1011 (vui->colourDescriptionPresentFlag
1012 || vui->videoFormat != 5
1013 || vui->videoFullRangeFlag != 0);
1015 hevc->sliceMode = 3;
1016 hevc->sliceModeData = 1;
1018 hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
1019 hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
1020 hevc->outputAUD = ctx->aud;
1022 if (avctx->refs >= 0) {
1023 /* 0 means "let the hardware decide" */
1024 hevc->maxNumRefFramesInDPB = avctx->refs;
1026 if (avctx->gop_size >= 0) {
1027 hevc->idrPeriod = cc->gopLength;
1030 if (IS_CBR(cc->rcParams.rateControlMode)) {
1031 hevc->outputBufferingPeriodSEI = 1;
1034 hevc->outputPictureTimingSEI = 1;
1036 switch (ctx->profile) {
1037 case NV_ENC_HEVC_PROFILE_MAIN:
1038 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
1039 avctx->profile = FF_PROFILE_HEVC_MAIN;
1041 case NV_ENC_HEVC_PROFILE_MAIN_10:
1042 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1043 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
1045 case NV_ENC_HEVC_PROFILE_REXT:
1046 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1047 avctx->profile = FF_PROFILE_HEVC_REXT;
1051 // force setting profile as main10 if input is 10 bit
1052 if (IS_10BIT(ctx->data_pix_fmt)) {
1053 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1054 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
1057 // force setting profile as rext if input is yuv444
1058 if (IS_YUV444(ctx->data_pix_fmt)) {
1059 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1060 avctx->profile = FF_PROFILE_HEVC_REXT;
1063 hevc->chromaFormatIDC = IS_YUV444(ctx->data_pix_fmt) ? 3 : 1;
1065 hevc->pixelBitDepthMinus8 = IS_10BIT(ctx->data_pix_fmt) ? 2 : 0;
1067 hevc->level = ctx->level;
1069 hevc->tier = ctx->tier;
1074 static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx)
1076 switch (avctx->codec->id) {
1077 case AV_CODEC_ID_H264:
1078 return nvenc_setup_h264_config(avctx);
1079 case AV_CODEC_ID_HEVC:
1080 return nvenc_setup_hevc_config(avctx);
1081 /* Earlier switch/case will return if unknown codec is passed. */
1087 static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
1089 NvencContext *ctx = avctx->priv_data;
1090 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1091 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1093 NV_ENC_PRESET_CONFIG preset_config = { 0 };
1094 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
1095 AVCPBProperties *cpb_props;
1099 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1100 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
1102 ctx->init_encode_params.encodeHeight = avctx->height;
1103 ctx->init_encode_params.encodeWidth = avctx->width;
1105 ctx->init_encode_params.encodeConfig = &ctx->encode_config;
1107 nvenc_map_preset(ctx);
1109 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
1110 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
1112 nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder,
1113 ctx->init_encode_params.encodeGUID,
1114 ctx->init_encode_params.presetGUID,
1116 if (nv_status != NV_ENC_SUCCESS)
1117 return nvenc_print_error(avctx, nv_status, "Cannot get the preset configuration");
1119 memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
1121 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1125 if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0) {
1126 dw*= avctx->sample_aspect_ratio.num;
1127 dh*= avctx->sample_aspect_ratio.den;
1129 av_reduce(&dw, &dh, dw, dh, 1024 * 1024);
1130 ctx->init_encode_params.darHeight = dh;
1131 ctx->init_encode_params.darWidth = dw;
1133 ctx->init_encode_params.frameRateNum = avctx->time_base.den;
1134 ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
1136 ctx->init_encode_params.enableEncodeAsync = 0;
1137 ctx->init_encode_params.enablePTD = 1;
1139 if (ctx->weighted_pred == 1)
1140 ctx->init_encode_params.enableWeightedPrediction = 1;
1142 if (ctx->bluray_compat) {
1144 avctx->refs = FFMIN(FFMAX(avctx->refs, 0), 6);
1145 avctx->max_b_frames = FFMIN(avctx->max_b_frames, 3);
1146 switch (avctx->codec->id) {
1147 case AV_CODEC_ID_H264:
1148 /* maximum level depends on used resolution */
1150 case AV_CODEC_ID_HEVC:
1151 ctx->level = NV_ENC_LEVEL_HEVC_51;
1152 ctx->tier = NV_ENC_TIER_HEVC_HIGH;
1157 if (avctx->gop_size > 0) {
1158 if (avctx->max_b_frames >= 0) {
1159 /* 0 is intra-only, 1 is I/P only, 2 is one B-Frame, 3 two B-frames, and so on. */
1160 ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
1163 ctx->encode_config.gopLength = avctx->gop_size;
1164 } else if (avctx->gop_size == 0) {
1165 ctx->encode_config.frameIntervalP = 0;
1166 ctx->encode_config.gopLength = 1;
1169 ctx->initial_pts[0] = AV_NOPTS_VALUE;
1170 ctx->initial_pts[1] = AV_NOPTS_VALUE;
1172 nvenc_recalc_surfaces(avctx);
1174 nvenc_setup_rate_control(avctx);
1176 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1177 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
1179 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
1182 res = nvenc_setup_codec_config(avctx);
1186 res = nvenc_push_context(avctx);
1190 nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
1192 res = nvenc_pop_context(avctx);
1196 if (nv_status != NV_ENC_SUCCESS) {
1197 return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
1200 if (ctx->encode_config.frameIntervalP > 1)
1201 avctx->has_b_frames = 2;
1203 if (ctx->encode_config.rcParams.averageBitRate > 0)
1204 avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
1206 cpb_props = ff_add_cpb_side_data(avctx);
1208 return AVERROR(ENOMEM);
1209 cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
1210 cpb_props->avg_bitrate = avctx->bit_rate;
1211 cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
1216 static NV_ENC_BUFFER_FORMAT nvenc_map_buffer_format(enum AVPixelFormat pix_fmt)
1219 case AV_PIX_FMT_YUV420P:
1220 return NV_ENC_BUFFER_FORMAT_YV12_PL;
1221 case AV_PIX_FMT_NV12:
1222 return NV_ENC_BUFFER_FORMAT_NV12_PL;
1223 case AV_PIX_FMT_P010:
1224 case AV_PIX_FMT_P016:
1225 return NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1226 case AV_PIX_FMT_YUV444P:
1227 return NV_ENC_BUFFER_FORMAT_YUV444_PL;
1228 case AV_PIX_FMT_YUV444P16:
1229 return NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1230 case AV_PIX_FMT_0RGB32:
1231 return NV_ENC_BUFFER_FORMAT_ARGB;
1232 case AV_PIX_FMT_0BGR32:
1233 return NV_ENC_BUFFER_FORMAT_ABGR;
1235 return NV_ENC_BUFFER_FORMAT_UNDEFINED;
1239 static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
1241 NvencContext *ctx = avctx->priv_data;
1242 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1243 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1244 NvencSurface* tmp_surface = &ctx->surfaces[idx];
1246 NVENCSTATUS nv_status;
1247 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
1248 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1250 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1251 ctx->surfaces[idx].in_ref = av_frame_alloc();
1252 if (!ctx->surfaces[idx].in_ref)
1253 return AVERROR(ENOMEM);
1255 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1257 ctx->surfaces[idx].format = nvenc_map_buffer_format(ctx->data_pix_fmt);
1258 if (ctx->surfaces[idx].format == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1259 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1260 av_get_pix_fmt_name(ctx->data_pix_fmt));
1261 return AVERROR(EINVAL);
1264 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1265 allocSurf.width = avctx->width;
1266 allocSurf.height = avctx->height;
1267 allocSurf.bufferFmt = ctx->surfaces[idx].format;
1269 nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
1270 if (nv_status != NV_ENC_SUCCESS) {
1271 return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
1274 ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
1275 ctx->surfaces[idx].width = allocSurf.width;
1276 ctx->surfaces[idx].height = allocSurf.height;
1279 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
1280 if (nv_status != NV_ENC_SUCCESS) {
1281 int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
1282 if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
1283 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
1284 av_frame_free(&ctx->surfaces[idx].in_ref);
1288 ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1289 ctx->surfaces[idx].size = allocOut.size;
1291 av_fifo_generic_write(ctx->unused_surface_queue, &tmp_surface, sizeof(tmp_surface), NULL);
1296 static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx)
1298 NvencContext *ctx = avctx->priv_data;
1299 int i, res = 0, res2;
1301 ctx->surfaces = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->surfaces));
1303 return AVERROR(ENOMEM);
1305 ctx->timestamp_list = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
1306 if (!ctx->timestamp_list)
1307 return AVERROR(ENOMEM);
1309 ctx->unused_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1310 if (!ctx->unused_surface_queue)
1311 return AVERROR(ENOMEM);
1313 ctx->output_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1314 if (!ctx->output_surface_queue)
1315 return AVERROR(ENOMEM);
1316 ctx->output_surface_ready_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1317 if (!ctx->output_surface_ready_queue)
1318 return AVERROR(ENOMEM);
1320 res = nvenc_push_context(avctx);
1324 for (i = 0; i < ctx->nb_surfaces; i++) {
1325 if ((res = nvenc_alloc_surface(avctx, i)) < 0)
1330 res2 = nvenc_pop_context(avctx);
1337 static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
1339 NvencContext *ctx = avctx->priv_data;
1340 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1341 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1343 NVENCSTATUS nv_status;
1344 uint32_t outSize = 0;
1345 char tmpHeader[256];
1346 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1347 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1349 payload.spsppsBuffer = tmpHeader;
1350 payload.inBufferSize = sizeof(tmpHeader);
1351 payload.outSPSPPSPayloadSize = &outSize;
1353 nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
1354 if (nv_status != NV_ENC_SUCCESS) {
1355 return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
1358 avctx->extradata_size = outSize;
1359 avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
1361 if (!avctx->extradata) {
1362 return AVERROR(ENOMEM);
1365 memcpy(avctx->extradata, tmpHeader, outSize);
1370 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
1372 NvencContext *ctx = avctx->priv_data;
1373 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1374 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1377 /* the encoder has to be flushed before it can be closed */
1378 if (ctx->nvencoder) {
1379 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
1380 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
1382 res = nvenc_push_context(avctx);
1386 p_nvenc->nvEncEncodePicture(ctx->nvencoder, ¶ms);
1389 av_fifo_freep(&ctx->timestamp_list);
1390 av_fifo_freep(&ctx->output_surface_ready_queue);
1391 av_fifo_freep(&ctx->output_surface_queue);
1392 av_fifo_freep(&ctx->unused_surface_queue);
1394 if (ctx->surfaces && (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11)) {
1395 for (i = 0; i < ctx->nb_registered_frames; i++) {
1396 if (ctx->registered_frames[i].mapped)
1397 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[i].in_map.mappedResource);
1398 if (ctx->registered_frames[i].regptr)
1399 p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1401 ctx->nb_registered_frames = 0;
1404 if (ctx->surfaces) {
1405 for (i = 0; i < ctx->nb_surfaces; ++i) {
1406 if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
1407 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
1408 av_frame_free(&ctx->surfaces[i].in_ref);
1409 p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
1412 av_freep(&ctx->surfaces);
1413 ctx->nb_surfaces = 0;
1415 if (ctx->nvencoder) {
1416 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1418 res = nvenc_pop_context(avctx);
1422 ctx->nvencoder = NULL;
1424 if (ctx->cu_context_internal)
1425 dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal);
1426 ctx->cu_context = ctx->cu_context_internal = NULL;
1429 if (ctx->d3d11_device) {
1430 ID3D11Device_Release(ctx->d3d11_device);
1431 ctx->d3d11_device = NULL;
1435 nvenc_free_functions(&dl_fn->nvenc_dl);
1436 cuda_free_functions(&dl_fn->cuda_dl);
1438 dl_fn->nvenc_device_count = 0;
1440 av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
1445 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
1447 NvencContext *ctx = avctx->priv_data;
1450 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1451 AVHWFramesContext *frames_ctx;
1452 if (!avctx->hw_frames_ctx) {
1453 av_log(avctx, AV_LOG_ERROR,
1454 "hw_frames_ctx must be set when using GPU frames as input\n");
1455 return AVERROR(EINVAL);
1457 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1458 if (frames_ctx->format != avctx->pix_fmt) {
1459 av_log(avctx, AV_LOG_ERROR,
1460 "hw_frames_ctx must match the GPU frame type\n");
1461 return AVERROR(EINVAL);
1463 ctx->data_pix_fmt = frames_ctx->sw_format;
1465 ctx->data_pix_fmt = avctx->pix_fmt;
1468 if ((ret = nvenc_load_libraries(avctx)) < 0)
1471 if ((ret = nvenc_setup_device(avctx)) < 0)
1474 if ((ret = nvenc_setup_encoder(avctx)) < 0)
1477 if ((ret = nvenc_setup_surfaces(avctx)) < 0)
1480 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1481 if ((ret = nvenc_setup_extradata(avctx)) < 0)
1488 static NvencSurface *get_free_frame(NvencContext *ctx)
1490 NvencSurface *tmp_surf;
1492 if (!(av_fifo_size(ctx->unused_surface_queue) > 0))
1496 av_fifo_generic_read(ctx->unused_surface_queue, &tmp_surf, sizeof(tmp_surf), NULL);
1500 static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *nv_surface,
1501 NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params, const AVFrame *frame)
1503 int dst_linesize[4] = {
1504 lock_buffer_params->pitch,
1505 lock_buffer_params->pitch,
1506 lock_buffer_params->pitch,
1507 lock_buffer_params->pitch
1509 uint8_t *dst_data[4];
1512 if (frame->format == AV_PIX_FMT_YUV420P)
1513 dst_linesize[1] = dst_linesize[2] >>= 1;
1515 ret = av_image_fill_pointers(dst_data, frame->format, nv_surface->height,
1516 lock_buffer_params->bufferDataPtr, dst_linesize);
1520 if (frame->format == AV_PIX_FMT_YUV420P)
1521 FFSWAP(uint8_t*, dst_data[1], dst_data[2]);
1523 av_image_copy(dst_data, dst_linesize,
1524 (const uint8_t**)frame->data, frame->linesize, frame->format,
1525 avctx->width, avctx->height);
1530 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1532 NvencContext *ctx = avctx->priv_data;
1533 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1534 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1535 NVENCSTATUS nv_status;
1539 if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1540 for (i = 0; i < ctx->nb_registered_frames; i++) {
1541 if (!ctx->registered_frames[i].mapped) {
1542 if (ctx->registered_frames[i].regptr) {
1543 nv_status = p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1544 if (nv_status != NV_ENC_SUCCESS)
1545 return nvenc_print_error(avctx, nv_status, "Failed unregistering unused input resource");
1546 ctx->registered_frames[i].ptr = NULL;
1547 ctx->registered_frames[i].regptr = NULL;
1553 return ctx->nb_registered_frames++;
1556 av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1557 return AVERROR(ENOMEM);
1560 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1562 NvencContext *ctx = avctx->priv_data;
1563 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1564 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1566 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frame->hw_frames_ctx->data;
1567 NV_ENC_REGISTER_RESOURCE reg;
1570 for (i = 0; i < ctx->nb_registered_frames; i++) {
1571 if (avctx->pix_fmt == AV_PIX_FMT_CUDA && ctx->registered_frames[i].ptr == frame->data[0])
1573 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])
1577 idx = nvenc_find_free_reg_resource(avctx);
1581 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1582 reg.width = frames_ctx->width;
1583 reg.height = frames_ctx->height;
1584 reg.pitch = frame->linesize[0];
1585 reg.resourceToRegister = frame->data[0];
1587 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1588 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1590 else if (avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1591 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX;
1592 reg.subResourceIndex = (intptr_t)frame->data[1];
1595 reg.bufferFormat = nvenc_map_buffer_format(frames_ctx->sw_format);
1596 if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1597 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1598 av_get_pix_fmt_name(frames_ctx->sw_format));
1599 return AVERROR(EINVAL);
1602 ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, ®);
1603 if (ret != NV_ENC_SUCCESS) {
1604 nvenc_print_error(avctx, ret, "Error registering an input resource");
1605 return AVERROR_UNKNOWN;
1608 ctx->registered_frames[idx].ptr = frame->data[0];
1609 ctx->registered_frames[idx].ptr_index = reg.subResourceIndex;
1610 ctx->registered_frames[idx].regptr = reg.registeredResource;
1614 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1615 NvencSurface *nvenc_frame)
1617 NvencContext *ctx = avctx->priv_data;
1618 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1619 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1622 NVENCSTATUS nv_status;
1624 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1625 int reg_idx = nvenc_register_frame(avctx, frame);
1627 av_log(avctx, AV_LOG_ERROR, "Could not register an input HW frame\n");
1631 res = av_frame_ref(nvenc_frame->in_ref, frame);
1635 if (!ctx->registered_frames[reg_idx].mapped) {
1636 ctx->registered_frames[reg_idx].in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1637 ctx->registered_frames[reg_idx].in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1638 nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &ctx->registered_frames[reg_idx].in_map);
1639 if (nv_status != NV_ENC_SUCCESS) {
1640 av_frame_unref(nvenc_frame->in_ref);
1641 return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
1645 ctx->registered_frames[reg_idx].mapped += 1;
1647 nvenc_frame->reg_idx = reg_idx;
1648 nvenc_frame->input_surface = ctx->registered_frames[reg_idx].in_map.mappedResource;
1649 nvenc_frame->format = ctx->registered_frames[reg_idx].in_map.mappedBufferFmt;
1650 nvenc_frame->pitch = frame->linesize[0];
1654 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1656 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1657 lockBufferParams.inputBuffer = nvenc_frame->input_surface;
1659 nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
1660 if (nv_status != NV_ENC_SUCCESS) {
1661 return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
1664 nvenc_frame->pitch = lockBufferParams.pitch;
1665 res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
1667 nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
1668 if (nv_status != NV_ENC_SUCCESS) {
1669 return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
1676 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1677 NV_ENC_PIC_PARAMS *params)
1679 NvencContext *ctx = avctx->priv_data;
1681 switch (avctx->codec->id) {
1682 case AV_CODEC_ID_H264:
1683 params->codecPicParams.h264PicParams.sliceMode =
1684 ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1685 params->codecPicParams.h264PicParams.sliceModeData =
1686 ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1688 case AV_CODEC_ID_HEVC:
1689 params->codecPicParams.hevcPicParams.sliceMode =
1690 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1691 params->codecPicParams.hevcPicParams.sliceModeData =
1692 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1697 static inline void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
1699 av_fifo_generic_write(queue, ×tamp, sizeof(timestamp), NULL);
1702 static inline int64_t timestamp_queue_dequeue(AVFifoBuffer* queue)
1704 int64_t timestamp = AV_NOPTS_VALUE;
1705 if (av_fifo_size(queue) > 0)
1706 av_fifo_generic_read(queue, ×tamp, sizeof(timestamp), NULL);
1711 static int nvenc_set_timestamp(AVCodecContext *avctx,
1712 NV_ENC_LOCK_BITSTREAM *params,
1715 NvencContext *ctx = avctx->priv_data;
1717 pkt->pts = params->outputTimeStamp;
1719 /* generate the first dts by linearly extrapolating the
1720 * first two pts values to the past */
1721 if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
1722 ctx->initial_pts[1] != AV_NOPTS_VALUE) {
1723 int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
1726 if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
1727 (ts0 > 0 && ts1 < INT64_MIN + ts0))
1728 return AVERROR(ERANGE);
1731 if ((delta < 0 && ts0 > INT64_MAX + delta) ||
1732 (delta > 0 && ts0 < INT64_MIN + delta))
1733 return AVERROR(ERANGE);
1734 pkt->dts = ts0 - delta;
1736 ctx->first_packet_output = 1;
1740 pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
1745 static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
1747 NvencContext *ctx = avctx->priv_data;
1748 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1749 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1751 uint32_t slice_mode_data;
1752 uint32_t *slice_offsets = NULL;
1753 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1754 NVENCSTATUS nv_status;
1757 enum AVPictureType pict_type;
1759 switch (avctx->codec->id) {
1760 case AV_CODEC_ID_H264:
1761 slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1763 case AV_CODEC_ID_H265:
1764 slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1767 av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
1768 res = AVERROR(EINVAL);
1771 slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
1773 if (!slice_offsets) {
1774 res = AVERROR(ENOMEM);
1778 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1780 lock_params.doNotWait = 0;
1781 lock_params.outputBitstream = tmpoutsurf->output_surface;
1782 lock_params.sliceOffsets = slice_offsets;
1784 nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
1785 if (nv_status != NV_ENC_SUCCESS) {
1786 res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
1790 if (res = ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes,0)) {
1791 p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1795 memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1797 nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1798 if (nv_status != NV_ENC_SUCCESS) {
1799 res = nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
1804 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1805 ctx->registered_frames[tmpoutsurf->reg_idx].mapped -= 1;
1806 if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped == 0) {
1807 nv_status = p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[tmpoutsurf->reg_idx].in_map.mappedResource);
1808 if (nv_status != NV_ENC_SUCCESS) {
1809 res = nvenc_print_error(avctx, nv_status, "Failed unmapping input resource");
1812 nv_status = p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[tmpoutsurf->reg_idx].regptr);
1813 if (nv_status != NV_ENC_SUCCESS) {
1814 res = nvenc_print_error(avctx, nv_status, "Failed unregistering input resource");
1817 ctx->registered_frames[tmpoutsurf->reg_idx].ptr = NULL;
1818 ctx->registered_frames[tmpoutsurf->reg_idx].regptr = NULL;
1819 } else if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped < 0) {
1824 av_frame_unref(tmpoutsurf->in_ref);
1826 tmpoutsurf->input_surface = NULL;
1829 switch (lock_params.pictureType) {
1830 case NV_ENC_PIC_TYPE_IDR:
1831 pkt->flags |= AV_PKT_FLAG_KEY;
1832 case NV_ENC_PIC_TYPE_I:
1833 pict_type = AV_PICTURE_TYPE_I;
1835 case NV_ENC_PIC_TYPE_P:
1836 pict_type = AV_PICTURE_TYPE_P;
1838 case NV_ENC_PIC_TYPE_B:
1839 pict_type = AV_PICTURE_TYPE_B;
1841 case NV_ENC_PIC_TYPE_BI:
1842 pict_type = AV_PICTURE_TYPE_BI;
1845 av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
1846 av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
1847 res = AVERROR_EXTERNAL;
1851 #if FF_API_CODED_FRAME
1852 FF_DISABLE_DEPRECATION_WARNINGS
1853 avctx->coded_frame->pict_type = pict_type;
1854 FF_ENABLE_DEPRECATION_WARNINGS
1857 ff_side_data_set_encoder_stats(pkt,
1858 (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
1860 res = nvenc_set_timestamp(avctx, &lock_params, pkt);
1864 av_free(slice_offsets);
1869 timestamp_queue_dequeue(ctx->timestamp_list);
1872 av_free(slice_offsets);
1877 static int output_ready(AVCodecContext *avctx, int flush)
1879 NvencContext *ctx = avctx->priv_data;
1880 int nb_ready, nb_pending;
1882 /* when B-frames are enabled, we wait for two initial timestamps to
1883 * calculate the first dts */
1884 if (!flush && avctx->max_b_frames > 0 &&
1885 (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
1888 nb_ready = av_fifo_size(ctx->output_surface_ready_queue) / sizeof(NvencSurface*);
1889 nb_pending = av_fifo_size(ctx->output_surface_queue) / sizeof(NvencSurface*);
1891 return nb_ready > 0;
1892 return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
1895 int ff_nvenc_send_frame(AVCodecContext *avctx, const AVFrame *frame)
1897 NVENCSTATUS nv_status;
1898 NvencSurface *tmp_out_surf, *in_surf;
1901 NvencContext *ctx = avctx->priv_data;
1902 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1903 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1905 NV_ENC_PIC_PARAMS pic_params = { 0 };
1906 pic_params.version = NV_ENC_PIC_PARAMS_VER;
1908 if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
1909 return AVERROR(EINVAL);
1911 if (ctx->encoder_flushing)
1915 in_surf = get_free_frame(ctx);
1917 return AVERROR(EAGAIN);
1919 res = nvenc_push_context(avctx);
1923 res = nvenc_upload_frame(avctx, frame, in_surf);
1925 res2 = nvenc_pop_context(avctx);
1932 pic_params.inputBuffer = in_surf->input_surface;
1933 pic_params.bufferFmt = in_surf->format;
1934 pic_params.inputWidth = in_surf->width;
1935 pic_params.inputHeight = in_surf->height;
1936 pic_params.inputPitch = in_surf->pitch;
1937 pic_params.outputBitstream = in_surf->output_surface;
1939 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1940 if (frame->top_field_first)
1941 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
1943 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
1945 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1948 if (ctx->forced_idr >= 0 && frame->pict_type == AV_PICTURE_TYPE_I) {
1949 pic_params.encodePicFlags =
1950 ctx->forced_idr ? NV_ENC_PIC_FLAG_FORCEIDR : NV_ENC_PIC_FLAG_FORCEINTRA;
1952 pic_params.encodePicFlags = 0;
1955 pic_params.inputTimeStamp = frame->pts;
1957 nvenc_codec_specific_pic_params(avctx, &pic_params);
1959 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1960 ctx->encoder_flushing = 1;
1963 res = nvenc_push_context(avctx);
1967 nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
1969 res = nvenc_pop_context(avctx);
1973 if (nv_status != NV_ENC_SUCCESS &&
1974 nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
1975 return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
1978 av_fifo_generic_write(ctx->output_surface_queue, &in_surf, sizeof(in_surf), NULL);
1979 timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
1981 if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
1982 ctx->initial_pts[0] = frame->pts;
1983 else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
1984 ctx->initial_pts[1] = frame->pts;
1987 /* all the pending buffers are now ready for output */
1988 if (nv_status == NV_ENC_SUCCESS) {
1989 while (av_fifo_size(ctx->output_surface_queue) > 0) {
1990 av_fifo_generic_read(ctx->output_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
1991 av_fifo_generic_write(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
1998 int ff_nvenc_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
2000 NvencSurface *tmp_out_surf;
2003 NvencContext *ctx = avctx->priv_data;
2005 if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
2006 return AVERROR(EINVAL);
2008 if (output_ready(avctx, ctx->encoder_flushing)) {
2009 av_fifo_generic_read(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2011 res = nvenc_push_context(avctx);
2015 res = process_output_surface(avctx, pkt, tmp_out_surf);
2017 res2 = nvenc_pop_context(avctx);
2024 av_fifo_generic_write(ctx->unused_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2025 } else if (ctx->encoder_flushing) {
2028 return AVERROR(EAGAIN);
2034 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
2035 const AVFrame *frame, int *got_packet)
2037 NvencContext *ctx = avctx->priv_data;
2040 if (!ctx->encoder_flushing) {
2041 res = ff_nvenc_send_frame(avctx, frame);
2046 res = ff_nvenc_receive_packet(avctx, pkt);
2047 if (res == AVERROR(EAGAIN) || res == AVERROR_EOF) {
2049 } else if (res < 0) {