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[] = {
51 #define IS_10BIT(pix_fmt) (pix_fmt == AV_PIX_FMT_P010 || \
52 pix_fmt == AV_PIX_FMT_YUV444P16)
54 #define IS_YUV444(pix_fmt) (pix_fmt == AV_PIX_FMT_YUV444P || \
55 pix_fmt == AV_PIX_FMT_YUV444P16)
62 { NV_ENC_SUCCESS, 0, "success" },
63 { NV_ENC_ERR_NO_ENCODE_DEVICE, AVERROR(ENOENT), "no encode device" },
64 { NV_ENC_ERR_UNSUPPORTED_DEVICE, AVERROR(ENOSYS), "unsupported device" },
65 { NV_ENC_ERR_INVALID_ENCODERDEVICE, AVERROR(EINVAL), "invalid encoder device" },
66 { NV_ENC_ERR_INVALID_DEVICE, AVERROR(EINVAL), "invalid device" },
67 { NV_ENC_ERR_DEVICE_NOT_EXIST, AVERROR(EIO), "device does not exist" },
68 { NV_ENC_ERR_INVALID_PTR, AVERROR(EFAULT), "invalid ptr" },
69 { NV_ENC_ERR_INVALID_EVENT, AVERROR(EINVAL), "invalid event" },
70 { NV_ENC_ERR_INVALID_PARAM, AVERROR(EINVAL), "invalid param" },
71 { NV_ENC_ERR_INVALID_CALL, AVERROR(EINVAL), "invalid call" },
72 { NV_ENC_ERR_OUT_OF_MEMORY, AVERROR(ENOMEM), "out of memory" },
73 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED, AVERROR(EINVAL), "encoder not initialized" },
74 { NV_ENC_ERR_UNSUPPORTED_PARAM, AVERROR(ENOSYS), "unsupported param" },
75 { NV_ENC_ERR_LOCK_BUSY, AVERROR(EAGAIN), "lock busy" },
76 { NV_ENC_ERR_NOT_ENOUGH_BUFFER, AVERROR_BUFFER_TOO_SMALL, "not enough buffer"},
77 { NV_ENC_ERR_INVALID_VERSION, AVERROR(EINVAL), "invalid version" },
78 { NV_ENC_ERR_MAP_FAILED, AVERROR(EIO), "map failed" },
79 { NV_ENC_ERR_NEED_MORE_INPUT, AVERROR(EAGAIN), "need more input" },
80 { NV_ENC_ERR_ENCODER_BUSY, AVERROR(EAGAIN), "encoder busy" },
81 { NV_ENC_ERR_EVENT_NOT_REGISTERD, AVERROR(EBADF), "event not registered" },
82 { NV_ENC_ERR_GENERIC, AVERROR_UNKNOWN, "generic error" },
83 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY, AVERROR(EINVAL), "incompatible client key" },
84 { NV_ENC_ERR_UNIMPLEMENTED, AVERROR(ENOSYS), "unimplemented" },
85 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO), "resource register failed" },
86 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED, AVERROR(EBADF), "resource not registered" },
87 { NV_ENC_ERR_RESOURCE_NOT_MAPPED, AVERROR(EBADF), "resource not mapped" },
90 static int nvenc_map_error(NVENCSTATUS err, const char **desc)
93 for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
94 if (nvenc_errors[i].nverr == err) {
96 *desc = nvenc_errors[i].desc;
97 return nvenc_errors[i].averr;
101 *desc = "unknown error";
102 return AVERROR_UNKNOWN;
105 static int nvenc_print_error(void *log_ctx, NVENCSTATUS err,
106 const char *error_string)
110 ret = nvenc_map_error(err, &desc);
111 av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
115 static void nvenc_print_driver_requirement(AVCodecContext *avctx, int level)
117 #if defined(_WIN32) || defined(__CYGWIN__)
118 const char *minver = "378.66";
120 const char *minver = "378.13";
122 av_log(avctx, level, "The minimum required Nvidia driver for nvenc is %s or newer\n", minver);
125 static av_cold int nvenc_load_libraries(AVCodecContext *avctx)
127 NvencContext *ctx = avctx->priv_data;
128 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
130 uint32_t nvenc_max_ver;
133 ret = cuda_load_functions(&dl_fn->cuda_dl);
137 ret = nvenc_load_functions(&dl_fn->nvenc_dl);
139 nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
143 err = dl_fn->nvenc_dl->NvEncodeAPIGetMaxSupportedVersion(&nvenc_max_ver);
144 if (err != NV_ENC_SUCCESS)
145 return nvenc_print_error(avctx, err, "Failed to query nvenc max version");
147 av_log(avctx, AV_LOG_VERBOSE, "Loaded Nvenc version %d.%d\n", nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
149 if ((NVENCAPI_MAJOR_VERSION << 4 | NVENCAPI_MINOR_VERSION) > nvenc_max_ver) {
150 av_log(avctx, AV_LOG_ERROR, "Driver does not support the required nvenc API version. "
151 "Required: %d.%d Found: %d.%d\n",
152 NVENCAPI_MAJOR_VERSION, NVENCAPI_MINOR_VERSION,
153 nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
154 nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
155 return AVERROR(ENOSYS);
158 dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
160 err = dl_fn->nvenc_dl->NvEncodeAPICreateInstance(&dl_fn->nvenc_funcs);
161 if (err != NV_ENC_SUCCESS)
162 return nvenc_print_error(avctx, err, "Failed to create nvenc instance");
164 av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
169 static av_cold int nvenc_open_session(AVCodecContext *avctx)
171 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
172 NvencContext *ctx = avctx->priv_data;
173 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
176 params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
177 params.apiVersion = NVENCAPI_VERSION;
178 params.device = ctx->cu_context;
179 params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
181 ret = p_nvenc->nvEncOpenEncodeSessionEx(¶ms, &ctx->nvencoder);
182 if (ret != NV_ENC_SUCCESS) {
183 ctx->nvencoder = NULL;
184 return nvenc_print_error(avctx, ret, "OpenEncodeSessionEx failed");
190 static int nvenc_check_codec_support(AVCodecContext *avctx)
192 NvencContext *ctx = avctx->priv_data;
193 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
194 int i, ret, count = 0;
197 ret = p_nvenc->nvEncGetEncodeGUIDCount(ctx->nvencoder, &count);
199 if (ret != NV_ENC_SUCCESS || !count)
200 return AVERROR(ENOSYS);
202 guids = av_malloc(count * sizeof(GUID));
204 return AVERROR(ENOMEM);
206 ret = p_nvenc->nvEncGetEncodeGUIDs(ctx->nvencoder, guids, count, &count);
207 if (ret != NV_ENC_SUCCESS) {
208 ret = AVERROR(ENOSYS);
212 ret = AVERROR(ENOSYS);
213 for (i = 0; i < count; i++) {
214 if (!memcmp(&guids[i], &ctx->init_encode_params.encodeGUID, sizeof(*guids))) {
226 static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
228 NvencContext *ctx = avctx->priv_data;
229 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
230 NV_ENC_CAPS_PARAM params = { 0 };
233 params.version = NV_ENC_CAPS_PARAM_VER;
234 params.capsToQuery = cap;
236 ret = p_nvenc->nvEncGetEncodeCaps(ctx->nvencoder, ctx->init_encode_params.encodeGUID, ¶ms, &val);
238 if (ret == NV_ENC_SUCCESS)
243 static int nvenc_check_capabilities(AVCodecContext *avctx)
245 NvencContext *ctx = avctx->priv_data;
248 ret = nvenc_check_codec_support(avctx);
250 av_log(avctx, AV_LOG_VERBOSE, "Codec not supported\n");
254 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
255 if (IS_YUV444(ctx->data_pix_fmt) && ret <= 0) {
256 av_log(avctx, AV_LOG_VERBOSE, "YUV444P not supported\n");
257 return AVERROR(ENOSYS);
260 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOSSLESS_ENCODE);
261 if (ctx->preset >= PRESET_LOSSLESS_DEFAULT && ret <= 0) {
262 av_log(avctx, AV_LOG_VERBOSE, "Lossless encoding not supported\n");
263 return AVERROR(ENOSYS);
266 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
267 if (ret < avctx->width) {
268 av_log(avctx, AV_LOG_VERBOSE, "Width %d exceeds %d\n",
270 return AVERROR(ENOSYS);
273 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
274 if (ret < avctx->height) {
275 av_log(avctx, AV_LOG_VERBOSE, "Height %d exceeds %d\n",
277 return AVERROR(ENOSYS);
280 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
281 if (ret < avctx->max_b_frames) {
282 av_log(avctx, AV_LOG_VERBOSE, "Max B-frames %d exceed %d\n",
283 avctx->max_b_frames, ret);
285 return AVERROR(ENOSYS);
288 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_FIELD_ENCODING);
289 if (ret < 1 && avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
290 av_log(avctx, AV_LOG_VERBOSE,
291 "Interlaced encoding is not supported. Supported level: %d\n",
293 return AVERROR(ENOSYS);
296 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_10BIT_ENCODE);
297 if (IS_10BIT(ctx->data_pix_fmt) && ret <= 0) {
298 av_log(avctx, AV_LOG_VERBOSE, "10 bit encode not supported\n");
299 return AVERROR(ENOSYS);
302 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOOKAHEAD);
303 if (ctx->rc_lookahead > 0 && ret <= 0) {
304 av_log(avctx, AV_LOG_VERBOSE, "RC lookahead not supported\n");
305 return AVERROR(ENOSYS);
308 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_TEMPORAL_AQ);
309 if (ctx->temporal_aq > 0 && ret <= 0) {
310 av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ not supported\n");
311 return AVERROR(ENOSYS);
314 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_WEIGHTED_PREDICTION);
315 if (ctx->weighted_pred > 0 && ret <= 0) {
316 av_log (avctx, AV_LOG_VERBOSE, "Weighted Prediction not supported\n");
317 return AVERROR(ENOSYS);
320 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_CABAC);
321 if (ctx->coder == NV_ENC_H264_ENTROPY_CODING_MODE_CABAC && ret <= 0) {
322 av_log(avctx, AV_LOG_VERBOSE, "CABAC entropy coding not supported\n");
323 return AVERROR(ENOSYS);
329 static av_cold int nvenc_check_device(AVCodecContext *avctx, int idx)
331 NvencContext *ctx = avctx->priv_data;
332 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
333 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
334 char name[128] = { 0};
335 int major, minor, ret;
339 int loglevel = AV_LOG_VERBOSE;
341 if (ctx->device == LIST_DEVICES)
342 loglevel = AV_LOG_INFO;
344 cu_res = dl_fn->cuda_dl->cuDeviceGet(&cu_device, idx);
345 if (cu_res != CUDA_SUCCESS) {
346 av_log(avctx, AV_LOG_ERROR,
347 "Cannot access the CUDA device %d\n",
352 cu_res = dl_fn->cuda_dl->cuDeviceGetName(name, sizeof(name), cu_device);
353 if (cu_res != CUDA_SUCCESS) {
354 av_log(avctx, AV_LOG_ERROR, "cuDeviceGetName failed on device %d\n", idx);
358 cu_res = dl_fn->cuda_dl->cuDeviceComputeCapability(&major, &minor, cu_device);
359 if (cu_res != CUDA_SUCCESS) {
360 av_log(avctx, AV_LOG_ERROR, "cuDeviceComputeCapability failed on device %d\n", idx);
364 av_log(avctx, loglevel, "[ GPU #%d - < %s > has Compute SM %d.%d ]\n", idx, name, major, minor);
365 if (((major << 4) | minor) < NVENC_CAP) {
366 av_log(avctx, loglevel, "does not support NVENC\n");
370 if (ctx->device != idx && ctx->device != ANY_DEVICE)
373 cu_res = dl_fn->cuda_dl->cuCtxCreate(&ctx->cu_context_internal, 0, cu_device);
374 if (cu_res != CUDA_SUCCESS) {
375 av_log(avctx, AV_LOG_FATAL, "Failed creating CUDA context for NVENC: 0x%x\n", (int)cu_res);
379 ctx->cu_context = ctx->cu_context_internal;
381 cu_res = dl_fn->cuda_dl->cuCtxPopCurrent(&dummy);
382 if (cu_res != CUDA_SUCCESS) {
383 av_log(avctx, AV_LOG_FATAL, "Failed popping CUDA context: 0x%x\n", (int)cu_res);
387 if ((ret = nvenc_open_session(avctx)) < 0)
390 if ((ret = nvenc_check_capabilities(avctx)) < 0)
393 av_log(avctx, loglevel, "supports NVENC\n");
395 dl_fn->nvenc_device_count++;
397 if (ctx->device == idx || ctx->device == ANY_DEVICE)
401 cu_res = dl_fn->cuda_dl->cuCtxPushCurrent(ctx->cu_context);
402 if (cu_res != CUDA_SUCCESS) {
403 av_log(avctx, AV_LOG_ERROR, "cuCtxPushCurrent failed\n");
404 return AVERROR_EXTERNAL;
407 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
408 ctx->nvencoder = NULL;
410 cu_res = dl_fn->cuda_dl->cuCtxPopCurrent(&dummy);
411 if (cu_res != CUDA_SUCCESS) {
412 av_log(avctx, AV_LOG_ERROR, "cuCtxPopCurrent failed\n");
413 return AVERROR_EXTERNAL;
417 dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal);
418 ctx->cu_context_internal = NULL;
421 return AVERROR(ENOSYS);
424 static av_cold int nvenc_setup_device(AVCodecContext *avctx)
426 NvencContext *ctx = avctx->priv_data;
427 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
429 switch (avctx->codec->id) {
430 case AV_CODEC_ID_H264:
431 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
433 case AV_CODEC_ID_HEVC:
434 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
440 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->hw_frames_ctx || avctx->hw_device_ctx) {
441 AVHWFramesContext *frames_ctx;
442 AVHWDeviceContext *hwdev_ctx;
443 AVCUDADeviceContext *device_hwctx;
446 if (avctx->hw_frames_ctx) {
447 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
448 device_hwctx = frames_ctx->device_ctx->hwctx;
449 } else if (avctx->hw_device_ctx) {
450 hwdev_ctx = (AVHWDeviceContext*)avctx->hw_device_ctx->data;
451 device_hwctx = hwdev_ctx->hwctx;
453 return AVERROR(EINVAL);
456 ctx->cu_context = device_hwctx->cuda_ctx;
458 ret = nvenc_open_session(avctx);
462 ret = nvenc_check_capabilities(avctx);
464 av_log(avctx, AV_LOG_FATAL, "Provided device doesn't support required NVENC features\n");
468 int i, nb_devices = 0;
470 if ((dl_fn->cuda_dl->cuInit(0)) != CUDA_SUCCESS) {
471 av_log(avctx, AV_LOG_ERROR,
472 "Cannot init CUDA\n");
473 return AVERROR_UNKNOWN;
476 if ((dl_fn->cuda_dl->cuDeviceGetCount(&nb_devices)) != CUDA_SUCCESS) {
477 av_log(avctx, AV_LOG_ERROR,
478 "Cannot enumerate the CUDA devices\n");
479 return AVERROR_UNKNOWN;
483 av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
484 return AVERROR_EXTERNAL;
487 av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", nb_devices);
489 dl_fn->nvenc_device_count = 0;
490 for (i = 0; i < nb_devices; ++i) {
491 if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
495 if (ctx->device == LIST_DEVICES)
498 if (!dl_fn->nvenc_device_count) {
499 av_log(avctx, AV_LOG_FATAL, "No NVENC capable devices found\n");
500 return AVERROR_EXTERNAL;
503 av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->device, nb_devices);
504 return AVERROR(EINVAL);
510 typedef struct GUIDTuple {
515 #define PRESET_ALIAS(alias, name, ...) \
516 [PRESET_ ## alias] = { NV_ENC_PRESET_ ## name ## _GUID, __VA_ARGS__ }
518 #define PRESET(name, ...) PRESET_ALIAS(name, name, __VA_ARGS__)
520 static void nvenc_map_preset(NvencContext *ctx)
522 GUIDTuple presets[] = {
527 PRESET_ALIAS(SLOW, HQ, NVENC_TWO_PASSES),
528 PRESET_ALIAS(MEDIUM, HQ, NVENC_ONE_PASS),
529 PRESET_ALIAS(FAST, HP, NVENC_ONE_PASS),
530 PRESET(LOW_LATENCY_DEFAULT, NVENC_LOWLATENCY),
531 PRESET(LOW_LATENCY_HP, NVENC_LOWLATENCY),
532 PRESET(LOW_LATENCY_HQ, NVENC_LOWLATENCY),
533 PRESET(LOSSLESS_DEFAULT, NVENC_LOSSLESS),
534 PRESET(LOSSLESS_HP, NVENC_LOSSLESS),
537 GUIDTuple *t = &presets[ctx->preset];
539 ctx->init_encode_params.presetGUID = t->guid;
540 ctx->flags = t->flags;
546 static av_cold void set_constqp(AVCodecContext *avctx)
548 NvencContext *ctx = avctx->priv_data;
549 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
551 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
553 if (ctx->init_qp_p >= 0) {
554 rc->constQP.qpInterP = ctx->init_qp_p;
555 if (ctx->init_qp_i >= 0 && ctx->init_qp_b >= 0) {
556 rc->constQP.qpIntra = ctx->init_qp_i;
557 rc->constQP.qpInterB = ctx->init_qp_b;
558 } else if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
559 rc->constQP.qpIntra = av_clip(
560 rc->constQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
561 rc->constQP.qpInterB = av_clip(
562 rc->constQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
564 rc->constQP.qpIntra = rc->constQP.qpInterP;
565 rc->constQP.qpInterB = rc->constQP.qpInterP;
567 } else if (ctx->cqp >= 0) {
568 rc->constQP.qpInterP = rc->constQP.qpInterB = rc->constQP.qpIntra = ctx->cqp;
569 if (avctx->b_quant_factor != 0.0)
570 rc->constQP.qpInterB = av_clip(ctx->cqp * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
571 if (avctx->i_quant_factor != 0.0)
572 rc->constQP.qpIntra = av_clip(ctx->cqp * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
579 static av_cold void set_vbr(AVCodecContext *avctx)
581 NvencContext *ctx = avctx->priv_data;
582 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
585 if (avctx->qmin >= 0 && avctx->qmax >= 0) {
589 rc->minQP.qpInterB = avctx->qmin;
590 rc->minQP.qpInterP = avctx->qmin;
591 rc->minQP.qpIntra = avctx->qmin;
593 rc->maxQP.qpInterB = avctx->qmax;
594 rc->maxQP.qpInterP = avctx->qmax;
595 rc->maxQP.qpIntra = avctx->qmax;
597 qp_inter_p = (avctx->qmax + 3 * avctx->qmin) / 4; // biased towards Qmin
598 } else if (avctx->qmin >= 0) {
601 rc->minQP.qpInterB = avctx->qmin;
602 rc->minQP.qpInterP = avctx->qmin;
603 rc->minQP.qpIntra = avctx->qmin;
605 qp_inter_p = avctx->qmin;
607 qp_inter_p = 26; // default to 26
610 rc->enableInitialRCQP = 1;
612 if (ctx->init_qp_p < 0) {
613 rc->initialRCQP.qpInterP = qp_inter_p;
615 rc->initialRCQP.qpInterP = ctx->init_qp_p;
618 if (ctx->init_qp_i < 0) {
619 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
620 rc->initialRCQP.qpIntra = av_clip(
621 rc->initialRCQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
623 rc->initialRCQP.qpIntra = rc->initialRCQP.qpInterP;
626 rc->initialRCQP.qpIntra = ctx->init_qp_i;
629 if (ctx->init_qp_b < 0) {
630 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
631 rc->initialRCQP.qpInterB = av_clip(
632 rc->initialRCQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
634 rc->initialRCQP.qpInterB = rc->initialRCQP.qpInterP;
637 rc->initialRCQP.qpInterB = ctx->init_qp_b;
641 static av_cold void set_lossless(AVCodecContext *avctx)
643 NvencContext *ctx = avctx->priv_data;
644 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
646 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
647 rc->constQP.qpInterB = 0;
648 rc->constQP.qpInterP = 0;
649 rc->constQP.qpIntra = 0;
655 static void nvenc_override_rate_control(AVCodecContext *avctx)
657 NvencContext *ctx = avctx->priv_data;
658 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
661 case NV_ENC_PARAMS_RC_CONSTQP:
664 case NV_ENC_PARAMS_RC_VBR_MINQP:
665 if (avctx->qmin < 0) {
666 av_log(avctx, AV_LOG_WARNING,
667 "The variable bitrate rate-control requires "
668 "the 'qmin' option set.\n");
673 case NV_ENC_PARAMS_RC_VBR_HQ:
674 case NV_ENC_PARAMS_RC_VBR:
677 case NV_ENC_PARAMS_RC_CBR:
678 case NV_ENC_PARAMS_RC_CBR_HQ:
679 case NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ:
683 rc->rateControlMode = ctx->rc;
686 static av_cold int nvenc_recalc_surfaces(AVCodecContext *avctx)
688 NvencContext *ctx = avctx->priv_data;
689 // default minimum of 4 surfaces
690 // multiply by 2 for number of NVENCs on gpu (hardcode to 2)
691 // another multiply by 2 to avoid blocking next PBB group
692 int nb_surfaces = FFMAX(4, ctx->encode_config.frameIntervalP * 2 * 2);
695 if (ctx->rc_lookahead > 0) {
696 // +1 is to account for lkd_bound calculation later
697 // +4 is to allow sufficient pipelining with lookahead
698 nb_surfaces = FFMAX(1, FFMAX(nb_surfaces, ctx->rc_lookahead + ctx->encode_config.frameIntervalP + 1 + 4));
699 if (nb_surfaces > ctx->nb_surfaces && ctx->nb_surfaces > 0)
701 av_log(avctx, AV_LOG_WARNING,
702 "Defined rc_lookahead requires more surfaces, "
703 "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
705 ctx->nb_surfaces = FFMAX(nb_surfaces, ctx->nb_surfaces);
707 if (ctx->encode_config.frameIntervalP > 1 && ctx->nb_surfaces < nb_surfaces && ctx->nb_surfaces > 0)
709 av_log(avctx, AV_LOG_WARNING,
710 "Defined b-frame requires more surfaces, "
711 "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
712 ctx->nb_surfaces = FFMAX(ctx->nb_surfaces, nb_surfaces);
714 else if (ctx->nb_surfaces <= 0)
715 ctx->nb_surfaces = nb_surfaces;
716 // otherwise use user specified value
719 ctx->nb_surfaces = FFMAX(1, FFMIN(MAX_REGISTERED_FRAMES, ctx->nb_surfaces));
720 ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
725 static av_cold void nvenc_setup_rate_control(AVCodecContext *avctx)
727 NvencContext *ctx = avctx->priv_data;
729 if (avctx->global_quality > 0)
730 av_log(avctx, AV_LOG_WARNING, "Using global_quality with nvenc is deprecated. Use qp instead.\n");
732 if (ctx->cqp < 0 && avctx->global_quality > 0)
733 ctx->cqp = avctx->global_quality;
735 if (avctx->bit_rate > 0) {
736 ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
737 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
738 ctx->encode_config.rcParams.maxBitRate = ctx->encode_config.rcParams.averageBitRate;
741 if (avctx->rc_max_rate > 0)
742 ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
745 if (ctx->flags & NVENC_ONE_PASS)
747 if (ctx->flags & NVENC_TWO_PASSES)
750 if (ctx->twopass < 0)
751 ctx->twopass = (ctx->flags & NVENC_LOWLATENCY) != 0;
755 ctx->rc = NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ;
757 ctx->rc = NV_ENC_PARAMS_RC_CBR;
759 } else if (ctx->cqp >= 0) {
760 ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
761 } else if (ctx->twopass) {
762 ctx->rc = NV_ENC_PARAMS_RC_VBR_HQ;
763 } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
764 ctx->rc = NV_ENC_PARAMS_RC_VBR_MINQP;
768 if (ctx->rc >= 0 && ctx->rc & RC_MODE_DEPRECATED) {
769 av_log(avctx, AV_LOG_WARNING, "Specified rc mode is deprecated.\n");
770 av_log(avctx, AV_LOG_WARNING, "\tll_2pass_quality -> cbr_ld_hq\n");
771 av_log(avctx, AV_LOG_WARNING, "\tll_2pass_size -> cbr_hq\n");
772 av_log(avctx, AV_LOG_WARNING, "\tvbr_2pass -> vbr_hq\n");
773 av_log(avctx, AV_LOG_WARNING, "\tvbr_minqp -> (no replacement)\n");
775 ctx->rc &= ~RC_MODE_DEPRECATED;
778 if (ctx->flags & NVENC_LOSSLESS) {
780 } else if (ctx->rc >= 0) {
781 nvenc_override_rate_control(avctx);
783 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
787 if (avctx->rc_buffer_size > 0) {
788 ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
789 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
790 ctx->encode_config.rcParams.vbvBufferSize = 2 * ctx->encode_config.rcParams.averageBitRate;
794 ctx->encode_config.rcParams.enableAQ = 1;
795 ctx->encode_config.rcParams.aqStrength = ctx->aq_strength;
796 av_log(avctx, AV_LOG_VERBOSE, "AQ enabled.\n");
799 if (ctx->temporal_aq) {
800 ctx->encode_config.rcParams.enableTemporalAQ = 1;
801 av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ enabled.\n");
804 if (ctx->rc_lookahead > 0) {
805 int lkd_bound = FFMIN(ctx->nb_surfaces, ctx->async_depth) -
806 ctx->encode_config.frameIntervalP - 4;
809 av_log(avctx, AV_LOG_WARNING,
810 "Lookahead not enabled. Increase buffer delay (-delay).\n");
812 ctx->encode_config.rcParams.enableLookahead = 1;
813 ctx->encode_config.rcParams.lookaheadDepth = av_clip(ctx->rc_lookahead, 0, lkd_bound);
814 ctx->encode_config.rcParams.disableIadapt = ctx->no_scenecut;
815 ctx->encode_config.rcParams.disableBadapt = !ctx->b_adapt;
816 av_log(avctx, AV_LOG_VERBOSE,
817 "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",
818 ctx->encode_config.rcParams.lookaheadDepth,
819 ctx->encode_config.rcParams.disableIadapt ? "disabled" : "enabled",
820 ctx->encode_config.rcParams.disableBadapt ? "disabled" : "enabled");
824 if (ctx->strict_gop) {
825 ctx->encode_config.rcParams.strictGOPTarget = 1;
826 av_log(avctx, AV_LOG_VERBOSE, "Strict GOP target enabled.\n");
830 ctx->encode_config.rcParams.enableNonRefP = 1;
832 if (ctx->zerolatency)
833 ctx->encode_config.rcParams.zeroReorderDelay = 1;
837 //convert from float to fixed point 8.8
838 int tmp_quality = (int)(ctx->quality * 256.0f);
839 ctx->encode_config.rcParams.targetQuality = (uint8_t)(tmp_quality >> 8);
840 ctx->encode_config.rcParams.targetQualityLSB = (uint8_t)(tmp_quality & 0xff);
844 static av_cold int nvenc_setup_h264_config(AVCodecContext *avctx)
846 NvencContext *ctx = avctx->priv_data;
847 NV_ENC_CONFIG *cc = &ctx->encode_config;
848 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
849 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
851 vui->colourMatrix = avctx->colorspace;
852 vui->colourPrimaries = avctx->color_primaries;
853 vui->transferCharacteristics = avctx->color_trc;
854 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
855 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
857 vui->colourDescriptionPresentFlag =
858 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
860 vui->videoSignalTypePresentFlag =
861 (vui->colourDescriptionPresentFlag
862 || vui->videoFormat != 5
863 || vui->videoFullRangeFlag != 0);
866 h264->sliceModeData = 1;
868 h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
869 h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
870 h264->outputAUD = ctx->aud;
872 if (avctx->refs >= 0) {
873 /* 0 means "let the hardware decide" */
874 h264->maxNumRefFrames = avctx->refs;
876 if (avctx->gop_size >= 0) {
877 h264->idrPeriod = cc->gopLength;
880 if (IS_CBR(cc->rcParams.rateControlMode)) {
881 h264->outputBufferingPeriodSEI = 1;
884 h264->outputPictureTimingSEI = 1;
886 if (cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ ||
887 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_HQ ||
888 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_VBR_HQ) {
889 h264->adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
890 h264->fmoMode = NV_ENC_H264_FMO_DISABLE;
893 if (ctx->flags & NVENC_LOSSLESS) {
894 h264->qpPrimeYZeroTransformBypassFlag = 1;
896 switch(ctx->profile) {
897 case NV_ENC_H264_PROFILE_BASELINE:
898 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
899 avctx->profile = FF_PROFILE_H264_BASELINE;
901 case NV_ENC_H264_PROFILE_MAIN:
902 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
903 avctx->profile = FF_PROFILE_H264_MAIN;
905 case NV_ENC_H264_PROFILE_HIGH:
906 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
907 avctx->profile = FF_PROFILE_H264_HIGH;
909 case NV_ENC_H264_PROFILE_HIGH_444P:
910 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
911 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
916 // force setting profile as high444p if input is AV_PIX_FMT_YUV444P
917 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P) {
918 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
919 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
922 h264->chromaFormatIDC = avctx->profile == FF_PROFILE_H264_HIGH_444_PREDICTIVE ? 3 : 1;
924 h264->level = ctx->level;
927 h264->entropyCodingMode = ctx->coder;
932 static av_cold int nvenc_setup_hevc_config(AVCodecContext *avctx)
934 NvencContext *ctx = avctx->priv_data;
935 NV_ENC_CONFIG *cc = &ctx->encode_config;
936 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
937 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
939 vui->colourMatrix = avctx->colorspace;
940 vui->colourPrimaries = avctx->color_primaries;
941 vui->transferCharacteristics = avctx->color_trc;
942 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
943 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
945 vui->colourDescriptionPresentFlag =
946 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
948 vui->videoSignalTypePresentFlag =
949 (vui->colourDescriptionPresentFlag
950 || vui->videoFormat != 5
951 || vui->videoFullRangeFlag != 0);
954 hevc->sliceModeData = 1;
956 hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
957 hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
958 hevc->outputAUD = ctx->aud;
960 if (avctx->refs >= 0) {
961 /* 0 means "let the hardware decide" */
962 hevc->maxNumRefFramesInDPB = avctx->refs;
964 if (avctx->gop_size >= 0) {
965 hevc->idrPeriod = cc->gopLength;
968 if (IS_CBR(cc->rcParams.rateControlMode)) {
969 hevc->outputBufferingPeriodSEI = 1;
972 hevc->outputPictureTimingSEI = 1;
974 switch (ctx->profile) {
975 case NV_ENC_HEVC_PROFILE_MAIN:
976 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
977 avctx->profile = FF_PROFILE_HEVC_MAIN;
979 case NV_ENC_HEVC_PROFILE_MAIN_10:
980 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
981 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
983 case NV_ENC_HEVC_PROFILE_REXT:
984 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
985 avctx->profile = FF_PROFILE_HEVC_REXT;
989 // force setting profile as main10 if input is 10 bit
990 if (IS_10BIT(ctx->data_pix_fmt)) {
991 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
992 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
995 // force setting profile as rext if input is yuv444
996 if (IS_YUV444(ctx->data_pix_fmt)) {
997 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
998 avctx->profile = FF_PROFILE_HEVC_REXT;
1001 hevc->chromaFormatIDC = IS_YUV444(ctx->data_pix_fmt) ? 3 : 1;
1003 hevc->pixelBitDepthMinus8 = IS_10BIT(ctx->data_pix_fmt) ? 2 : 0;
1005 hevc->level = ctx->level;
1007 hevc->tier = ctx->tier;
1012 static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx)
1014 switch (avctx->codec->id) {
1015 case AV_CODEC_ID_H264:
1016 return nvenc_setup_h264_config(avctx);
1017 case AV_CODEC_ID_HEVC:
1018 return nvenc_setup_hevc_config(avctx);
1019 /* Earlier switch/case will return if unknown codec is passed. */
1025 static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
1027 NvencContext *ctx = avctx->priv_data;
1028 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1029 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1031 NV_ENC_PRESET_CONFIG preset_config = { 0 };
1032 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
1033 AVCPBProperties *cpb_props;
1039 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1040 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
1042 ctx->init_encode_params.encodeHeight = avctx->height;
1043 ctx->init_encode_params.encodeWidth = avctx->width;
1045 ctx->init_encode_params.encodeConfig = &ctx->encode_config;
1047 nvenc_map_preset(ctx);
1049 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
1050 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
1052 nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder,
1053 ctx->init_encode_params.encodeGUID,
1054 ctx->init_encode_params.presetGUID,
1056 if (nv_status != NV_ENC_SUCCESS)
1057 return nvenc_print_error(avctx, nv_status, "Cannot get the preset configuration");
1059 memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
1061 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1065 if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0) {
1066 dw*= avctx->sample_aspect_ratio.num;
1067 dh*= avctx->sample_aspect_ratio.den;
1069 av_reduce(&dw, &dh, dw, dh, 1024 * 1024);
1070 ctx->init_encode_params.darHeight = dh;
1071 ctx->init_encode_params.darWidth = dw;
1073 ctx->init_encode_params.frameRateNum = avctx->time_base.den;
1074 ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
1076 ctx->init_encode_params.enableEncodeAsync = 0;
1077 ctx->init_encode_params.enablePTD = 1;
1079 if (ctx->weighted_pred == 1)
1080 ctx->init_encode_params.enableWeightedPrediction = 1;
1082 if (ctx->bluray_compat) {
1084 avctx->refs = FFMIN(FFMAX(avctx->refs, 0), 6);
1085 avctx->max_b_frames = FFMIN(avctx->max_b_frames, 3);
1086 switch (avctx->codec->id) {
1087 case AV_CODEC_ID_H264:
1088 /* maximum level depends on used resolution */
1090 case AV_CODEC_ID_HEVC:
1091 ctx->level = NV_ENC_LEVEL_HEVC_51;
1092 ctx->tier = NV_ENC_TIER_HEVC_HIGH;
1097 if (avctx->gop_size > 0) {
1098 if (avctx->max_b_frames >= 0) {
1099 /* 0 is intra-only, 1 is I/P only, 2 is one B-Frame, 3 two B-frames, and so on. */
1100 ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
1103 ctx->encode_config.gopLength = avctx->gop_size;
1104 } else if (avctx->gop_size == 0) {
1105 ctx->encode_config.frameIntervalP = 0;
1106 ctx->encode_config.gopLength = 1;
1109 ctx->initial_pts[0] = AV_NOPTS_VALUE;
1110 ctx->initial_pts[1] = AV_NOPTS_VALUE;
1112 nvenc_recalc_surfaces(avctx);
1114 nvenc_setup_rate_control(avctx);
1116 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1117 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
1119 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
1122 res = nvenc_setup_codec_config(avctx);
1126 cu_res = dl_fn->cuda_dl->cuCtxPushCurrent(ctx->cu_context);
1127 if (cu_res != CUDA_SUCCESS) {
1128 av_log(avctx, AV_LOG_ERROR, "cuCtxPushCurrent failed\n");
1129 return AVERROR_EXTERNAL;
1132 nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
1134 cu_res = dl_fn->cuda_dl->cuCtxPopCurrent(&dummy);
1135 if (cu_res != CUDA_SUCCESS) {
1136 av_log(avctx, AV_LOG_ERROR, "cuCtxPopCurrent failed\n");
1137 return AVERROR_EXTERNAL;
1140 if (nv_status != NV_ENC_SUCCESS) {
1141 return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
1144 if (ctx->encode_config.frameIntervalP > 1)
1145 avctx->has_b_frames = 2;
1147 if (ctx->encode_config.rcParams.averageBitRate > 0)
1148 avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
1150 cpb_props = ff_add_cpb_side_data(avctx);
1152 return AVERROR(ENOMEM);
1153 cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
1154 cpb_props->avg_bitrate = avctx->bit_rate;
1155 cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
1160 static NV_ENC_BUFFER_FORMAT nvenc_map_buffer_format(enum AVPixelFormat pix_fmt)
1163 case AV_PIX_FMT_YUV420P:
1164 return NV_ENC_BUFFER_FORMAT_YV12_PL;
1165 case AV_PIX_FMT_NV12:
1166 return NV_ENC_BUFFER_FORMAT_NV12_PL;
1167 case AV_PIX_FMT_P010:
1168 return NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1169 case AV_PIX_FMT_YUV444P:
1170 return NV_ENC_BUFFER_FORMAT_YUV444_PL;
1171 case AV_PIX_FMT_YUV444P16:
1172 return NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1173 case AV_PIX_FMT_0RGB32:
1174 return NV_ENC_BUFFER_FORMAT_ARGB;
1175 case AV_PIX_FMT_0BGR32:
1176 return NV_ENC_BUFFER_FORMAT_ABGR;
1178 return NV_ENC_BUFFER_FORMAT_UNDEFINED;
1182 static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
1184 NvencContext *ctx = avctx->priv_data;
1185 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1186 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1187 NvencSurface* tmp_surface = &ctx->surfaces[idx];
1189 NVENCSTATUS nv_status;
1190 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
1191 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1193 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1194 ctx->surfaces[idx].in_ref = av_frame_alloc();
1195 if (!ctx->surfaces[idx].in_ref)
1196 return AVERROR(ENOMEM);
1198 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1200 ctx->surfaces[idx].format = nvenc_map_buffer_format(ctx->data_pix_fmt);
1201 if (ctx->surfaces[idx].format == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1202 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1203 av_get_pix_fmt_name(ctx->data_pix_fmt));
1204 return AVERROR(EINVAL);
1207 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1208 allocSurf.width = avctx->width;
1209 allocSurf.height = avctx->height;
1210 allocSurf.bufferFmt = ctx->surfaces[idx].format;
1212 nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
1213 if (nv_status != NV_ENC_SUCCESS) {
1214 return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
1217 ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
1218 ctx->surfaces[idx].width = allocSurf.width;
1219 ctx->surfaces[idx].height = allocSurf.height;
1222 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
1223 if (nv_status != NV_ENC_SUCCESS) {
1224 int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
1225 if (avctx->pix_fmt != AV_PIX_FMT_CUDA)
1226 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
1227 av_frame_free(&ctx->surfaces[idx].in_ref);
1231 ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1232 ctx->surfaces[idx].size = allocOut.size;
1234 av_fifo_generic_write(ctx->unused_surface_queue, &tmp_surface, sizeof(tmp_surface), NULL);
1239 static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx)
1241 NvencContext *ctx = avctx->priv_data;
1242 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1247 ctx->surfaces = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->surfaces));
1249 return AVERROR(ENOMEM);
1251 ctx->timestamp_list = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
1252 if (!ctx->timestamp_list)
1253 return AVERROR(ENOMEM);
1255 ctx->unused_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1256 if (!ctx->unused_surface_queue)
1257 return AVERROR(ENOMEM);
1259 ctx->output_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1260 if (!ctx->output_surface_queue)
1261 return AVERROR(ENOMEM);
1262 ctx->output_surface_ready_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1263 if (!ctx->output_surface_ready_queue)
1264 return AVERROR(ENOMEM);
1266 cu_res = dl_fn->cuda_dl->cuCtxPushCurrent(ctx->cu_context);
1267 if (cu_res != CUDA_SUCCESS) {
1268 av_log(avctx, AV_LOG_ERROR, "cuCtxPushCurrent failed\n");
1269 return AVERROR_EXTERNAL;
1272 for (i = 0; i < ctx->nb_surfaces; i++) {
1273 if ((res = nvenc_alloc_surface(avctx, i)) < 0)
1275 cu_res = dl_fn->cuda_dl->cuCtxPopCurrent(&dummy);
1276 if (cu_res != CUDA_SUCCESS) {
1277 av_log(avctx, AV_LOG_ERROR, "cuCtxPopCurrent failed\n");
1278 return AVERROR_EXTERNAL;
1284 cu_res = dl_fn->cuda_dl->cuCtxPopCurrent(&dummy);
1285 if (cu_res != CUDA_SUCCESS) {
1286 av_log(avctx, AV_LOG_ERROR, "cuCtxPopCurrent failed\n");
1287 return AVERROR_EXTERNAL;
1293 static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
1295 NvencContext *ctx = avctx->priv_data;
1296 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1297 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1299 NVENCSTATUS nv_status;
1300 uint32_t outSize = 0;
1301 char tmpHeader[256];
1302 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1303 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1305 payload.spsppsBuffer = tmpHeader;
1306 payload.inBufferSize = sizeof(tmpHeader);
1307 payload.outSPSPPSPayloadSize = &outSize;
1309 nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
1310 if (nv_status != NV_ENC_SUCCESS) {
1311 return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
1314 avctx->extradata_size = outSize;
1315 avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
1317 if (!avctx->extradata) {
1318 return AVERROR(ENOMEM);
1321 memcpy(avctx->extradata, tmpHeader, outSize);
1326 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
1328 NvencContext *ctx = avctx->priv_data;
1329 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1330 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1335 /* the encoder has to be flushed before it can be closed */
1336 if (ctx->nvencoder) {
1337 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
1338 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
1340 cu_res = dl_fn->cuda_dl->cuCtxPushCurrent(ctx->cu_context);
1341 if (cu_res != CUDA_SUCCESS) {
1342 av_log(avctx, AV_LOG_ERROR, "cuCtxPushCurrent failed\n");
1343 return AVERROR_EXTERNAL;
1346 p_nvenc->nvEncEncodePicture(ctx->nvencoder, ¶ms);
1349 av_fifo_freep(&ctx->timestamp_list);
1350 av_fifo_freep(&ctx->output_surface_ready_queue);
1351 av_fifo_freep(&ctx->output_surface_queue);
1352 av_fifo_freep(&ctx->unused_surface_queue);
1354 if (ctx->surfaces && avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1355 for (i = 0; i < ctx->nb_surfaces; ++i) {
1356 if (ctx->surfaces[i].input_surface) {
1357 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->surfaces[i].in_map.mappedResource);
1360 for (i = 0; i < ctx->nb_registered_frames; i++) {
1361 if (ctx->registered_frames[i].regptr)
1362 p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1364 ctx->nb_registered_frames = 0;
1367 if (ctx->surfaces) {
1368 for (i = 0; i < ctx->nb_surfaces; ++i) {
1369 if (avctx->pix_fmt != AV_PIX_FMT_CUDA)
1370 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
1371 av_frame_free(&ctx->surfaces[i].in_ref);
1372 p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
1375 av_freep(&ctx->surfaces);
1376 ctx->nb_surfaces = 0;
1378 if (ctx->nvencoder) {
1379 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1381 cu_res = dl_fn->cuda_dl->cuCtxPopCurrent(&dummy);
1382 if (cu_res != CUDA_SUCCESS) {
1383 av_log(avctx, AV_LOG_ERROR, "cuCtxPopCurrent failed\n");
1384 return AVERROR_EXTERNAL;
1387 ctx->nvencoder = NULL;
1389 if (ctx->cu_context_internal)
1390 dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal);
1391 ctx->cu_context = ctx->cu_context_internal = NULL;
1393 nvenc_free_functions(&dl_fn->nvenc_dl);
1394 cuda_free_functions(&dl_fn->cuda_dl);
1396 dl_fn->nvenc_device_count = 0;
1398 av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
1403 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
1405 NvencContext *ctx = avctx->priv_data;
1408 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1409 AVHWFramesContext *frames_ctx;
1410 if (!avctx->hw_frames_ctx) {
1411 av_log(avctx, AV_LOG_ERROR,
1412 "hw_frames_ctx must be set when using GPU frames as input\n");
1413 return AVERROR(EINVAL);
1415 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1416 ctx->data_pix_fmt = frames_ctx->sw_format;
1418 ctx->data_pix_fmt = avctx->pix_fmt;
1421 if ((ret = nvenc_load_libraries(avctx)) < 0)
1424 if ((ret = nvenc_setup_device(avctx)) < 0)
1427 if ((ret = nvenc_setup_encoder(avctx)) < 0)
1430 if ((ret = nvenc_setup_surfaces(avctx)) < 0)
1433 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1434 if ((ret = nvenc_setup_extradata(avctx)) < 0)
1441 static NvencSurface *get_free_frame(NvencContext *ctx)
1443 NvencSurface *tmp_surf;
1445 if (!(av_fifo_size(ctx->unused_surface_queue) > 0))
1449 av_fifo_generic_read(ctx->unused_surface_queue, &tmp_surf, sizeof(tmp_surf), NULL);
1453 static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *nv_surface,
1454 NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params, const AVFrame *frame)
1456 int dst_linesize[4] = {
1457 lock_buffer_params->pitch,
1458 lock_buffer_params->pitch,
1459 lock_buffer_params->pitch,
1460 lock_buffer_params->pitch
1462 uint8_t *dst_data[4];
1465 if (frame->format == AV_PIX_FMT_YUV420P)
1466 dst_linesize[1] = dst_linesize[2] >>= 1;
1468 ret = av_image_fill_pointers(dst_data, frame->format, nv_surface->height,
1469 lock_buffer_params->bufferDataPtr, dst_linesize);
1473 if (frame->format == AV_PIX_FMT_YUV420P)
1474 FFSWAP(uint8_t*, dst_data[1], dst_data[2]);
1476 av_image_copy(dst_data, dst_linesize,
1477 (const uint8_t**)frame->data, frame->linesize, frame->format,
1478 avctx->width, avctx->height);
1483 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1485 NvencContext *ctx = avctx->priv_data;
1486 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1487 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1491 if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1492 for (i = 0; i < ctx->nb_registered_frames; i++) {
1493 if (!ctx->registered_frames[i].mapped) {
1494 if (ctx->registered_frames[i].regptr) {
1495 p_nvenc->nvEncUnregisterResource(ctx->nvencoder,
1496 ctx->registered_frames[i].regptr);
1497 ctx->registered_frames[i].regptr = NULL;
1503 return ctx->nb_registered_frames++;
1506 av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1507 return AVERROR(ENOMEM);
1510 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1512 NvencContext *ctx = avctx->priv_data;
1513 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1514 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1516 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frame->hw_frames_ctx->data;
1517 NV_ENC_REGISTER_RESOURCE reg;
1520 for (i = 0; i < ctx->nb_registered_frames; i++) {
1521 if (ctx->registered_frames[i].ptr == (CUdeviceptr)frame->data[0])
1525 idx = nvenc_find_free_reg_resource(avctx);
1529 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1530 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1531 reg.width = frames_ctx->width;
1532 reg.height = frames_ctx->height;
1533 reg.pitch = frame->linesize[0];
1534 reg.resourceToRegister = frame->data[0];
1536 reg.bufferFormat = nvenc_map_buffer_format(frames_ctx->sw_format);
1537 if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1538 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1539 av_get_pix_fmt_name(frames_ctx->sw_format));
1540 return AVERROR(EINVAL);
1543 ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, ®);
1544 if (ret != NV_ENC_SUCCESS) {
1545 nvenc_print_error(avctx, ret, "Error registering an input resource");
1546 return AVERROR_UNKNOWN;
1549 ctx->registered_frames[idx].ptr = (CUdeviceptr)frame->data[0];
1550 ctx->registered_frames[idx].regptr = reg.registeredResource;
1554 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1555 NvencSurface *nvenc_frame)
1557 NvencContext *ctx = avctx->priv_data;
1558 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1559 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1562 NVENCSTATUS nv_status;
1564 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1565 int reg_idx = nvenc_register_frame(avctx, frame);
1567 av_log(avctx, AV_LOG_ERROR, "Could not register an input CUDA frame\n");
1571 res = av_frame_ref(nvenc_frame->in_ref, frame);
1575 nvenc_frame->in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1576 nvenc_frame->in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1577 nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &nvenc_frame->in_map);
1578 if (nv_status != NV_ENC_SUCCESS) {
1579 av_frame_unref(nvenc_frame->in_ref);
1580 return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
1583 ctx->registered_frames[reg_idx].mapped = 1;
1584 nvenc_frame->reg_idx = reg_idx;
1585 nvenc_frame->input_surface = nvenc_frame->in_map.mappedResource;
1586 nvenc_frame->format = nvenc_frame->in_map.mappedBufferFmt;
1587 nvenc_frame->pitch = frame->linesize[0];
1590 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1592 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1593 lockBufferParams.inputBuffer = nvenc_frame->input_surface;
1595 nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
1596 if (nv_status != NV_ENC_SUCCESS) {
1597 return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
1600 nvenc_frame->pitch = lockBufferParams.pitch;
1601 res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
1603 nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
1604 if (nv_status != NV_ENC_SUCCESS) {
1605 return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
1612 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1613 NV_ENC_PIC_PARAMS *params)
1615 NvencContext *ctx = avctx->priv_data;
1617 switch (avctx->codec->id) {
1618 case AV_CODEC_ID_H264:
1619 params->codecPicParams.h264PicParams.sliceMode =
1620 ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1621 params->codecPicParams.h264PicParams.sliceModeData =
1622 ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1624 case AV_CODEC_ID_HEVC:
1625 params->codecPicParams.hevcPicParams.sliceMode =
1626 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1627 params->codecPicParams.hevcPicParams.sliceModeData =
1628 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1633 static inline void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
1635 av_fifo_generic_write(queue, ×tamp, sizeof(timestamp), NULL);
1638 static inline int64_t timestamp_queue_dequeue(AVFifoBuffer* queue)
1640 int64_t timestamp = AV_NOPTS_VALUE;
1641 if (av_fifo_size(queue) > 0)
1642 av_fifo_generic_read(queue, ×tamp, sizeof(timestamp), NULL);
1647 static int nvenc_set_timestamp(AVCodecContext *avctx,
1648 NV_ENC_LOCK_BITSTREAM *params,
1651 NvencContext *ctx = avctx->priv_data;
1653 pkt->pts = params->outputTimeStamp;
1655 /* generate the first dts by linearly extrapolating the
1656 * first two pts values to the past */
1657 if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
1658 ctx->initial_pts[1] != AV_NOPTS_VALUE) {
1659 int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
1662 if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
1663 (ts0 > 0 && ts1 < INT64_MIN + ts0))
1664 return AVERROR(ERANGE);
1667 if ((delta < 0 && ts0 > INT64_MAX + delta) ||
1668 (delta > 0 && ts0 < INT64_MIN + delta))
1669 return AVERROR(ERANGE);
1670 pkt->dts = ts0 - delta;
1672 ctx->first_packet_output = 1;
1676 pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
1681 static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
1683 NvencContext *ctx = avctx->priv_data;
1684 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1685 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1687 uint32_t slice_mode_data;
1688 uint32_t *slice_offsets = NULL;
1689 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1690 NVENCSTATUS nv_status;
1693 enum AVPictureType pict_type;
1695 switch (avctx->codec->id) {
1696 case AV_CODEC_ID_H264:
1697 slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1699 case AV_CODEC_ID_H265:
1700 slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1703 av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
1704 res = AVERROR(EINVAL);
1707 slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
1712 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1714 lock_params.doNotWait = 0;
1715 lock_params.outputBitstream = tmpoutsurf->output_surface;
1716 lock_params.sliceOffsets = slice_offsets;
1718 nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
1719 if (nv_status != NV_ENC_SUCCESS) {
1720 res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
1724 if (res = ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes,0)) {
1725 p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1729 memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1731 nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1732 if (nv_status != NV_ENC_SUCCESS)
1733 nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
1736 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1737 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, tmpoutsurf->in_map.mappedResource);
1738 av_frame_unref(tmpoutsurf->in_ref);
1739 ctx->registered_frames[tmpoutsurf->reg_idx].mapped = 0;
1741 tmpoutsurf->input_surface = NULL;
1744 switch (lock_params.pictureType) {
1745 case NV_ENC_PIC_TYPE_IDR:
1746 pkt->flags |= AV_PKT_FLAG_KEY;
1747 case NV_ENC_PIC_TYPE_I:
1748 pict_type = AV_PICTURE_TYPE_I;
1750 case NV_ENC_PIC_TYPE_P:
1751 pict_type = AV_PICTURE_TYPE_P;
1753 case NV_ENC_PIC_TYPE_B:
1754 pict_type = AV_PICTURE_TYPE_B;
1756 case NV_ENC_PIC_TYPE_BI:
1757 pict_type = AV_PICTURE_TYPE_BI;
1760 av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
1761 av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
1762 res = AVERROR_EXTERNAL;
1766 #if FF_API_CODED_FRAME
1767 FF_DISABLE_DEPRECATION_WARNINGS
1768 avctx->coded_frame->pict_type = pict_type;
1769 FF_ENABLE_DEPRECATION_WARNINGS
1772 ff_side_data_set_encoder_stats(pkt,
1773 (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
1775 res = nvenc_set_timestamp(avctx, &lock_params, pkt);
1779 av_free(slice_offsets);
1784 timestamp_queue_dequeue(ctx->timestamp_list);
1787 av_free(slice_offsets);
1792 static int output_ready(AVCodecContext *avctx, int flush)
1794 NvencContext *ctx = avctx->priv_data;
1795 int nb_ready, nb_pending;
1797 /* when B-frames are enabled, we wait for two initial timestamps to
1798 * calculate the first dts */
1799 if (!flush && avctx->max_b_frames > 0 &&
1800 (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
1803 nb_ready = av_fifo_size(ctx->output_surface_ready_queue) / sizeof(NvencSurface*);
1804 nb_pending = av_fifo_size(ctx->output_surface_queue) / sizeof(NvencSurface*);
1806 return nb_ready > 0;
1807 return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
1810 int ff_nvenc_send_frame(AVCodecContext *avctx, const AVFrame *frame)
1812 NVENCSTATUS nv_status;
1815 NvencSurface *tmp_out_surf, *in_surf;
1818 NvencContext *ctx = avctx->priv_data;
1819 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1820 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1822 NV_ENC_PIC_PARAMS pic_params = { 0 };
1823 pic_params.version = NV_ENC_PIC_PARAMS_VER;
1825 if (!ctx->cu_context || !ctx->nvencoder)
1826 return AVERROR(EINVAL);
1828 if (ctx->encoder_flushing)
1832 in_surf = get_free_frame(ctx);
1834 return AVERROR(EAGAIN);
1836 cu_res = dl_fn->cuda_dl->cuCtxPushCurrent(ctx->cu_context);
1837 if (cu_res != CUDA_SUCCESS) {
1838 av_log(avctx, AV_LOG_ERROR, "cuCtxPushCurrent failed\n");
1839 return AVERROR_EXTERNAL;
1842 res = nvenc_upload_frame(avctx, frame, in_surf);
1844 cu_res = dl_fn->cuda_dl->cuCtxPopCurrent(&dummy);
1845 if (cu_res != CUDA_SUCCESS) {
1846 av_log(avctx, AV_LOG_ERROR, "cuCtxPopCurrent failed\n");
1847 return AVERROR_EXTERNAL;
1853 pic_params.inputBuffer = in_surf->input_surface;
1854 pic_params.bufferFmt = in_surf->format;
1855 pic_params.inputWidth = in_surf->width;
1856 pic_params.inputHeight = in_surf->height;
1857 pic_params.inputPitch = in_surf->pitch;
1858 pic_params.outputBitstream = in_surf->output_surface;
1860 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1861 if (frame->top_field_first)
1862 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
1864 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
1866 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1869 if (ctx->forced_idr >= 0 && frame->pict_type == AV_PICTURE_TYPE_I) {
1870 pic_params.encodePicFlags =
1871 ctx->forced_idr ? NV_ENC_PIC_FLAG_FORCEIDR : NV_ENC_PIC_FLAG_FORCEINTRA;
1873 pic_params.encodePicFlags = 0;
1876 pic_params.inputTimeStamp = frame->pts;
1878 nvenc_codec_specific_pic_params(avctx, &pic_params);
1880 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1881 ctx->encoder_flushing = 1;
1884 cu_res = dl_fn->cuda_dl->cuCtxPushCurrent(ctx->cu_context);
1885 if (cu_res != CUDA_SUCCESS) {
1886 av_log(avctx, AV_LOG_ERROR, "cuCtxPushCurrent failed\n");
1887 return AVERROR_EXTERNAL;
1890 nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
1892 cu_res = dl_fn->cuda_dl->cuCtxPopCurrent(&dummy);
1893 if (cu_res != CUDA_SUCCESS) {
1894 av_log(avctx, AV_LOG_ERROR, "cuCtxPopCurrent failed\n");
1895 return AVERROR_EXTERNAL;
1898 if (nv_status != NV_ENC_SUCCESS &&
1899 nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
1900 return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
1903 av_fifo_generic_write(ctx->output_surface_queue, &in_surf, sizeof(in_surf), NULL);
1904 timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
1906 if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
1907 ctx->initial_pts[0] = frame->pts;
1908 else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
1909 ctx->initial_pts[1] = frame->pts;
1912 /* all the pending buffers are now ready for output */
1913 if (nv_status == NV_ENC_SUCCESS) {
1914 while (av_fifo_size(ctx->output_surface_queue) > 0) {
1915 av_fifo_generic_read(ctx->output_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
1916 av_fifo_generic_write(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
1923 int ff_nvenc_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
1927 NvencSurface *tmp_out_surf;
1930 NvencContext *ctx = avctx->priv_data;
1931 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1933 if (!ctx->cu_context || !ctx->nvencoder)
1934 return AVERROR(EINVAL);
1936 if (output_ready(avctx, ctx->encoder_flushing)) {
1937 av_fifo_generic_read(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
1939 cu_res = dl_fn->cuda_dl->cuCtxPushCurrent(ctx->cu_context);
1940 if (cu_res != CUDA_SUCCESS) {
1941 av_log(avctx, AV_LOG_ERROR, "cuCtxPushCurrent failed\n");
1942 return AVERROR_EXTERNAL;
1945 res = process_output_surface(avctx, pkt, tmp_out_surf);
1947 cu_res = dl_fn->cuda_dl->cuCtxPopCurrent(&dummy);
1948 if (cu_res != CUDA_SUCCESS) {
1949 av_log(avctx, AV_LOG_ERROR, "cuCtxPopCurrent failed\n");
1950 return AVERROR_EXTERNAL;
1956 av_fifo_generic_write(ctx->unused_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
1957 } else if (ctx->encoder_flushing) {
1960 return AVERROR(EAGAIN);
1966 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1967 const AVFrame *frame, int *got_packet)
1969 NvencContext *ctx = avctx->priv_data;
1972 if (!ctx->encoder_flushing) {
1973 res = ff_nvenc_send_frame(avctx, frame);
1978 res = ff_nvenc_receive_packet(avctx, pkt);
1979 if (res == AVERROR(EAGAIN) || res == AVERROR_EOF) {
1981 } else if (res < 0) {