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[] = {
54 #define IS_10BIT(pix_fmt) (pix_fmt == AV_PIX_FMT_P010 || \
55 pix_fmt == AV_PIX_FMT_YUV444P16)
57 #define IS_YUV444(pix_fmt) (pix_fmt == AV_PIX_FMT_YUV444P || \
58 pix_fmt == AV_PIX_FMT_YUV444P16)
65 { NV_ENC_SUCCESS, 0, "success" },
66 { NV_ENC_ERR_NO_ENCODE_DEVICE, AVERROR(ENOENT), "no encode device" },
67 { NV_ENC_ERR_UNSUPPORTED_DEVICE, AVERROR(ENOSYS), "unsupported device" },
68 { NV_ENC_ERR_INVALID_ENCODERDEVICE, AVERROR(EINVAL), "invalid encoder device" },
69 { NV_ENC_ERR_INVALID_DEVICE, AVERROR(EINVAL), "invalid device" },
70 { NV_ENC_ERR_DEVICE_NOT_EXIST, AVERROR(EIO), "device does not exist" },
71 { NV_ENC_ERR_INVALID_PTR, AVERROR(EFAULT), "invalid ptr" },
72 { NV_ENC_ERR_INVALID_EVENT, AVERROR(EINVAL), "invalid event" },
73 { NV_ENC_ERR_INVALID_PARAM, AVERROR(EINVAL), "invalid param" },
74 { NV_ENC_ERR_INVALID_CALL, AVERROR(EINVAL), "invalid call" },
75 { NV_ENC_ERR_OUT_OF_MEMORY, AVERROR(ENOMEM), "out of memory" },
76 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED, AVERROR(EINVAL), "encoder not initialized" },
77 { NV_ENC_ERR_UNSUPPORTED_PARAM, AVERROR(ENOSYS), "unsupported param" },
78 { NV_ENC_ERR_LOCK_BUSY, AVERROR(EAGAIN), "lock busy" },
79 { NV_ENC_ERR_NOT_ENOUGH_BUFFER, AVERROR_BUFFER_TOO_SMALL, "not enough buffer"},
80 { NV_ENC_ERR_INVALID_VERSION, AVERROR(EINVAL), "invalid version" },
81 { NV_ENC_ERR_MAP_FAILED, AVERROR(EIO), "map failed" },
82 { NV_ENC_ERR_NEED_MORE_INPUT, AVERROR(EAGAIN), "need more input" },
83 { NV_ENC_ERR_ENCODER_BUSY, AVERROR(EAGAIN), "encoder busy" },
84 { NV_ENC_ERR_EVENT_NOT_REGISTERD, AVERROR(EBADF), "event not registered" },
85 { NV_ENC_ERR_GENERIC, AVERROR_UNKNOWN, "generic error" },
86 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY, AVERROR(EINVAL), "incompatible client key" },
87 { NV_ENC_ERR_UNIMPLEMENTED, AVERROR(ENOSYS), "unimplemented" },
88 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO), "resource register failed" },
89 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED, AVERROR(EBADF), "resource not registered" },
90 { NV_ENC_ERR_RESOURCE_NOT_MAPPED, AVERROR(EBADF), "resource not mapped" },
93 static int nvenc_map_error(NVENCSTATUS err, const char **desc)
96 for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
97 if (nvenc_errors[i].nverr == err) {
99 *desc = nvenc_errors[i].desc;
100 return nvenc_errors[i].averr;
104 *desc = "unknown error";
105 return AVERROR_UNKNOWN;
108 static int nvenc_print_error(void *log_ctx, NVENCSTATUS err,
109 const char *error_string)
113 ret = nvenc_map_error(err, &desc);
114 av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
118 static void nvenc_print_driver_requirement(AVCodecContext *avctx, int level)
120 #if defined(_WIN32) || defined(__CYGWIN__)
121 const char *minver = "378.66";
123 const char *minver = "378.13";
125 av_log(avctx, level, "The minimum required Nvidia driver for nvenc is %s or newer\n", minver);
128 static av_cold int nvenc_load_libraries(AVCodecContext *avctx)
130 NvencContext *ctx = avctx->priv_data;
131 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
133 uint32_t nvenc_max_ver;
136 ret = cuda_load_functions(&dl_fn->cuda_dl, avctx);
140 ret = nvenc_load_functions(&dl_fn->nvenc_dl, avctx);
142 nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
146 err = dl_fn->nvenc_dl->NvEncodeAPIGetMaxSupportedVersion(&nvenc_max_ver);
147 if (err != NV_ENC_SUCCESS)
148 return nvenc_print_error(avctx, err, "Failed to query nvenc max version");
150 av_log(avctx, AV_LOG_VERBOSE, "Loaded Nvenc version %d.%d\n", nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
152 if ((NVENCAPI_MAJOR_VERSION << 4 | NVENCAPI_MINOR_VERSION) > nvenc_max_ver) {
153 av_log(avctx, AV_LOG_ERROR, "Driver does not support the required nvenc API version. "
154 "Required: %d.%d Found: %d.%d\n",
155 NVENCAPI_MAJOR_VERSION, NVENCAPI_MINOR_VERSION,
156 nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
157 nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
158 return AVERROR(ENOSYS);
161 dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
163 err = dl_fn->nvenc_dl->NvEncodeAPICreateInstance(&dl_fn->nvenc_funcs);
164 if (err != NV_ENC_SUCCESS)
165 return nvenc_print_error(avctx, err, "Failed to create nvenc instance");
167 av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
172 static int nvenc_push_context(AVCodecContext *avctx)
174 NvencContext *ctx = avctx->priv_data;
175 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
178 if (ctx->d3d11_device)
181 cu_res = dl_fn->cuda_dl->cuCtxPushCurrent(ctx->cu_context);
182 if (cu_res != CUDA_SUCCESS) {
183 av_log(avctx, AV_LOG_ERROR, "cuCtxPushCurrent failed\n");
184 return AVERROR_EXTERNAL;
190 static int nvenc_pop_context(AVCodecContext *avctx)
192 NvencContext *ctx = avctx->priv_data;
193 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
197 if (ctx->d3d11_device)
200 cu_res = dl_fn->cuda_dl->cuCtxPopCurrent(&dummy);
201 if (cu_res != CUDA_SUCCESS) {
202 av_log(avctx, AV_LOG_ERROR, "cuCtxPopCurrent failed\n");
203 return AVERROR_EXTERNAL;
209 static av_cold int nvenc_open_session(AVCodecContext *avctx)
211 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
212 NvencContext *ctx = avctx->priv_data;
213 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
216 params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
217 params.apiVersion = NVENCAPI_VERSION;
218 if (ctx->d3d11_device) {
219 params.device = ctx->d3d11_device;
220 params.deviceType = NV_ENC_DEVICE_TYPE_DIRECTX;
222 params.device = ctx->cu_context;
223 params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
226 ret = p_nvenc->nvEncOpenEncodeSessionEx(¶ms, &ctx->nvencoder);
227 if (ret != NV_ENC_SUCCESS) {
228 ctx->nvencoder = NULL;
229 return nvenc_print_error(avctx, ret, "OpenEncodeSessionEx failed");
235 static int nvenc_check_codec_support(AVCodecContext *avctx)
237 NvencContext *ctx = avctx->priv_data;
238 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
239 int i, ret, count = 0;
242 ret = p_nvenc->nvEncGetEncodeGUIDCount(ctx->nvencoder, &count);
244 if (ret != NV_ENC_SUCCESS || !count)
245 return AVERROR(ENOSYS);
247 guids = av_malloc(count * sizeof(GUID));
249 return AVERROR(ENOMEM);
251 ret = p_nvenc->nvEncGetEncodeGUIDs(ctx->nvencoder, guids, count, &count);
252 if (ret != NV_ENC_SUCCESS) {
253 ret = AVERROR(ENOSYS);
257 ret = AVERROR(ENOSYS);
258 for (i = 0; i < count; i++) {
259 if (!memcmp(&guids[i], &ctx->init_encode_params.encodeGUID, sizeof(*guids))) {
271 static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
273 NvencContext *ctx = avctx->priv_data;
274 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
275 NV_ENC_CAPS_PARAM params = { 0 };
278 params.version = NV_ENC_CAPS_PARAM_VER;
279 params.capsToQuery = cap;
281 ret = p_nvenc->nvEncGetEncodeCaps(ctx->nvencoder, ctx->init_encode_params.encodeGUID, ¶ms, &val);
283 if (ret == NV_ENC_SUCCESS)
288 static int nvenc_check_capabilities(AVCodecContext *avctx)
290 NvencContext *ctx = avctx->priv_data;
293 ret = nvenc_check_codec_support(avctx);
295 av_log(avctx, AV_LOG_VERBOSE, "Codec not supported\n");
299 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
300 if (IS_YUV444(ctx->data_pix_fmt) && ret <= 0) {
301 av_log(avctx, AV_LOG_VERBOSE, "YUV444P not supported\n");
302 return AVERROR(ENOSYS);
305 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOSSLESS_ENCODE);
306 if (ctx->preset >= PRESET_LOSSLESS_DEFAULT && ret <= 0) {
307 av_log(avctx, AV_LOG_VERBOSE, "Lossless encoding not supported\n");
308 return AVERROR(ENOSYS);
311 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
312 if (ret < avctx->width) {
313 av_log(avctx, AV_LOG_VERBOSE, "Width %d exceeds %d\n",
315 return AVERROR(ENOSYS);
318 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
319 if (ret < avctx->height) {
320 av_log(avctx, AV_LOG_VERBOSE, "Height %d exceeds %d\n",
322 return AVERROR(ENOSYS);
325 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
326 if (ret < avctx->max_b_frames) {
327 av_log(avctx, AV_LOG_VERBOSE, "Max B-frames %d exceed %d\n",
328 avctx->max_b_frames, ret);
330 return AVERROR(ENOSYS);
333 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_FIELD_ENCODING);
334 if (ret < 1 && avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
335 av_log(avctx, AV_LOG_VERBOSE,
336 "Interlaced encoding is not supported. Supported level: %d\n",
338 return AVERROR(ENOSYS);
341 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_10BIT_ENCODE);
342 if (IS_10BIT(ctx->data_pix_fmt) && ret <= 0) {
343 av_log(avctx, AV_LOG_VERBOSE, "10 bit encode not supported\n");
344 return AVERROR(ENOSYS);
347 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOOKAHEAD);
348 if (ctx->rc_lookahead > 0 && ret <= 0) {
349 av_log(avctx, AV_LOG_VERBOSE, "RC lookahead not supported\n");
350 return AVERROR(ENOSYS);
353 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_TEMPORAL_AQ);
354 if (ctx->temporal_aq > 0 && ret <= 0) {
355 av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ not supported\n");
356 return AVERROR(ENOSYS);
359 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_WEIGHTED_PREDICTION);
360 if (ctx->weighted_pred > 0 && ret <= 0) {
361 av_log (avctx, AV_LOG_VERBOSE, "Weighted Prediction not supported\n");
362 return AVERROR(ENOSYS);
365 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_CABAC);
366 if (ctx->coder == NV_ENC_H264_ENTROPY_CODING_MODE_CABAC && ret <= 0) {
367 av_log(avctx, AV_LOG_VERBOSE, "CABAC entropy coding not supported\n");
368 return AVERROR(ENOSYS);
374 static av_cold int nvenc_check_device(AVCodecContext *avctx, int idx)
376 NvencContext *ctx = avctx->priv_data;
377 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
378 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
379 char name[128] = { 0};
380 int major, minor, ret;
383 int loglevel = AV_LOG_VERBOSE;
385 if (ctx->device == LIST_DEVICES)
386 loglevel = AV_LOG_INFO;
388 cu_res = dl_fn->cuda_dl->cuDeviceGet(&cu_device, idx);
389 if (cu_res != CUDA_SUCCESS) {
390 av_log(avctx, AV_LOG_ERROR,
391 "Cannot access the CUDA device %d\n",
396 cu_res = dl_fn->cuda_dl->cuDeviceGetName(name, sizeof(name), cu_device);
397 if (cu_res != CUDA_SUCCESS) {
398 av_log(avctx, AV_LOG_ERROR, "cuDeviceGetName failed on device %d\n", idx);
402 cu_res = dl_fn->cuda_dl->cuDeviceComputeCapability(&major, &minor, cu_device);
403 if (cu_res != CUDA_SUCCESS) {
404 av_log(avctx, AV_LOG_ERROR, "cuDeviceComputeCapability failed on device %d\n", idx);
408 av_log(avctx, loglevel, "[ GPU #%d - < %s > has Compute SM %d.%d ]\n", idx, name, major, minor);
409 if (((major << 4) | minor) < NVENC_CAP) {
410 av_log(avctx, loglevel, "does not support NVENC\n");
414 if (ctx->device != idx && ctx->device != ANY_DEVICE)
417 cu_res = dl_fn->cuda_dl->cuCtxCreate(&ctx->cu_context_internal, 0, cu_device);
418 if (cu_res != CUDA_SUCCESS) {
419 av_log(avctx, AV_LOG_FATAL, "Failed creating CUDA context for NVENC: 0x%x\n", (int)cu_res);
423 ctx->cu_context = ctx->cu_context_internal;
425 if ((ret = nvenc_pop_context(avctx)) < 0)
428 if ((ret = nvenc_open_session(avctx)) < 0)
431 if ((ret = nvenc_check_capabilities(avctx)) < 0)
434 av_log(avctx, loglevel, "supports NVENC\n");
436 dl_fn->nvenc_device_count++;
438 if (ctx->device == idx || ctx->device == ANY_DEVICE)
442 if ((ret = nvenc_push_context(avctx)) < 0)
445 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
446 ctx->nvencoder = NULL;
448 if ((ret = nvenc_pop_context(avctx)) < 0)
452 dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal);
453 ctx->cu_context_internal = NULL;
456 return AVERROR(ENOSYS);
459 static av_cold int nvenc_setup_device(AVCodecContext *avctx)
461 NvencContext *ctx = avctx->priv_data;
462 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
464 switch (avctx->codec->id) {
465 case AV_CODEC_ID_H264:
466 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
468 case AV_CODEC_ID_HEVC:
469 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
475 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11 || avctx->hw_frames_ctx || avctx->hw_device_ctx) {
476 AVHWFramesContext *frames_ctx;
477 AVHWDeviceContext *hwdev_ctx;
478 AVCUDADeviceContext *cuda_device_hwctx = NULL;
480 AVD3D11VADeviceContext *d3d11_device_hwctx = NULL;
484 if (avctx->hw_frames_ctx) {
485 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
486 if (frames_ctx->format == AV_PIX_FMT_CUDA)
487 cuda_device_hwctx = frames_ctx->device_ctx->hwctx;
489 else if (frames_ctx->format == AV_PIX_FMT_D3D11)
490 d3d11_device_hwctx = frames_ctx->device_ctx->hwctx;
493 return AVERROR(EINVAL);
494 } else if (avctx->hw_device_ctx) {
495 hwdev_ctx = (AVHWDeviceContext*)avctx->hw_device_ctx->data;
496 if (hwdev_ctx->type == AV_HWDEVICE_TYPE_CUDA)
497 cuda_device_hwctx = hwdev_ctx->hwctx;
499 else if (hwdev_ctx->type == AV_HWDEVICE_TYPE_D3D11VA)
500 d3d11_device_hwctx = hwdev_ctx->hwctx;
503 return AVERROR(EINVAL);
505 return AVERROR(EINVAL);
508 if (cuda_device_hwctx) {
509 ctx->cu_context = cuda_device_hwctx->cuda_ctx;
512 else if (d3d11_device_hwctx) {
513 ctx->d3d11_device = d3d11_device_hwctx->device;
514 ID3D11Device_AddRef(ctx->d3d11_device);
518 ret = nvenc_open_session(avctx);
522 ret = nvenc_check_capabilities(avctx);
524 av_log(avctx, AV_LOG_FATAL, "Provided device doesn't support required NVENC features\n");
528 int i, nb_devices = 0;
530 if ((dl_fn->cuda_dl->cuInit(0)) != CUDA_SUCCESS) {
531 av_log(avctx, AV_LOG_ERROR,
532 "Cannot init CUDA\n");
533 return AVERROR_UNKNOWN;
536 if ((dl_fn->cuda_dl->cuDeviceGetCount(&nb_devices)) != CUDA_SUCCESS) {
537 av_log(avctx, AV_LOG_ERROR,
538 "Cannot enumerate the CUDA devices\n");
539 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 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;
992 static av_cold int nvenc_setup_hevc_config(AVCodecContext *avctx)
994 NvencContext *ctx = avctx->priv_data;
995 NV_ENC_CONFIG *cc = &ctx->encode_config;
996 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
997 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
999 vui->colourMatrix = avctx->colorspace;
1000 vui->colourPrimaries = avctx->color_primaries;
1001 vui->transferCharacteristics = avctx->color_trc;
1002 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
1003 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
1005 vui->colourDescriptionPresentFlag =
1006 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
1008 vui->videoSignalTypePresentFlag =
1009 (vui->colourDescriptionPresentFlag
1010 || vui->videoFormat != 5
1011 || vui->videoFullRangeFlag != 0);
1013 hevc->sliceMode = 3;
1014 hevc->sliceModeData = 1;
1016 hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
1017 hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
1018 hevc->outputAUD = ctx->aud;
1020 if (avctx->refs >= 0) {
1021 /* 0 means "let the hardware decide" */
1022 hevc->maxNumRefFramesInDPB = avctx->refs;
1024 if (avctx->gop_size >= 0) {
1025 hevc->idrPeriod = cc->gopLength;
1028 if (IS_CBR(cc->rcParams.rateControlMode)) {
1029 hevc->outputBufferingPeriodSEI = 1;
1032 hevc->outputPictureTimingSEI = 1;
1034 switch (ctx->profile) {
1035 case NV_ENC_HEVC_PROFILE_MAIN:
1036 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
1037 avctx->profile = FF_PROFILE_HEVC_MAIN;
1039 case NV_ENC_HEVC_PROFILE_MAIN_10:
1040 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1041 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
1043 case NV_ENC_HEVC_PROFILE_REXT:
1044 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1045 avctx->profile = FF_PROFILE_HEVC_REXT;
1049 // force setting profile as main10 if input is 10 bit
1050 if (IS_10BIT(ctx->data_pix_fmt)) {
1051 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1052 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
1055 // force setting profile as rext if input is yuv444
1056 if (IS_YUV444(ctx->data_pix_fmt)) {
1057 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1058 avctx->profile = FF_PROFILE_HEVC_REXT;
1061 hevc->chromaFormatIDC = IS_YUV444(ctx->data_pix_fmt) ? 3 : 1;
1063 hevc->pixelBitDepthMinus8 = IS_10BIT(ctx->data_pix_fmt) ? 2 : 0;
1065 hevc->level = ctx->level;
1067 hevc->tier = ctx->tier;
1072 static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx)
1074 switch (avctx->codec->id) {
1075 case AV_CODEC_ID_H264:
1076 return nvenc_setup_h264_config(avctx);
1077 case AV_CODEC_ID_HEVC:
1078 return nvenc_setup_hevc_config(avctx);
1079 /* Earlier switch/case will return if unknown codec is passed. */
1085 static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
1087 NvencContext *ctx = avctx->priv_data;
1088 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1089 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1091 NV_ENC_PRESET_CONFIG preset_config = { 0 };
1092 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
1093 AVCPBProperties *cpb_props;
1097 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1098 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
1100 ctx->init_encode_params.encodeHeight = avctx->height;
1101 ctx->init_encode_params.encodeWidth = avctx->width;
1103 ctx->init_encode_params.encodeConfig = &ctx->encode_config;
1105 nvenc_map_preset(ctx);
1107 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
1108 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
1110 nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder,
1111 ctx->init_encode_params.encodeGUID,
1112 ctx->init_encode_params.presetGUID,
1114 if (nv_status != NV_ENC_SUCCESS)
1115 return nvenc_print_error(avctx, nv_status, "Cannot get the preset configuration");
1117 memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
1119 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1123 if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0) {
1124 dw*= avctx->sample_aspect_ratio.num;
1125 dh*= avctx->sample_aspect_ratio.den;
1127 av_reduce(&dw, &dh, dw, dh, 1024 * 1024);
1128 ctx->init_encode_params.darHeight = dh;
1129 ctx->init_encode_params.darWidth = dw;
1131 ctx->init_encode_params.frameRateNum = avctx->time_base.den;
1132 ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
1134 ctx->init_encode_params.enableEncodeAsync = 0;
1135 ctx->init_encode_params.enablePTD = 1;
1137 if (ctx->weighted_pred == 1)
1138 ctx->init_encode_params.enableWeightedPrediction = 1;
1140 if (ctx->bluray_compat) {
1142 avctx->refs = FFMIN(FFMAX(avctx->refs, 0), 6);
1143 avctx->max_b_frames = FFMIN(avctx->max_b_frames, 3);
1144 switch (avctx->codec->id) {
1145 case AV_CODEC_ID_H264:
1146 /* maximum level depends on used resolution */
1148 case AV_CODEC_ID_HEVC:
1149 ctx->level = NV_ENC_LEVEL_HEVC_51;
1150 ctx->tier = NV_ENC_TIER_HEVC_HIGH;
1155 if (avctx->gop_size > 0) {
1156 if (avctx->max_b_frames >= 0) {
1157 /* 0 is intra-only, 1 is I/P only, 2 is one B-Frame, 3 two B-frames, and so on. */
1158 ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
1161 ctx->encode_config.gopLength = avctx->gop_size;
1162 } else if (avctx->gop_size == 0) {
1163 ctx->encode_config.frameIntervalP = 0;
1164 ctx->encode_config.gopLength = 1;
1167 ctx->initial_pts[0] = AV_NOPTS_VALUE;
1168 ctx->initial_pts[1] = AV_NOPTS_VALUE;
1170 nvenc_recalc_surfaces(avctx);
1172 nvenc_setup_rate_control(avctx);
1174 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1175 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
1177 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
1180 res = nvenc_setup_codec_config(avctx);
1184 res = nvenc_push_context(avctx);
1188 nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
1190 res = nvenc_pop_context(avctx);
1194 if (nv_status != NV_ENC_SUCCESS) {
1195 return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
1198 if (ctx->encode_config.frameIntervalP > 1)
1199 avctx->has_b_frames = 2;
1201 if (ctx->encode_config.rcParams.averageBitRate > 0)
1202 avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
1204 cpb_props = ff_add_cpb_side_data(avctx);
1206 return AVERROR(ENOMEM);
1207 cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
1208 cpb_props->avg_bitrate = avctx->bit_rate;
1209 cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
1214 static NV_ENC_BUFFER_FORMAT nvenc_map_buffer_format(enum AVPixelFormat pix_fmt)
1217 case AV_PIX_FMT_YUV420P:
1218 return NV_ENC_BUFFER_FORMAT_YV12_PL;
1219 case AV_PIX_FMT_NV12:
1220 return NV_ENC_BUFFER_FORMAT_NV12_PL;
1221 case AV_PIX_FMT_P010:
1222 return NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1223 case AV_PIX_FMT_YUV444P:
1224 return NV_ENC_BUFFER_FORMAT_YUV444_PL;
1225 case AV_PIX_FMT_YUV444P16:
1226 return NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1227 case AV_PIX_FMT_0RGB32:
1228 return NV_ENC_BUFFER_FORMAT_ARGB;
1229 case AV_PIX_FMT_0BGR32:
1230 return NV_ENC_BUFFER_FORMAT_ABGR;
1232 return NV_ENC_BUFFER_FORMAT_UNDEFINED;
1236 static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
1238 NvencContext *ctx = avctx->priv_data;
1239 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1240 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1241 NvencSurface* tmp_surface = &ctx->surfaces[idx];
1243 NVENCSTATUS nv_status;
1244 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
1245 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1247 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1248 ctx->surfaces[idx].in_ref = av_frame_alloc();
1249 if (!ctx->surfaces[idx].in_ref)
1250 return AVERROR(ENOMEM);
1252 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1254 ctx->surfaces[idx].format = nvenc_map_buffer_format(ctx->data_pix_fmt);
1255 if (ctx->surfaces[idx].format == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1256 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1257 av_get_pix_fmt_name(ctx->data_pix_fmt));
1258 return AVERROR(EINVAL);
1261 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1262 allocSurf.width = avctx->width;
1263 allocSurf.height = avctx->height;
1264 allocSurf.bufferFmt = ctx->surfaces[idx].format;
1266 nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
1267 if (nv_status != NV_ENC_SUCCESS) {
1268 return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
1271 ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
1272 ctx->surfaces[idx].width = allocSurf.width;
1273 ctx->surfaces[idx].height = allocSurf.height;
1276 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
1277 if (nv_status != NV_ENC_SUCCESS) {
1278 int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
1279 if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
1280 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
1281 av_frame_free(&ctx->surfaces[idx].in_ref);
1285 ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1286 ctx->surfaces[idx].size = allocOut.size;
1288 av_fifo_generic_write(ctx->unused_surface_queue, &tmp_surface, sizeof(tmp_surface), NULL);
1293 static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx)
1295 NvencContext *ctx = avctx->priv_data;
1296 int i, res = 0, res2;
1298 ctx->surfaces = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->surfaces));
1300 return AVERROR(ENOMEM);
1302 ctx->timestamp_list = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
1303 if (!ctx->timestamp_list)
1304 return AVERROR(ENOMEM);
1306 ctx->unused_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1307 if (!ctx->unused_surface_queue)
1308 return AVERROR(ENOMEM);
1310 ctx->output_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1311 if (!ctx->output_surface_queue)
1312 return AVERROR(ENOMEM);
1313 ctx->output_surface_ready_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1314 if (!ctx->output_surface_ready_queue)
1315 return AVERROR(ENOMEM);
1317 res = nvenc_push_context(avctx);
1321 for (i = 0; i < ctx->nb_surfaces; i++) {
1322 if ((res = nvenc_alloc_surface(avctx, i)) < 0)
1327 res2 = nvenc_pop_context(avctx);
1334 static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
1336 NvencContext *ctx = avctx->priv_data;
1337 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1338 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1340 NVENCSTATUS nv_status;
1341 uint32_t outSize = 0;
1342 char tmpHeader[256];
1343 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1344 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1346 payload.spsppsBuffer = tmpHeader;
1347 payload.inBufferSize = sizeof(tmpHeader);
1348 payload.outSPSPPSPayloadSize = &outSize;
1350 nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
1351 if (nv_status != NV_ENC_SUCCESS) {
1352 return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
1355 avctx->extradata_size = outSize;
1356 avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
1358 if (!avctx->extradata) {
1359 return AVERROR(ENOMEM);
1362 memcpy(avctx->extradata, tmpHeader, outSize);
1367 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
1369 NvencContext *ctx = avctx->priv_data;
1370 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1371 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1374 /* the encoder has to be flushed before it can be closed */
1375 if (ctx->nvencoder) {
1376 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
1377 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
1379 res = nvenc_push_context(avctx);
1383 p_nvenc->nvEncEncodePicture(ctx->nvencoder, ¶ms);
1386 av_fifo_freep(&ctx->timestamp_list);
1387 av_fifo_freep(&ctx->output_surface_ready_queue);
1388 av_fifo_freep(&ctx->output_surface_queue);
1389 av_fifo_freep(&ctx->unused_surface_queue);
1391 if (ctx->surfaces && (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11)) {
1392 for (i = 0; i < ctx->nb_surfaces; ++i) {
1393 if (ctx->surfaces[i].input_surface) {
1394 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->surfaces[i].in_map.mappedResource);
1397 for (i = 0; i < ctx->nb_registered_frames; i++) {
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;
1538 if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1539 for (i = 0; i < ctx->nb_registered_frames; i++) {
1540 if (!ctx->registered_frames[i].mapped) {
1541 if (ctx->registered_frames[i].regptr) {
1542 p_nvenc->nvEncUnregisterResource(ctx->nvencoder,
1543 ctx->registered_frames[i].regptr);
1544 ctx->registered_frames[i].regptr = NULL;
1550 return ctx->nb_registered_frames++;
1553 av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1554 return AVERROR(ENOMEM);
1557 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1559 NvencContext *ctx = avctx->priv_data;
1560 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1561 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1563 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frame->hw_frames_ctx->data;
1564 NV_ENC_REGISTER_RESOURCE reg;
1567 for (i = 0; i < ctx->nb_registered_frames; i++) {
1568 if (avctx->pix_fmt == AV_PIX_FMT_CUDA && ctx->registered_frames[i].ptr == frame->data[0])
1570 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])
1574 idx = nvenc_find_free_reg_resource(avctx);
1578 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1579 reg.width = frames_ctx->width;
1580 reg.height = frames_ctx->height;
1581 reg.pitch = frame->linesize[0];
1582 reg.resourceToRegister = frame->data[0];
1584 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1585 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1587 else if (avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1588 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX;
1589 reg.subResourceIndex = (intptr_t)frame->data[1];
1592 reg.bufferFormat = nvenc_map_buffer_format(frames_ctx->sw_format);
1593 if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1594 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1595 av_get_pix_fmt_name(frames_ctx->sw_format));
1596 return AVERROR(EINVAL);
1599 ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, ®);
1600 if (ret != NV_ENC_SUCCESS) {
1601 nvenc_print_error(avctx, ret, "Error registering an input resource");
1602 return AVERROR_UNKNOWN;
1605 ctx->registered_frames[idx].ptr = frame->data[0];
1606 ctx->registered_frames[idx].ptr_index = reg.subResourceIndex;
1607 ctx->registered_frames[idx].regptr = reg.registeredResource;
1611 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1612 NvencSurface *nvenc_frame)
1614 NvencContext *ctx = avctx->priv_data;
1615 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1616 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1619 NVENCSTATUS nv_status;
1621 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1622 int reg_idx = nvenc_register_frame(avctx, frame);
1624 av_log(avctx, AV_LOG_ERROR, "Could not register an input HW frame\n");
1628 res = av_frame_ref(nvenc_frame->in_ref, frame);
1632 nvenc_frame->in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1633 nvenc_frame->in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1634 nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &nvenc_frame->in_map);
1635 if (nv_status != NV_ENC_SUCCESS) {
1636 av_frame_unref(nvenc_frame->in_ref);
1637 return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
1640 ctx->registered_frames[reg_idx].mapped = 1;
1641 nvenc_frame->reg_idx = reg_idx;
1642 nvenc_frame->input_surface = nvenc_frame->in_map.mappedResource;
1643 nvenc_frame->format = nvenc_frame->in_map.mappedBufferFmt;
1644 nvenc_frame->pitch = frame->linesize[0];
1647 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1649 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1650 lockBufferParams.inputBuffer = nvenc_frame->input_surface;
1652 nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
1653 if (nv_status != NV_ENC_SUCCESS) {
1654 return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
1657 nvenc_frame->pitch = lockBufferParams.pitch;
1658 res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
1660 nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
1661 if (nv_status != NV_ENC_SUCCESS) {
1662 return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
1669 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1670 NV_ENC_PIC_PARAMS *params)
1672 NvencContext *ctx = avctx->priv_data;
1674 switch (avctx->codec->id) {
1675 case AV_CODEC_ID_H264:
1676 params->codecPicParams.h264PicParams.sliceMode =
1677 ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1678 params->codecPicParams.h264PicParams.sliceModeData =
1679 ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1681 case AV_CODEC_ID_HEVC:
1682 params->codecPicParams.hevcPicParams.sliceMode =
1683 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1684 params->codecPicParams.hevcPicParams.sliceModeData =
1685 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1690 static inline void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
1692 av_fifo_generic_write(queue, ×tamp, sizeof(timestamp), NULL);
1695 static inline int64_t timestamp_queue_dequeue(AVFifoBuffer* queue)
1697 int64_t timestamp = AV_NOPTS_VALUE;
1698 if (av_fifo_size(queue) > 0)
1699 av_fifo_generic_read(queue, ×tamp, sizeof(timestamp), NULL);
1704 static int nvenc_set_timestamp(AVCodecContext *avctx,
1705 NV_ENC_LOCK_BITSTREAM *params,
1708 NvencContext *ctx = avctx->priv_data;
1710 pkt->pts = params->outputTimeStamp;
1712 /* generate the first dts by linearly extrapolating the
1713 * first two pts values to the past */
1714 if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
1715 ctx->initial_pts[1] != AV_NOPTS_VALUE) {
1716 int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
1719 if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
1720 (ts0 > 0 && ts1 < INT64_MIN + ts0))
1721 return AVERROR(ERANGE);
1724 if ((delta < 0 && ts0 > INT64_MAX + delta) ||
1725 (delta > 0 && ts0 < INT64_MIN + delta))
1726 return AVERROR(ERANGE);
1727 pkt->dts = ts0 - delta;
1729 ctx->first_packet_output = 1;
1733 pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
1738 static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
1740 NvencContext *ctx = avctx->priv_data;
1741 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1742 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1744 uint32_t slice_mode_data;
1745 uint32_t *slice_offsets = NULL;
1746 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1747 NVENCSTATUS nv_status;
1750 enum AVPictureType pict_type;
1752 switch (avctx->codec->id) {
1753 case AV_CODEC_ID_H264:
1754 slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1756 case AV_CODEC_ID_H265:
1757 slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1760 av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
1761 res = AVERROR(EINVAL);
1764 slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
1769 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1771 lock_params.doNotWait = 0;
1772 lock_params.outputBitstream = tmpoutsurf->output_surface;
1773 lock_params.sliceOffsets = slice_offsets;
1775 nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
1776 if (nv_status != NV_ENC_SUCCESS) {
1777 res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
1781 if (res = ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes,0)) {
1782 p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1786 memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1788 nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1789 if (nv_status != NV_ENC_SUCCESS)
1790 nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
1793 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1794 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, tmpoutsurf->in_map.mappedResource);
1795 av_frame_unref(tmpoutsurf->in_ref);
1796 ctx->registered_frames[tmpoutsurf->reg_idx].mapped = 0;
1798 tmpoutsurf->input_surface = NULL;
1801 switch (lock_params.pictureType) {
1802 case NV_ENC_PIC_TYPE_IDR:
1803 pkt->flags |= AV_PKT_FLAG_KEY;
1804 case NV_ENC_PIC_TYPE_I:
1805 pict_type = AV_PICTURE_TYPE_I;
1807 case NV_ENC_PIC_TYPE_P:
1808 pict_type = AV_PICTURE_TYPE_P;
1810 case NV_ENC_PIC_TYPE_B:
1811 pict_type = AV_PICTURE_TYPE_B;
1813 case NV_ENC_PIC_TYPE_BI:
1814 pict_type = AV_PICTURE_TYPE_BI;
1817 av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
1818 av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
1819 res = AVERROR_EXTERNAL;
1823 #if FF_API_CODED_FRAME
1824 FF_DISABLE_DEPRECATION_WARNINGS
1825 avctx->coded_frame->pict_type = pict_type;
1826 FF_ENABLE_DEPRECATION_WARNINGS
1829 ff_side_data_set_encoder_stats(pkt,
1830 (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
1832 res = nvenc_set_timestamp(avctx, &lock_params, pkt);
1836 av_free(slice_offsets);
1841 timestamp_queue_dequeue(ctx->timestamp_list);
1844 av_free(slice_offsets);
1849 static int output_ready(AVCodecContext *avctx, int flush)
1851 NvencContext *ctx = avctx->priv_data;
1852 int nb_ready, nb_pending;
1854 /* when B-frames are enabled, we wait for two initial timestamps to
1855 * calculate the first dts */
1856 if (!flush && avctx->max_b_frames > 0 &&
1857 (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
1860 nb_ready = av_fifo_size(ctx->output_surface_ready_queue) / sizeof(NvencSurface*);
1861 nb_pending = av_fifo_size(ctx->output_surface_queue) / sizeof(NvencSurface*);
1863 return nb_ready > 0;
1864 return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
1867 int ff_nvenc_send_frame(AVCodecContext *avctx, const AVFrame *frame)
1869 NVENCSTATUS nv_status;
1870 NvencSurface *tmp_out_surf, *in_surf;
1873 NvencContext *ctx = avctx->priv_data;
1874 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1875 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1877 NV_ENC_PIC_PARAMS pic_params = { 0 };
1878 pic_params.version = NV_ENC_PIC_PARAMS_VER;
1880 if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
1881 return AVERROR(EINVAL);
1883 if (ctx->encoder_flushing)
1887 in_surf = get_free_frame(ctx);
1889 return AVERROR(EAGAIN);
1891 res = nvenc_push_context(avctx);
1895 res = nvenc_upload_frame(avctx, frame, in_surf);
1897 res2 = nvenc_pop_context(avctx);
1904 pic_params.inputBuffer = in_surf->input_surface;
1905 pic_params.bufferFmt = in_surf->format;
1906 pic_params.inputWidth = in_surf->width;
1907 pic_params.inputHeight = in_surf->height;
1908 pic_params.inputPitch = in_surf->pitch;
1909 pic_params.outputBitstream = in_surf->output_surface;
1911 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1912 if (frame->top_field_first)
1913 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
1915 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
1917 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1920 if (ctx->forced_idr >= 0 && frame->pict_type == AV_PICTURE_TYPE_I) {
1921 pic_params.encodePicFlags =
1922 ctx->forced_idr ? NV_ENC_PIC_FLAG_FORCEIDR : NV_ENC_PIC_FLAG_FORCEINTRA;
1924 pic_params.encodePicFlags = 0;
1927 pic_params.inputTimeStamp = frame->pts;
1929 nvenc_codec_specific_pic_params(avctx, &pic_params);
1931 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1932 ctx->encoder_flushing = 1;
1935 res = nvenc_push_context(avctx);
1939 nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
1941 res = nvenc_pop_context(avctx);
1945 if (nv_status != NV_ENC_SUCCESS &&
1946 nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
1947 return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
1950 av_fifo_generic_write(ctx->output_surface_queue, &in_surf, sizeof(in_surf), NULL);
1951 timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
1953 if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
1954 ctx->initial_pts[0] = frame->pts;
1955 else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
1956 ctx->initial_pts[1] = frame->pts;
1959 /* all the pending buffers are now ready for output */
1960 if (nv_status == NV_ENC_SUCCESS) {
1961 while (av_fifo_size(ctx->output_surface_queue) > 0) {
1962 av_fifo_generic_read(ctx->output_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
1963 av_fifo_generic_write(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
1970 int ff_nvenc_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
1972 NvencSurface *tmp_out_surf;
1975 NvencContext *ctx = avctx->priv_data;
1977 if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
1978 return AVERROR(EINVAL);
1980 if (output_ready(avctx, ctx->encoder_flushing)) {
1981 av_fifo_generic_read(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
1983 res = nvenc_push_context(avctx);
1987 res = process_output_surface(avctx, pkt, tmp_out_surf);
1989 res2 = nvenc_pop_context(avctx);
1996 av_fifo_generic_write(ctx->unused_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
1997 } else if (ctx->encoder_flushing) {
2000 return AVERROR(EAGAIN);
2006 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
2007 const AVFrame *frame, int *got_packet)
2009 NvencContext *ctx = avctx->priv_data;
2012 if (!ctx->encoder_flushing) {
2013 res = ff_nvenc_send_frame(avctx, frame);
2018 res = ff_nvenc_receive_packet(avctx, pkt);
2019 if (res == AVERROR(EAGAIN) || res == AVERROR_EOF) {
2021 } else if (res < 0) {