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);
323 static av_cold int nvenc_check_device(AVCodecContext *avctx, int idx)
325 NvencContext *ctx = avctx->priv_data;
326 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
327 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
328 char name[128] = { 0};
329 int major, minor, ret;
333 int loglevel = AV_LOG_VERBOSE;
335 if (ctx->device == LIST_DEVICES)
336 loglevel = AV_LOG_INFO;
338 cu_res = dl_fn->cuda_dl->cuDeviceGet(&cu_device, idx);
339 if (cu_res != CUDA_SUCCESS) {
340 av_log(avctx, AV_LOG_ERROR,
341 "Cannot access the CUDA device %d\n",
346 cu_res = dl_fn->cuda_dl->cuDeviceGetName(name, sizeof(name), cu_device);
347 if (cu_res != CUDA_SUCCESS) {
348 av_log(avctx, AV_LOG_ERROR, "cuDeviceGetName failed on device %d\n", idx);
352 cu_res = dl_fn->cuda_dl->cuDeviceComputeCapability(&major, &minor, cu_device);
353 if (cu_res != CUDA_SUCCESS) {
354 av_log(avctx, AV_LOG_ERROR, "cuDeviceComputeCapability failed on device %d\n", idx);
358 av_log(avctx, loglevel, "[ GPU #%d - < %s > has Compute SM %d.%d ]\n", idx, name, major, minor);
359 if (((major << 4) | minor) < NVENC_CAP) {
360 av_log(avctx, loglevel, "does not support NVENC\n");
364 if (ctx->device != idx && ctx->device != ANY_DEVICE)
367 cu_res = dl_fn->cuda_dl->cuCtxCreate(&ctx->cu_context_internal, 0, cu_device);
368 if (cu_res != CUDA_SUCCESS) {
369 av_log(avctx, AV_LOG_FATAL, "Failed creating CUDA context for NVENC: 0x%x\n", (int)cu_res);
373 ctx->cu_context = ctx->cu_context_internal;
375 cu_res = dl_fn->cuda_dl->cuCtxPopCurrent(&dummy);
376 if (cu_res != CUDA_SUCCESS) {
377 av_log(avctx, AV_LOG_FATAL, "Failed popping CUDA context: 0x%x\n", (int)cu_res);
381 if ((ret = nvenc_open_session(avctx)) < 0)
384 if ((ret = nvenc_check_capabilities(avctx)) < 0)
387 av_log(avctx, loglevel, "supports NVENC\n");
389 dl_fn->nvenc_device_count++;
391 if (ctx->device == idx || ctx->device == ANY_DEVICE)
395 cu_res = dl_fn->cuda_dl->cuCtxPushCurrent(ctx->cu_context);
396 if (cu_res != CUDA_SUCCESS) {
397 av_log(avctx, AV_LOG_ERROR, "cuCtxPushCurrent failed\n");
398 return AVERROR_EXTERNAL;
401 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
402 ctx->nvencoder = NULL;
404 cu_res = dl_fn->cuda_dl->cuCtxPopCurrent(&dummy);
405 if (cu_res != CUDA_SUCCESS) {
406 av_log(avctx, AV_LOG_ERROR, "cuCtxPopCurrent failed\n");
407 return AVERROR_EXTERNAL;
411 dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal);
412 ctx->cu_context_internal = NULL;
415 return AVERROR(ENOSYS);
418 static av_cold int nvenc_setup_device(AVCodecContext *avctx)
420 NvencContext *ctx = avctx->priv_data;
421 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
423 switch (avctx->codec->id) {
424 case AV_CODEC_ID_H264:
425 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
427 case AV_CODEC_ID_HEVC:
428 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
434 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->hw_frames_ctx || avctx->hw_device_ctx) {
435 AVHWFramesContext *frames_ctx;
436 AVHWDeviceContext *hwdev_ctx;
437 AVCUDADeviceContext *device_hwctx;
440 if (avctx->hw_frames_ctx) {
441 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
442 device_hwctx = frames_ctx->device_ctx->hwctx;
443 } else if (avctx->hw_device_ctx) {
444 hwdev_ctx = (AVHWDeviceContext*)avctx->hw_device_ctx->data;
445 device_hwctx = hwdev_ctx->hwctx;
447 return AVERROR(EINVAL);
450 ctx->cu_context = device_hwctx->cuda_ctx;
452 ret = nvenc_open_session(avctx);
456 ret = nvenc_check_capabilities(avctx);
458 av_log(avctx, AV_LOG_FATAL, "Provided device doesn't support required NVENC features\n");
462 int i, nb_devices = 0;
464 if ((dl_fn->cuda_dl->cuInit(0)) != CUDA_SUCCESS) {
465 av_log(avctx, AV_LOG_ERROR,
466 "Cannot init CUDA\n");
467 return AVERROR_UNKNOWN;
470 if ((dl_fn->cuda_dl->cuDeviceGetCount(&nb_devices)) != CUDA_SUCCESS) {
471 av_log(avctx, AV_LOG_ERROR,
472 "Cannot enumerate the CUDA devices\n");
473 return AVERROR_UNKNOWN;
477 av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
478 return AVERROR_EXTERNAL;
481 av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", nb_devices);
483 dl_fn->nvenc_device_count = 0;
484 for (i = 0; i < nb_devices; ++i) {
485 if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
489 if (ctx->device == LIST_DEVICES)
492 if (!dl_fn->nvenc_device_count) {
493 av_log(avctx, AV_LOG_FATAL, "No NVENC capable devices found\n");
494 return AVERROR_EXTERNAL;
497 av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->device, nb_devices);
498 return AVERROR(EINVAL);
504 typedef struct GUIDTuple {
509 #define PRESET_ALIAS(alias, name, ...) \
510 [PRESET_ ## alias] = { NV_ENC_PRESET_ ## name ## _GUID, __VA_ARGS__ }
512 #define PRESET(name, ...) PRESET_ALIAS(name, name, __VA_ARGS__)
514 static void nvenc_map_preset(NvencContext *ctx)
516 GUIDTuple presets[] = {
521 PRESET_ALIAS(SLOW, HQ, NVENC_TWO_PASSES),
522 PRESET_ALIAS(MEDIUM, HQ, NVENC_ONE_PASS),
523 PRESET_ALIAS(FAST, HP, NVENC_ONE_PASS),
524 PRESET(LOW_LATENCY_DEFAULT, NVENC_LOWLATENCY),
525 PRESET(LOW_LATENCY_HP, NVENC_LOWLATENCY),
526 PRESET(LOW_LATENCY_HQ, NVENC_LOWLATENCY),
527 PRESET(LOSSLESS_DEFAULT, NVENC_LOSSLESS),
528 PRESET(LOSSLESS_HP, NVENC_LOSSLESS),
531 GUIDTuple *t = &presets[ctx->preset];
533 ctx->init_encode_params.presetGUID = t->guid;
534 ctx->flags = t->flags;
540 static av_cold void set_constqp(AVCodecContext *avctx)
542 NvencContext *ctx = avctx->priv_data;
543 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
545 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
547 if (ctx->init_qp_p >= 0) {
548 rc->constQP.qpInterP = ctx->init_qp_p;
549 if (ctx->init_qp_i >= 0 && ctx->init_qp_b >= 0) {
550 rc->constQP.qpIntra = ctx->init_qp_i;
551 rc->constQP.qpInterB = ctx->init_qp_b;
552 } else if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
553 rc->constQP.qpIntra = av_clip(
554 rc->constQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
555 rc->constQP.qpInterB = av_clip(
556 rc->constQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
558 rc->constQP.qpIntra = rc->constQP.qpInterP;
559 rc->constQP.qpInterB = rc->constQP.qpInterP;
561 } else if (ctx->cqp >= 0) {
562 rc->constQP.qpInterP = rc->constQP.qpInterB = rc->constQP.qpIntra = ctx->cqp;
563 if (avctx->b_quant_factor != 0.0)
564 rc->constQP.qpInterB = av_clip(ctx->cqp * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
565 if (avctx->i_quant_factor != 0.0)
566 rc->constQP.qpIntra = av_clip(ctx->cqp * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
573 static av_cold void set_vbr(AVCodecContext *avctx)
575 NvencContext *ctx = avctx->priv_data;
576 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
579 if (avctx->qmin >= 0 && avctx->qmax >= 0) {
583 rc->minQP.qpInterB = avctx->qmin;
584 rc->minQP.qpInterP = avctx->qmin;
585 rc->minQP.qpIntra = avctx->qmin;
587 rc->maxQP.qpInterB = avctx->qmax;
588 rc->maxQP.qpInterP = avctx->qmax;
589 rc->maxQP.qpIntra = avctx->qmax;
591 qp_inter_p = (avctx->qmax + 3 * avctx->qmin) / 4; // biased towards Qmin
592 } else if (avctx->qmin >= 0) {
595 rc->minQP.qpInterB = avctx->qmin;
596 rc->minQP.qpInterP = avctx->qmin;
597 rc->minQP.qpIntra = avctx->qmin;
599 qp_inter_p = avctx->qmin;
601 qp_inter_p = 26; // default to 26
604 rc->enableInitialRCQP = 1;
606 if (ctx->init_qp_p < 0) {
607 rc->initialRCQP.qpInterP = qp_inter_p;
609 rc->initialRCQP.qpInterP = ctx->init_qp_p;
612 if (ctx->init_qp_i < 0) {
613 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
614 rc->initialRCQP.qpIntra = av_clip(
615 rc->initialRCQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
617 rc->initialRCQP.qpIntra = rc->initialRCQP.qpInterP;
620 rc->initialRCQP.qpIntra = ctx->init_qp_i;
623 if (ctx->init_qp_b < 0) {
624 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
625 rc->initialRCQP.qpInterB = av_clip(
626 rc->initialRCQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
628 rc->initialRCQP.qpInterB = rc->initialRCQP.qpInterP;
631 rc->initialRCQP.qpInterB = ctx->init_qp_b;
635 static av_cold void set_lossless(AVCodecContext *avctx)
637 NvencContext *ctx = avctx->priv_data;
638 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
640 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
641 rc->constQP.qpInterB = 0;
642 rc->constQP.qpInterP = 0;
643 rc->constQP.qpIntra = 0;
649 static void nvenc_override_rate_control(AVCodecContext *avctx)
651 NvencContext *ctx = avctx->priv_data;
652 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
655 case NV_ENC_PARAMS_RC_CONSTQP:
658 case NV_ENC_PARAMS_RC_VBR_MINQP:
659 if (avctx->qmin < 0) {
660 av_log(avctx, AV_LOG_WARNING,
661 "The variable bitrate rate-control requires "
662 "the 'qmin' option set.\n");
667 case NV_ENC_PARAMS_RC_VBR_HQ:
668 case NV_ENC_PARAMS_RC_VBR:
671 case NV_ENC_PARAMS_RC_CBR:
672 case NV_ENC_PARAMS_RC_CBR_HQ:
673 case NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ:
677 rc->rateControlMode = ctx->rc;
680 static av_cold int nvenc_recalc_surfaces(AVCodecContext *avctx)
682 NvencContext *ctx = avctx->priv_data;
683 // default minimum of 4 surfaces
684 // multiply by 2 for number of NVENCs on gpu (hardcode to 2)
685 // another multiply by 2 to avoid blocking next PBB group
686 int nb_surfaces = FFMAX(4, ctx->encode_config.frameIntervalP * 2 * 2);
689 if (ctx->rc_lookahead > 0) {
690 // +1 is to account for lkd_bound calculation later
691 // +4 is to allow sufficient pipelining with lookahead
692 nb_surfaces = FFMAX(1, FFMAX(nb_surfaces, ctx->rc_lookahead + ctx->encode_config.frameIntervalP + 1 + 4));
693 if (nb_surfaces > ctx->nb_surfaces && ctx->nb_surfaces > 0)
695 av_log(avctx, AV_LOG_WARNING,
696 "Defined rc_lookahead requires more surfaces, "
697 "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
699 ctx->nb_surfaces = FFMAX(nb_surfaces, ctx->nb_surfaces);
701 if (ctx->encode_config.frameIntervalP > 1 && ctx->nb_surfaces < nb_surfaces && ctx->nb_surfaces > 0)
703 av_log(avctx, AV_LOG_WARNING,
704 "Defined b-frame requires more surfaces, "
705 "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
706 ctx->nb_surfaces = FFMAX(ctx->nb_surfaces, nb_surfaces);
708 else if (ctx->nb_surfaces <= 0)
709 ctx->nb_surfaces = nb_surfaces;
710 // otherwise use user specified value
713 ctx->nb_surfaces = FFMAX(1, FFMIN(MAX_REGISTERED_FRAMES, ctx->nb_surfaces));
714 ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
719 static av_cold void nvenc_setup_rate_control(AVCodecContext *avctx)
721 NvencContext *ctx = avctx->priv_data;
723 if (avctx->global_quality > 0)
724 av_log(avctx, AV_LOG_WARNING, "Using global_quality with nvenc is deprecated. Use qp instead.\n");
726 if (ctx->cqp < 0 && avctx->global_quality > 0)
727 ctx->cqp = avctx->global_quality;
729 if (avctx->bit_rate > 0) {
730 ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
731 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
732 ctx->encode_config.rcParams.maxBitRate = ctx->encode_config.rcParams.averageBitRate;
735 if (avctx->rc_max_rate > 0)
736 ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
739 if (ctx->flags & NVENC_ONE_PASS)
741 if (ctx->flags & NVENC_TWO_PASSES)
744 if (ctx->twopass < 0)
745 ctx->twopass = (ctx->flags & NVENC_LOWLATENCY) != 0;
749 ctx->rc = NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ;
751 ctx->rc = NV_ENC_PARAMS_RC_CBR;
753 } else if (ctx->cqp >= 0) {
754 ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
755 } else if (ctx->twopass) {
756 ctx->rc = NV_ENC_PARAMS_RC_VBR_HQ;
757 } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
758 ctx->rc = NV_ENC_PARAMS_RC_VBR_MINQP;
762 if (ctx->rc >= 0 && ctx->rc & RC_MODE_DEPRECATED) {
763 av_log(avctx, AV_LOG_WARNING, "Specified rc mode is deprecated.\n");
764 av_log(avctx, AV_LOG_WARNING, "\tll_2pass_quality -> cbr_ld_hq\n");
765 av_log(avctx, AV_LOG_WARNING, "\tll_2pass_size -> cbr_hq\n");
766 av_log(avctx, AV_LOG_WARNING, "\tvbr_2pass -> vbr_hq\n");
767 av_log(avctx, AV_LOG_WARNING, "\tvbr_minqp -> (no replacement)\n");
769 ctx->rc &= ~RC_MODE_DEPRECATED;
772 if (ctx->flags & NVENC_LOSSLESS) {
774 } else if (ctx->rc >= 0) {
775 nvenc_override_rate_control(avctx);
777 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
781 if (avctx->rc_buffer_size > 0) {
782 ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
783 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
784 ctx->encode_config.rcParams.vbvBufferSize = 2 * ctx->encode_config.rcParams.averageBitRate;
788 ctx->encode_config.rcParams.enableAQ = 1;
789 ctx->encode_config.rcParams.aqStrength = ctx->aq_strength;
790 av_log(avctx, AV_LOG_VERBOSE, "AQ enabled.\n");
793 if (ctx->temporal_aq) {
794 ctx->encode_config.rcParams.enableTemporalAQ = 1;
795 av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ enabled.\n");
798 if (ctx->rc_lookahead > 0) {
799 int lkd_bound = FFMIN(ctx->nb_surfaces, ctx->async_depth) -
800 ctx->encode_config.frameIntervalP - 4;
803 av_log(avctx, AV_LOG_WARNING,
804 "Lookahead not enabled. Increase buffer delay (-delay).\n");
806 ctx->encode_config.rcParams.enableLookahead = 1;
807 ctx->encode_config.rcParams.lookaheadDepth = av_clip(ctx->rc_lookahead, 0, lkd_bound);
808 ctx->encode_config.rcParams.disableIadapt = ctx->no_scenecut;
809 ctx->encode_config.rcParams.disableBadapt = !ctx->b_adapt;
810 av_log(avctx, AV_LOG_VERBOSE,
811 "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",
812 ctx->encode_config.rcParams.lookaheadDepth,
813 ctx->encode_config.rcParams.disableIadapt ? "disabled" : "enabled",
814 ctx->encode_config.rcParams.disableBadapt ? "disabled" : "enabled");
818 if (ctx->strict_gop) {
819 ctx->encode_config.rcParams.strictGOPTarget = 1;
820 av_log(avctx, AV_LOG_VERBOSE, "Strict GOP target enabled.\n");
824 ctx->encode_config.rcParams.enableNonRefP = 1;
826 if (ctx->zerolatency)
827 ctx->encode_config.rcParams.zeroReorderDelay = 1;
831 //convert from float to fixed point 8.8
832 int tmp_quality = (int)(ctx->quality * 256.0f);
833 ctx->encode_config.rcParams.targetQuality = (uint8_t)(tmp_quality >> 8);
834 ctx->encode_config.rcParams.targetQualityLSB = (uint8_t)(tmp_quality & 0xff);
838 static av_cold int nvenc_setup_h264_config(AVCodecContext *avctx)
840 NvencContext *ctx = avctx->priv_data;
841 NV_ENC_CONFIG *cc = &ctx->encode_config;
842 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
843 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
845 vui->colourMatrix = avctx->colorspace;
846 vui->colourPrimaries = avctx->color_primaries;
847 vui->transferCharacteristics = avctx->color_trc;
848 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
849 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
851 vui->colourDescriptionPresentFlag =
852 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
854 vui->videoSignalTypePresentFlag =
855 (vui->colourDescriptionPresentFlag
856 || vui->videoFormat != 5
857 || vui->videoFullRangeFlag != 0);
860 h264->sliceModeData = 1;
862 h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
863 h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
864 h264->outputAUD = ctx->aud;
866 if (avctx->refs >= 0) {
867 /* 0 means "let the hardware decide" */
868 h264->maxNumRefFrames = avctx->refs;
870 if (avctx->gop_size >= 0) {
871 h264->idrPeriod = cc->gopLength;
874 if (IS_CBR(cc->rcParams.rateControlMode)) {
875 h264->outputBufferingPeriodSEI = 1;
876 h264->outputPictureTimingSEI = 1;
879 if (cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ ||
880 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_HQ ||
881 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_VBR_HQ) {
882 h264->adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
883 h264->fmoMode = NV_ENC_H264_FMO_DISABLE;
886 if (ctx->flags & NVENC_LOSSLESS) {
887 h264->qpPrimeYZeroTransformBypassFlag = 1;
889 switch(ctx->profile) {
890 case NV_ENC_H264_PROFILE_BASELINE:
891 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
892 avctx->profile = FF_PROFILE_H264_BASELINE;
894 case NV_ENC_H264_PROFILE_MAIN:
895 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
896 avctx->profile = FF_PROFILE_H264_MAIN;
898 case NV_ENC_H264_PROFILE_HIGH:
899 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
900 avctx->profile = FF_PROFILE_H264_HIGH;
902 case NV_ENC_H264_PROFILE_HIGH_444P:
903 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
904 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
909 // force setting profile as high444p if input is AV_PIX_FMT_YUV444P
910 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P) {
911 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
912 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
915 h264->chromaFormatIDC = avctx->profile == FF_PROFILE_H264_HIGH_444_PREDICTIVE ? 3 : 1;
917 h264->level = ctx->level;
922 static av_cold int nvenc_setup_hevc_config(AVCodecContext *avctx)
924 NvencContext *ctx = avctx->priv_data;
925 NV_ENC_CONFIG *cc = &ctx->encode_config;
926 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
927 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
929 vui->colourMatrix = avctx->colorspace;
930 vui->colourPrimaries = avctx->color_primaries;
931 vui->transferCharacteristics = avctx->color_trc;
932 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
933 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
935 vui->colourDescriptionPresentFlag =
936 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
938 vui->videoSignalTypePresentFlag =
939 (vui->colourDescriptionPresentFlag
940 || vui->videoFormat != 5
941 || vui->videoFullRangeFlag != 0);
944 hevc->sliceModeData = 1;
946 hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
947 hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
948 hevc->outputAUD = ctx->aud;
950 if (avctx->refs >= 0) {
951 /* 0 means "let the hardware decide" */
952 hevc->maxNumRefFramesInDPB = avctx->refs;
954 if (avctx->gop_size >= 0) {
955 hevc->idrPeriod = cc->gopLength;
958 if (IS_CBR(cc->rcParams.rateControlMode)) {
959 hevc->outputBufferingPeriodSEI = 1;
960 hevc->outputPictureTimingSEI = 1;
963 switch (ctx->profile) {
964 case NV_ENC_HEVC_PROFILE_MAIN:
965 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
966 avctx->profile = FF_PROFILE_HEVC_MAIN;
968 case NV_ENC_HEVC_PROFILE_MAIN_10:
969 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
970 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
972 case NV_ENC_HEVC_PROFILE_REXT:
973 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
974 avctx->profile = FF_PROFILE_HEVC_REXT;
978 // force setting profile as main10 if input is 10 bit
979 if (IS_10BIT(ctx->data_pix_fmt)) {
980 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
981 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
984 // force setting profile as rext if input is yuv444
985 if (IS_YUV444(ctx->data_pix_fmt)) {
986 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
987 avctx->profile = FF_PROFILE_HEVC_REXT;
990 hevc->chromaFormatIDC = IS_YUV444(ctx->data_pix_fmt) ? 3 : 1;
992 hevc->pixelBitDepthMinus8 = IS_10BIT(ctx->data_pix_fmt) ? 2 : 0;
994 hevc->level = ctx->level;
996 hevc->tier = ctx->tier;
1001 static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx)
1003 switch (avctx->codec->id) {
1004 case AV_CODEC_ID_H264:
1005 return nvenc_setup_h264_config(avctx);
1006 case AV_CODEC_ID_HEVC:
1007 return nvenc_setup_hevc_config(avctx);
1008 /* Earlier switch/case will return if unknown codec is passed. */
1014 static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
1016 NvencContext *ctx = avctx->priv_data;
1017 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1018 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1020 NV_ENC_PRESET_CONFIG preset_config = { 0 };
1021 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
1022 AVCPBProperties *cpb_props;
1028 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1029 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
1031 ctx->init_encode_params.encodeHeight = avctx->height;
1032 ctx->init_encode_params.encodeWidth = avctx->width;
1034 ctx->init_encode_params.encodeConfig = &ctx->encode_config;
1036 nvenc_map_preset(ctx);
1038 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
1039 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
1041 nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder,
1042 ctx->init_encode_params.encodeGUID,
1043 ctx->init_encode_params.presetGUID,
1045 if (nv_status != NV_ENC_SUCCESS)
1046 return nvenc_print_error(avctx, nv_status, "Cannot get the preset configuration");
1048 memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
1050 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1054 if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0) {
1055 dw*= avctx->sample_aspect_ratio.num;
1056 dh*= avctx->sample_aspect_ratio.den;
1058 av_reduce(&dw, &dh, dw, dh, 1024 * 1024);
1059 ctx->init_encode_params.darHeight = dh;
1060 ctx->init_encode_params.darWidth = dw;
1062 ctx->init_encode_params.frameRateNum = avctx->time_base.den;
1063 ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
1065 ctx->init_encode_params.enableEncodeAsync = 0;
1066 ctx->init_encode_params.enablePTD = 1;
1068 if (ctx->weighted_pred == 1)
1069 ctx->init_encode_params.enableWeightedPrediction = 1;
1071 if (ctx->bluray_compat) {
1073 avctx->refs = FFMIN(FFMAX(avctx->refs, 0), 6);
1074 avctx->max_b_frames = FFMIN(avctx->max_b_frames, 3);
1075 switch (avctx->codec->id) {
1076 case AV_CODEC_ID_H264:
1077 /* maximum level depends on used resolution */
1079 case AV_CODEC_ID_HEVC:
1080 ctx->level = NV_ENC_LEVEL_HEVC_51;
1081 ctx->tier = NV_ENC_TIER_HEVC_HIGH;
1086 if (avctx->gop_size > 0) {
1087 if (avctx->max_b_frames >= 0) {
1088 /* 0 is intra-only, 1 is I/P only, 2 is one B-Frame, 3 two B-frames, and so on. */
1089 ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
1092 ctx->encode_config.gopLength = avctx->gop_size;
1093 } else if (avctx->gop_size == 0) {
1094 ctx->encode_config.frameIntervalP = 0;
1095 ctx->encode_config.gopLength = 1;
1098 ctx->initial_pts[0] = AV_NOPTS_VALUE;
1099 ctx->initial_pts[1] = AV_NOPTS_VALUE;
1101 nvenc_recalc_surfaces(avctx);
1103 nvenc_setup_rate_control(avctx);
1105 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1106 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
1108 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
1111 res = nvenc_setup_codec_config(avctx);
1115 cu_res = dl_fn->cuda_dl->cuCtxPushCurrent(ctx->cu_context);
1116 if (cu_res != CUDA_SUCCESS) {
1117 av_log(avctx, AV_LOG_ERROR, "cuCtxPushCurrent failed\n");
1118 return AVERROR_EXTERNAL;
1121 nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
1123 cu_res = dl_fn->cuda_dl->cuCtxPopCurrent(&dummy);
1124 if (cu_res != CUDA_SUCCESS) {
1125 av_log(avctx, AV_LOG_ERROR, "cuCtxPopCurrent failed\n");
1126 return AVERROR_EXTERNAL;
1129 if (nv_status != NV_ENC_SUCCESS) {
1130 return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
1133 if (ctx->encode_config.frameIntervalP > 1)
1134 avctx->has_b_frames = 2;
1136 if (ctx->encode_config.rcParams.averageBitRate > 0)
1137 avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
1139 cpb_props = ff_add_cpb_side_data(avctx);
1141 return AVERROR(ENOMEM);
1142 cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
1143 cpb_props->avg_bitrate = avctx->bit_rate;
1144 cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
1149 static NV_ENC_BUFFER_FORMAT nvenc_map_buffer_format(enum AVPixelFormat pix_fmt)
1152 case AV_PIX_FMT_YUV420P:
1153 return NV_ENC_BUFFER_FORMAT_YV12_PL;
1154 case AV_PIX_FMT_NV12:
1155 return NV_ENC_BUFFER_FORMAT_NV12_PL;
1156 case AV_PIX_FMT_P010:
1157 return NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1158 case AV_PIX_FMT_YUV444P:
1159 return NV_ENC_BUFFER_FORMAT_YUV444_PL;
1160 case AV_PIX_FMT_YUV444P16:
1161 return NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1162 case AV_PIX_FMT_0RGB32:
1163 return NV_ENC_BUFFER_FORMAT_ARGB;
1164 case AV_PIX_FMT_0BGR32:
1165 return NV_ENC_BUFFER_FORMAT_ABGR;
1167 return NV_ENC_BUFFER_FORMAT_UNDEFINED;
1171 static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
1173 NvencContext *ctx = avctx->priv_data;
1174 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1175 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1176 NvencSurface* tmp_surface = &ctx->surfaces[idx];
1178 NVENCSTATUS nv_status;
1179 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
1180 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1182 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1183 ctx->surfaces[idx].in_ref = av_frame_alloc();
1184 if (!ctx->surfaces[idx].in_ref)
1185 return AVERROR(ENOMEM);
1187 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1189 ctx->surfaces[idx].format = nvenc_map_buffer_format(ctx->data_pix_fmt);
1190 if (ctx->surfaces[idx].format == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1191 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1192 av_get_pix_fmt_name(ctx->data_pix_fmt));
1193 return AVERROR(EINVAL);
1196 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1197 allocSurf.width = avctx->width;
1198 allocSurf.height = avctx->height;
1199 allocSurf.bufferFmt = ctx->surfaces[idx].format;
1201 nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
1202 if (nv_status != NV_ENC_SUCCESS) {
1203 return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
1206 ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
1207 ctx->surfaces[idx].width = allocSurf.width;
1208 ctx->surfaces[idx].height = allocSurf.height;
1211 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
1212 if (nv_status != NV_ENC_SUCCESS) {
1213 int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
1214 if (avctx->pix_fmt != AV_PIX_FMT_CUDA)
1215 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
1216 av_frame_free(&ctx->surfaces[idx].in_ref);
1220 ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1221 ctx->surfaces[idx].size = allocOut.size;
1223 av_fifo_generic_write(ctx->unused_surface_queue, &tmp_surface, sizeof(tmp_surface), NULL);
1228 static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx)
1230 NvencContext *ctx = avctx->priv_data;
1231 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1236 ctx->surfaces = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->surfaces));
1238 return AVERROR(ENOMEM);
1240 ctx->timestamp_list = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
1241 if (!ctx->timestamp_list)
1242 return AVERROR(ENOMEM);
1244 ctx->unused_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1245 if (!ctx->unused_surface_queue)
1246 return AVERROR(ENOMEM);
1248 ctx->output_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1249 if (!ctx->output_surface_queue)
1250 return AVERROR(ENOMEM);
1251 ctx->output_surface_ready_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1252 if (!ctx->output_surface_ready_queue)
1253 return AVERROR(ENOMEM);
1255 cu_res = dl_fn->cuda_dl->cuCtxPushCurrent(ctx->cu_context);
1256 if (cu_res != CUDA_SUCCESS) {
1257 av_log(avctx, AV_LOG_ERROR, "cuCtxPushCurrent failed\n");
1258 return AVERROR_EXTERNAL;
1261 for (i = 0; i < ctx->nb_surfaces; i++) {
1262 if ((res = nvenc_alloc_surface(avctx, i)) < 0)
1264 cu_res = dl_fn->cuda_dl->cuCtxPopCurrent(&dummy);
1265 if (cu_res != CUDA_SUCCESS) {
1266 av_log(avctx, AV_LOG_ERROR, "cuCtxPopCurrent failed\n");
1267 return AVERROR_EXTERNAL;
1273 cu_res = dl_fn->cuda_dl->cuCtxPopCurrent(&dummy);
1274 if (cu_res != CUDA_SUCCESS) {
1275 av_log(avctx, AV_LOG_ERROR, "cuCtxPopCurrent failed\n");
1276 return AVERROR_EXTERNAL;
1282 static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
1284 NvencContext *ctx = avctx->priv_data;
1285 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1286 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1288 NVENCSTATUS nv_status;
1289 uint32_t outSize = 0;
1290 char tmpHeader[256];
1291 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1292 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1294 payload.spsppsBuffer = tmpHeader;
1295 payload.inBufferSize = sizeof(tmpHeader);
1296 payload.outSPSPPSPayloadSize = &outSize;
1298 nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
1299 if (nv_status != NV_ENC_SUCCESS) {
1300 return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
1303 avctx->extradata_size = outSize;
1304 avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
1306 if (!avctx->extradata) {
1307 return AVERROR(ENOMEM);
1310 memcpy(avctx->extradata, tmpHeader, outSize);
1315 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
1317 NvencContext *ctx = avctx->priv_data;
1318 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1319 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1324 cu_res = dl_fn->cuda_dl->cuCtxPushCurrent(ctx->cu_context);
1325 if (cu_res != CUDA_SUCCESS) {
1326 av_log(avctx, AV_LOG_ERROR, "cuCtxPushCurrent failed\n");
1327 return AVERROR_EXTERNAL;
1330 /* the encoder has to be flushed before it can be closed */
1331 if (ctx->nvencoder) {
1332 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
1333 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
1335 p_nvenc->nvEncEncodePicture(ctx->nvencoder, ¶ms);
1338 av_fifo_freep(&ctx->timestamp_list);
1339 av_fifo_freep(&ctx->output_surface_ready_queue);
1340 av_fifo_freep(&ctx->output_surface_queue);
1341 av_fifo_freep(&ctx->unused_surface_queue);
1343 if (ctx->surfaces && avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1344 for (i = 0; i < ctx->nb_surfaces; ++i) {
1345 if (ctx->surfaces[i].input_surface) {
1346 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->surfaces[i].in_map.mappedResource);
1349 for (i = 0; i < ctx->nb_registered_frames; i++) {
1350 if (ctx->registered_frames[i].regptr)
1351 p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1353 ctx->nb_registered_frames = 0;
1356 if (ctx->surfaces) {
1357 for (i = 0; i < ctx->nb_surfaces; ++i) {
1358 if (avctx->pix_fmt != AV_PIX_FMT_CUDA)
1359 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
1360 av_frame_free(&ctx->surfaces[i].in_ref);
1361 p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
1364 av_freep(&ctx->surfaces);
1365 ctx->nb_surfaces = 0;
1368 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1369 ctx->nvencoder = NULL;
1371 cu_res = dl_fn->cuda_dl->cuCtxPopCurrent(&dummy);
1372 if (cu_res != CUDA_SUCCESS) {
1373 av_log(avctx, AV_LOG_ERROR, "cuCtxPopCurrent failed\n");
1374 return AVERROR_EXTERNAL;
1377 if (ctx->cu_context_internal)
1378 dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal);
1379 ctx->cu_context = ctx->cu_context_internal = NULL;
1381 nvenc_free_functions(&dl_fn->nvenc_dl);
1382 cuda_free_functions(&dl_fn->cuda_dl);
1384 dl_fn->nvenc_device_count = 0;
1386 av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
1391 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
1393 NvencContext *ctx = avctx->priv_data;
1396 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1397 AVHWFramesContext *frames_ctx;
1398 if (!avctx->hw_frames_ctx) {
1399 av_log(avctx, AV_LOG_ERROR,
1400 "hw_frames_ctx must be set when using GPU frames as input\n");
1401 return AVERROR(EINVAL);
1403 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1404 ctx->data_pix_fmt = frames_ctx->sw_format;
1406 ctx->data_pix_fmt = avctx->pix_fmt;
1409 if ((ret = nvenc_load_libraries(avctx)) < 0)
1412 if ((ret = nvenc_setup_device(avctx)) < 0)
1415 if ((ret = nvenc_setup_encoder(avctx)) < 0)
1418 if ((ret = nvenc_setup_surfaces(avctx)) < 0)
1421 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1422 if ((ret = nvenc_setup_extradata(avctx)) < 0)
1429 static NvencSurface *get_free_frame(NvencContext *ctx)
1431 NvencSurface *tmp_surf;
1433 if (!(av_fifo_size(ctx->unused_surface_queue) > 0))
1437 av_fifo_generic_read(ctx->unused_surface_queue, &tmp_surf, sizeof(tmp_surf), NULL);
1441 static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *nv_surface,
1442 NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params, const AVFrame *frame)
1444 int dst_linesize[4] = {
1445 lock_buffer_params->pitch,
1446 lock_buffer_params->pitch,
1447 lock_buffer_params->pitch,
1448 lock_buffer_params->pitch
1450 uint8_t *dst_data[4];
1453 if (frame->format == AV_PIX_FMT_YUV420P)
1454 dst_linesize[1] = dst_linesize[2] >>= 1;
1456 ret = av_image_fill_pointers(dst_data, frame->format, nv_surface->height,
1457 lock_buffer_params->bufferDataPtr, dst_linesize);
1461 if (frame->format == AV_PIX_FMT_YUV420P)
1462 FFSWAP(uint8_t*, dst_data[1], dst_data[2]);
1464 av_image_copy(dst_data, dst_linesize,
1465 (const uint8_t**)frame->data, frame->linesize, frame->format,
1466 avctx->width, avctx->height);
1471 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1473 NvencContext *ctx = avctx->priv_data;
1474 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1475 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1479 if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1480 for (i = 0; i < ctx->nb_registered_frames; i++) {
1481 if (!ctx->registered_frames[i].mapped) {
1482 if (ctx->registered_frames[i].regptr) {
1483 p_nvenc->nvEncUnregisterResource(ctx->nvencoder,
1484 ctx->registered_frames[i].regptr);
1485 ctx->registered_frames[i].regptr = NULL;
1491 return ctx->nb_registered_frames++;
1494 av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1495 return AVERROR(ENOMEM);
1498 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1500 NvencContext *ctx = avctx->priv_data;
1501 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1502 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1504 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frame->hw_frames_ctx->data;
1505 NV_ENC_REGISTER_RESOURCE reg;
1508 for (i = 0; i < ctx->nb_registered_frames; i++) {
1509 if (ctx->registered_frames[i].ptr == (CUdeviceptr)frame->data[0])
1513 idx = nvenc_find_free_reg_resource(avctx);
1517 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1518 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1519 reg.width = frames_ctx->width;
1520 reg.height = frames_ctx->height;
1521 reg.pitch = frame->linesize[0];
1522 reg.resourceToRegister = frame->data[0];
1524 reg.bufferFormat = nvenc_map_buffer_format(frames_ctx->sw_format);
1525 if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1526 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1527 av_get_pix_fmt_name(frames_ctx->sw_format));
1528 return AVERROR(EINVAL);
1531 ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, ®);
1532 if (ret != NV_ENC_SUCCESS) {
1533 nvenc_print_error(avctx, ret, "Error registering an input resource");
1534 return AVERROR_UNKNOWN;
1537 ctx->registered_frames[idx].ptr = (CUdeviceptr)frame->data[0];
1538 ctx->registered_frames[idx].regptr = reg.registeredResource;
1542 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1543 NvencSurface *nvenc_frame)
1545 NvencContext *ctx = avctx->priv_data;
1546 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1547 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1550 NVENCSTATUS nv_status;
1552 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1553 int reg_idx = nvenc_register_frame(avctx, frame);
1555 av_log(avctx, AV_LOG_ERROR, "Could not register an input CUDA frame\n");
1559 res = av_frame_ref(nvenc_frame->in_ref, frame);
1563 nvenc_frame->in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1564 nvenc_frame->in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1565 nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &nvenc_frame->in_map);
1566 if (nv_status != NV_ENC_SUCCESS) {
1567 av_frame_unref(nvenc_frame->in_ref);
1568 return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
1571 ctx->registered_frames[reg_idx].mapped = 1;
1572 nvenc_frame->reg_idx = reg_idx;
1573 nvenc_frame->input_surface = nvenc_frame->in_map.mappedResource;
1574 nvenc_frame->format = nvenc_frame->in_map.mappedBufferFmt;
1575 nvenc_frame->pitch = frame->linesize[0];
1578 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1580 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1581 lockBufferParams.inputBuffer = nvenc_frame->input_surface;
1583 nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
1584 if (nv_status != NV_ENC_SUCCESS) {
1585 return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
1588 nvenc_frame->pitch = lockBufferParams.pitch;
1589 res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
1591 nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
1592 if (nv_status != NV_ENC_SUCCESS) {
1593 return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
1600 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1601 NV_ENC_PIC_PARAMS *params)
1603 NvencContext *ctx = avctx->priv_data;
1605 switch (avctx->codec->id) {
1606 case AV_CODEC_ID_H264:
1607 params->codecPicParams.h264PicParams.sliceMode =
1608 ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1609 params->codecPicParams.h264PicParams.sliceModeData =
1610 ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1612 case AV_CODEC_ID_HEVC:
1613 params->codecPicParams.hevcPicParams.sliceMode =
1614 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1615 params->codecPicParams.hevcPicParams.sliceModeData =
1616 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1621 static inline void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
1623 av_fifo_generic_write(queue, ×tamp, sizeof(timestamp), NULL);
1626 static inline int64_t timestamp_queue_dequeue(AVFifoBuffer* queue)
1628 int64_t timestamp = AV_NOPTS_VALUE;
1629 if (av_fifo_size(queue) > 0)
1630 av_fifo_generic_read(queue, ×tamp, sizeof(timestamp), NULL);
1635 static int nvenc_set_timestamp(AVCodecContext *avctx,
1636 NV_ENC_LOCK_BITSTREAM *params,
1639 NvencContext *ctx = avctx->priv_data;
1641 pkt->pts = params->outputTimeStamp;
1643 /* generate the first dts by linearly extrapolating the
1644 * first two pts values to the past */
1645 if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
1646 ctx->initial_pts[1] != AV_NOPTS_VALUE) {
1647 int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
1650 if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
1651 (ts0 > 0 && ts1 < INT64_MIN + ts0))
1652 return AVERROR(ERANGE);
1655 if ((delta < 0 && ts0 > INT64_MAX + delta) ||
1656 (delta > 0 && ts0 < INT64_MIN + delta))
1657 return AVERROR(ERANGE);
1658 pkt->dts = ts0 - delta;
1660 ctx->first_packet_output = 1;
1664 pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
1669 static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
1671 NvencContext *ctx = avctx->priv_data;
1672 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1673 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1675 uint32_t slice_mode_data;
1676 uint32_t *slice_offsets = NULL;
1677 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1678 NVENCSTATUS nv_status;
1681 enum AVPictureType pict_type;
1683 switch (avctx->codec->id) {
1684 case AV_CODEC_ID_H264:
1685 slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1687 case AV_CODEC_ID_H265:
1688 slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1691 av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
1692 res = AVERROR(EINVAL);
1695 slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
1700 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1702 lock_params.doNotWait = 0;
1703 lock_params.outputBitstream = tmpoutsurf->output_surface;
1704 lock_params.sliceOffsets = slice_offsets;
1706 nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
1707 if (nv_status != NV_ENC_SUCCESS) {
1708 res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
1712 if (res = ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes,0)) {
1713 p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1717 memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1719 nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1720 if (nv_status != NV_ENC_SUCCESS)
1721 nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
1724 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1725 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, tmpoutsurf->in_map.mappedResource);
1726 av_frame_unref(tmpoutsurf->in_ref);
1727 ctx->registered_frames[tmpoutsurf->reg_idx].mapped = 0;
1729 tmpoutsurf->input_surface = NULL;
1732 switch (lock_params.pictureType) {
1733 case NV_ENC_PIC_TYPE_IDR:
1734 pkt->flags |= AV_PKT_FLAG_KEY;
1735 case NV_ENC_PIC_TYPE_I:
1736 pict_type = AV_PICTURE_TYPE_I;
1738 case NV_ENC_PIC_TYPE_P:
1739 pict_type = AV_PICTURE_TYPE_P;
1741 case NV_ENC_PIC_TYPE_B:
1742 pict_type = AV_PICTURE_TYPE_B;
1744 case NV_ENC_PIC_TYPE_BI:
1745 pict_type = AV_PICTURE_TYPE_BI;
1748 av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
1749 av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
1750 res = AVERROR_EXTERNAL;
1754 #if FF_API_CODED_FRAME
1755 FF_DISABLE_DEPRECATION_WARNINGS
1756 avctx->coded_frame->pict_type = pict_type;
1757 FF_ENABLE_DEPRECATION_WARNINGS
1760 ff_side_data_set_encoder_stats(pkt,
1761 (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
1763 res = nvenc_set_timestamp(avctx, &lock_params, pkt);
1767 av_free(slice_offsets);
1772 timestamp_queue_dequeue(ctx->timestamp_list);
1775 av_free(slice_offsets);
1780 static int output_ready(AVCodecContext *avctx, int flush)
1782 NvencContext *ctx = avctx->priv_data;
1783 int nb_ready, nb_pending;
1785 /* when B-frames are enabled, we wait for two initial timestamps to
1786 * calculate the first dts */
1787 if (!flush && avctx->max_b_frames > 0 &&
1788 (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
1791 nb_ready = av_fifo_size(ctx->output_surface_ready_queue) / sizeof(NvencSurface*);
1792 nb_pending = av_fifo_size(ctx->output_surface_queue) / sizeof(NvencSurface*);
1794 return nb_ready > 0;
1795 return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
1798 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1799 const AVFrame *frame, int *got_packet)
1801 NVENCSTATUS nv_status;
1804 NvencSurface *tmpoutsurf, *inSurf;
1807 NvencContext *ctx = avctx->priv_data;
1808 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1809 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1811 NV_ENC_PIC_PARAMS pic_params = { 0 };
1812 pic_params.version = NV_ENC_PIC_PARAMS_VER;
1815 inSurf = get_free_frame(ctx);
1817 av_log(avctx, AV_LOG_ERROR, "No free surfaces\n");
1821 cu_res = dl_fn->cuda_dl->cuCtxPushCurrent(ctx->cu_context);
1822 if (cu_res != CUDA_SUCCESS) {
1823 av_log(avctx, AV_LOG_ERROR, "cuCtxPushCurrent failed\n");
1824 return AVERROR_EXTERNAL;
1827 res = nvenc_upload_frame(avctx, frame, inSurf);
1829 cu_res = dl_fn->cuda_dl->cuCtxPopCurrent(&dummy);
1830 if (cu_res != CUDA_SUCCESS) {
1831 av_log(avctx, AV_LOG_ERROR, "cuCtxPopCurrent failed\n");
1832 return AVERROR_EXTERNAL;
1839 pic_params.inputBuffer = inSurf->input_surface;
1840 pic_params.bufferFmt = inSurf->format;
1841 pic_params.inputWidth = inSurf->width;
1842 pic_params.inputHeight = inSurf->height;
1843 pic_params.inputPitch = inSurf->pitch;
1844 pic_params.outputBitstream = inSurf->output_surface;
1846 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1847 if (frame->top_field_first)
1848 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
1850 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
1852 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1855 if (ctx->forced_idr >= 0 && frame->pict_type == AV_PICTURE_TYPE_I) {
1856 pic_params.encodePicFlags =
1857 ctx->forced_idr ? NV_ENC_PIC_FLAG_FORCEIDR : NV_ENC_PIC_FLAG_FORCEINTRA;
1859 pic_params.encodePicFlags = 0;
1862 pic_params.inputTimeStamp = frame->pts;
1864 nvenc_codec_specific_pic_params(avctx, &pic_params);
1866 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1869 cu_res = dl_fn->cuda_dl->cuCtxPushCurrent(ctx->cu_context);
1870 if (cu_res != CUDA_SUCCESS) {
1871 av_log(avctx, AV_LOG_ERROR, "cuCtxPushCurrent failed\n");
1872 return AVERROR_EXTERNAL;
1875 nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
1877 cu_res = dl_fn->cuda_dl->cuCtxPopCurrent(&dummy);
1878 if (cu_res != CUDA_SUCCESS) {
1879 av_log(avctx, AV_LOG_ERROR, "cuCtxPopCurrent failed\n");
1880 return AVERROR_EXTERNAL;
1883 if (nv_status != NV_ENC_SUCCESS &&
1884 nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
1885 return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
1888 av_fifo_generic_write(ctx->output_surface_queue, &inSurf, sizeof(inSurf), NULL);
1889 timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
1891 if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
1892 ctx->initial_pts[0] = frame->pts;
1893 else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
1894 ctx->initial_pts[1] = frame->pts;
1897 /* all the pending buffers are now ready for output */
1898 if (nv_status == NV_ENC_SUCCESS) {
1899 while (av_fifo_size(ctx->output_surface_queue) > 0) {
1900 av_fifo_generic_read(ctx->output_surface_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
1901 av_fifo_generic_write(ctx->output_surface_ready_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
1905 if (output_ready(avctx, !frame)) {
1906 av_fifo_generic_read(ctx->output_surface_ready_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
1908 cu_res = dl_fn->cuda_dl->cuCtxPushCurrent(ctx->cu_context);
1909 if (cu_res != CUDA_SUCCESS) {
1910 av_log(avctx, AV_LOG_ERROR, "cuCtxPushCurrent failed\n");
1911 return AVERROR_EXTERNAL;
1914 res = process_output_surface(avctx, pkt, tmpoutsurf);
1916 cu_res = dl_fn->cuda_dl->cuCtxPopCurrent(&dummy);
1917 if (cu_res != CUDA_SUCCESS) {
1918 av_log(avctx, AV_LOG_ERROR, "cuCtxPopCurrent failed\n");
1919 return AVERROR_EXTERNAL;
1925 av_fifo_generic_write(ctx->unused_surface_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);