2 * H.264 hardware encoding using nvidia nvenc
3 * Copyright (c) 2014 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
30 #include "libavutil/imgutils.h"
31 #include "libavutil/avassert.h"
32 #include "libavutil/mem.h"
33 #include "libavutil/hwcontext.h"
40 #include "libavutil/hwcontext_cuda.h"
43 #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR || \
44 rc == NV_ENC_PARAMS_RC_2_PASS_QUALITY || \
45 rc == NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP)
48 #define LOAD_FUNC(l, s) GetProcAddress(l, s)
49 #define DL_CLOSE_FUNC(l) FreeLibrary(l)
51 #define LOAD_FUNC(l, s) dlsym(l, s)
52 #define DL_CLOSE_FUNC(l) dlclose(l)
55 const enum AVPixelFormat ff_nvenc_pix_fmts[] = {
65 typedef struct NvencData
69 NvencSurface *surface;
78 { NV_ENC_SUCCESS, 0, "success" },
79 { NV_ENC_ERR_NO_ENCODE_DEVICE, AVERROR(ENOENT), "no encode device" },
80 { NV_ENC_ERR_UNSUPPORTED_DEVICE, AVERROR(ENOSYS), "unsupported device" },
81 { NV_ENC_ERR_INVALID_ENCODERDEVICE, AVERROR(EINVAL), "invalid encoder device" },
82 { NV_ENC_ERR_INVALID_DEVICE, AVERROR(EINVAL), "invalid device" },
83 { NV_ENC_ERR_DEVICE_NOT_EXIST, AVERROR(EIO), "device does not exist" },
84 { NV_ENC_ERR_INVALID_PTR, AVERROR(EFAULT), "invalid ptr" },
85 { NV_ENC_ERR_INVALID_EVENT, AVERROR(EINVAL), "invalid event" },
86 { NV_ENC_ERR_INVALID_PARAM, AVERROR(EINVAL), "invalid param" },
87 { NV_ENC_ERR_INVALID_CALL, AVERROR(EINVAL), "invalid call" },
88 { NV_ENC_ERR_OUT_OF_MEMORY, AVERROR(ENOMEM), "out of memory" },
89 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED, AVERROR(EINVAL), "encoder not initialized" },
90 { NV_ENC_ERR_UNSUPPORTED_PARAM, AVERROR(ENOSYS), "unsupported param" },
91 { NV_ENC_ERR_LOCK_BUSY, AVERROR(EAGAIN), "lock busy" },
92 { NV_ENC_ERR_NOT_ENOUGH_BUFFER, AVERROR(ENOBUFS), "not enough buffer" },
93 { NV_ENC_ERR_INVALID_VERSION, AVERROR(EINVAL), "invalid version" },
94 { NV_ENC_ERR_MAP_FAILED, AVERROR(EIO), "map failed" },
95 { NV_ENC_ERR_NEED_MORE_INPUT, AVERROR(EAGAIN), "need more input" },
96 { NV_ENC_ERR_ENCODER_BUSY, AVERROR(EAGAIN), "encoder busy" },
97 { NV_ENC_ERR_EVENT_NOT_REGISTERD, AVERROR(EBADF), "event not registered" },
98 { NV_ENC_ERR_GENERIC, AVERROR_UNKNOWN, "generic error" },
99 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY, AVERROR(EINVAL), "incompatible client key" },
100 { NV_ENC_ERR_UNIMPLEMENTED, AVERROR(ENOSYS), "unimplemented" },
101 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO), "resource register failed" },
102 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED, AVERROR(EBADF), "resource not registered" },
103 { NV_ENC_ERR_RESOURCE_NOT_MAPPED, AVERROR(EBADF), "resource not mapped" },
106 static int nvenc_map_error(NVENCSTATUS err, const char **desc)
109 for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
110 if (nvenc_errors[i].nverr == err) {
112 *desc = nvenc_errors[i].desc;
113 return nvenc_errors[i].averr;
117 *desc = "unknown error";
118 return AVERROR_UNKNOWN;
121 static int nvenc_print_error(void *log_ctx, NVENCSTATUS err,
122 const char *error_string)
126 ret = nvenc_map_error(err, &desc);
127 av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
131 static void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
133 av_fifo_generic_write(queue, ×tamp, sizeof(timestamp), NULL);
136 static int64_t timestamp_queue_dequeue(AVFifoBuffer* queue)
138 int64_t timestamp = AV_NOPTS_VALUE;
139 if (av_fifo_size(queue) > 0)
140 av_fifo_generic_read(queue, ×tamp, sizeof(timestamp), NULL);
145 #define CHECK_LOAD_FUNC(t, f, s) \
147 (f) = (t)LOAD_FUNC(dl_fn->cuda_lib, s); \
149 av_log(avctx, AV_LOG_FATAL, "Failed loading %s from CUDA library\n", s); \
154 static av_cold int nvenc_dyload_cuda(AVCodecContext *avctx)
156 NvencContext *ctx = avctx->priv_data;
157 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
160 dl_fn->cu_init = cuInit;
161 dl_fn->cu_device_get_count = cuDeviceGetCount;
162 dl_fn->cu_device_get = cuDeviceGet;
163 dl_fn->cu_device_get_name = cuDeviceGetName;
164 dl_fn->cu_device_compute_capability = cuDeviceComputeCapability;
165 dl_fn->cu_ctx_create = cuCtxCreate_v2;
166 dl_fn->cu_ctx_pop_current = cuCtxPopCurrent_v2;
167 dl_fn->cu_ctx_destroy = cuCtxDestroy_v2;
175 dl_fn->cuda_lib = LoadLibrary(TEXT("nvcuda.dll"));
177 dl_fn->cuda_lib = dlopen("libcuda.so", RTLD_LAZY);
180 if (!dl_fn->cuda_lib) {
181 av_log(avctx, AV_LOG_FATAL, "Failed loading CUDA library\n");
185 CHECK_LOAD_FUNC(PCUINIT, dl_fn->cu_init, "cuInit");
186 CHECK_LOAD_FUNC(PCUDEVICEGETCOUNT, dl_fn->cu_device_get_count, "cuDeviceGetCount");
187 CHECK_LOAD_FUNC(PCUDEVICEGET, dl_fn->cu_device_get, "cuDeviceGet");
188 CHECK_LOAD_FUNC(PCUDEVICEGETNAME, dl_fn->cu_device_get_name, "cuDeviceGetName");
189 CHECK_LOAD_FUNC(PCUDEVICECOMPUTECAPABILITY, dl_fn->cu_device_compute_capability, "cuDeviceComputeCapability");
190 CHECK_LOAD_FUNC(PCUCTXCREATE, dl_fn->cu_ctx_create, "cuCtxCreate_v2");
191 CHECK_LOAD_FUNC(PCUCTXPOPCURRENT, dl_fn->cu_ctx_pop_current, "cuCtxPopCurrent_v2");
192 CHECK_LOAD_FUNC(PCUCTXDESTROY, dl_fn->cu_ctx_destroy, "cuCtxDestroy_v2");
199 DL_CLOSE_FUNC(dl_fn->cuda_lib);
201 dl_fn->cuda_lib = NULL;
207 static av_cold int check_cuda_errors(AVCodecContext *avctx, CUresult err, const char *func)
209 if (err != CUDA_SUCCESS) {
210 av_log(avctx, AV_LOG_FATAL, ">> %s - failed with error code 0x%x\n", func, err);
215 #define check_cuda_errors(f) if (!check_cuda_errors(avctx, f, #f)) goto error
217 static av_cold int nvenc_check_cuda(AVCodecContext *avctx)
219 int device_count = 0;
220 CUdevice cu_device = 0;
222 int smminor = 0, smmajor = 0;
223 int i, smver, target_smver;
225 NvencContext *ctx = avctx->priv_data;
226 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
228 switch (avctx->codec->id) {
229 case AV_CODEC_ID_H264:
230 target_smver = ctx->data_pix_fmt == AV_PIX_FMT_YUV444P ? 0x52 : 0x30;
232 case AV_CODEC_ID_H265:
236 av_log(avctx, AV_LOG_FATAL, "Unknown codec name\n");
240 if (ctx->preset >= PRESET_LOSSLESS_DEFAULT)
243 if (!nvenc_dyload_cuda(avctx))
246 if (dl_fn->nvenc_device_count > 0)
249 check_cuda_errors(dl_fn->cu_init(0));
251 check_cuda_errors(dl_fn->cu_device_get_count(&device_count));
254 av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
258 av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", device_count);
260 dl_fn->nvenc_device_count = 0;
262 for (i = 0; i < device_count; ++i) {
263 check_cuda_errors(dl_fn->cu_device_get(&cu_device, i));
264 check_cuda_errors(dl_fn->cu_device_get_name(gpu_name, sizeof(gpu_name), cu_device));
265 check_cuda_errors(dl_fn->cu_device_compute_capability(&smmajor, &smminor, cu_device));
267 smver = (smmajor << 4) | smminor;
269 av_log(avctx, AV_LOG_VERBOSE, "[ GPU #%d - < %s > has Compute SM %d.%d, NVENC %s ]\n", i, gpu_name, smmajor, smminor, (smver >= target_smver) ? "Available" : "Not Available");
271 if (smver >= target_smver)
272 dl_fn->nvenc_devices[dl_fn->nvenc_device_count++] = cu_device;
275 if (!dl_fn->nvenc_device_count) {
276 av_log(avctx, AV_LOG_FATAL, "No NVENC capable devices found\n");
284 dl_fn->nvenc_device_count = 0;
289 static av_cold int nvenc_dyload_nvenc(AVCodecContext *avctx)
291 PNVENCODEAPICREATEINSTANCE nvEncodeAPICreateInstance = 0;
292 NVENCSTATUS nvstatus;
294 NvencContext *ctx = avctx->priv_data;
295 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
297 if (!nvenc_check_cuda(avctx))
300 if (dl_fn->nvenc_lib)
304 if (sizeof(void*) == 8) {
305 dl_fn->nvenc_lib = LoadLibrary(TEXT("nvEncodeAPI64.dll"));
307 dl_fn->nvenc_lib = LoadLibrary(TEXT("nvEncodeAPI.dll"));
310 dl_fn->nvenc_lib = dlopen("libnvidia-encode.so.1", RTLD_LAZY);
313 if (!dl_fn->nvenc_lib) {
314 av_log(avctx, AV_LOG_FATAL, "Failed loading the nvenc library\n");
318 nvEncodeAPICreateInstance = (PNVENCODEAPICREATEINSTANCE)LOAD_FUNC(dl_fn->nvenc_lib, "NvEncodeAPICreateInstance");
320 if (!nvEncodeAPICreateInstance) {
321 av_log(avctx, AV_LOG_FATAL, "Failed to load nvenc entrypoint\n");
325 dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
327 nvstatus = nvEncodeAPICreateInstance(&dl_fn->nvenc_funcs);
329 if (nvstatus != NV_ENC_SUCCESS) {
330 nvenc_print_error(avctx, nvstatus, "Failed to create nvenc instance");
334 av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
339 if (dl_fn->nvenc_lib)
340 DL_CLOSE_FUNC(dl_fn->nvenc_lib);
342 dl_fn->nvenc_lib = NULL;
347 static av_cold void nvenc_unload_nvenc(AVCodecContext *avctx)
349 NvencContext *ctx = avctx->priv_data;
350 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
352 DL_CLOSE_FUNC(dl_fn->nvenc_lib);
353 dl_fn->nvenc_lib = NULL;
355 dl_fn->nvenc_device_count = 0;
358 DL_CLOSE_FUNC(dl_fn->cuda_lib);
359 dl_fn->cuda_lib = NULL;
362 dl_fn->cu_init = NULL;
363 dl_fn->cu_device_get_count = NULL;
364 dl_fn->cu_device_get = NULL;
365 dl_fn->cu_device_get_name = NULL;
366 dl_fn->cu_device_compute_capability = NULL;
367 dl_fn->cu_ctx_create = NULL;
368 dl_fn->cu_ctx_pop_current = NULL;
369 dl_fn->cu_ctx_destroy = NULL;
371 av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
374 static av_cold int nvenc_setup_device(AVCodecContext *avctx)
376 NvencContext *ctx = avctx->priv_data;
377 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
380 CUcontext cu_context_curr;
382 switch (avctx->codec->id) {
383 case AV_CODEC_ID_H264:
384 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
386 case AV_CODEC_ID_HEVC:
387 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
393 ctx->data_pix_fmt = avctx->pix_fmt;
396 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
397 AVHWFramesContext *frames_ctx;
398 AVCUDADeviceContext *device_hwctx;
400 if (!avctx->hw_frames_ctx) {
401 av_log(avctx, AV_LOG_ERROR, "hw_frames_ctx must be set when using GPU frames as input\n");
402 return AVERROR(EINVAL);
405 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
406 device_hwctx = frames_ctx->device_ctx->hwctx;
407 ctx->cu_context = device_hwctx->cuda_ctx;
408 ctx->data_pix_fmt = frames_ctx->sw_format;
413 if (ctx->gpu >= dl_fn->nvenc_device_count) {
414 av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->gpu, dl_fn->nvenc_device_count);
415 return AVERROR(EINVAL);
418 ctx->cu_context = NULL;
419 cu_res = dl_fn->cu_ctx_create(&ctx->cu_context_internal, 4, dl_fn->nvenc_devices[ctx->gpu]); // CU_CTX_SCHED_BLOCKING_SYNC=4, avoid CPU spins
421 if (cu_res != CUDA_SUCCESS) {
422 av_log(avctx, AV_LOG_FATAL, "Failed creating CUDA context for NVENC: 0x%x\n", (int)cu_res);
423 return AVERROR_EXTERNAL;
426 cu_res = dl_fn->cu_ctx_pop_current(&cu_context_curr);
428 if (cu_res != CUDA_SUCCESS) {
429 av_log(avctx, AV_LOG_FATAL, "Failed popping CUDA context: 0x%x\n", (int)cu_res);
430 return AVERROR_EXTERNAL;
433 ctx->cu_context = ctx->cu_context_internal;
438 static av_cold int nvenc_open_session(AVCodecContext *avctx)
440 NvencContext *ctx = avctx->priv_data;
441 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
442 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
444 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS encode_session_params = { 0 };
445 NVENCSTATUS nv_status;
447 encode_session_params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
448 encode_session_params.apiVersion = NVENCAPI_VERSION;
449 encode_session_params.device = ctx->cu_context;
450 encode_session_params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
452 nv_status = p_nvenc->nvEncOpenEncodeSessionEx(&encode_session_params, &ctx->nvencoder);
453 if (nv_status != NV_ENC_SUCCESS) {
454 ctx->nvencoder = NULL;
455 return nvenc_print_error(avctx, nv_status, "OpenEncodeSessionEx failed");
461 typedef struct GUIDTuple {
466 static void nvenc_map_preset(NvencContext *ctx)
468 GUIDTuple presets[] = {
469 { NV_ENC_PRESET_DEFAULT_GUID },
470 { NV_ENC_PRESET_HQ_GUID, NVENC_TWO_PASSES }, /* slow */
471 { NV_ENC_PRESET_HQ_GUID, NVENC_ONE_PASS }, /* medium */
472 { NV_ENC_PRESET_HP_GUID, NVENC_ONE_PASS }, /* fast */
473 { NV_ENC_PRESET_HP_GUID },
474 { NV_ENC_PRESET_HQ_GUID },
475 { NV_ENC_PRESET_BD_GUID },
476 { NV_ENC_PRESET_LOW_LATENCY_DEFAULT_GUID, NVENC_LOWLATENCY },
477 { NV_ENC_PRESET_LOW_LATENCY_HQ_GUID, NVENC_LOWLATENCY },
478 { NV_ENC_PRESET_LOW_LATENCY_HP_GUID, NVENC_LOWLATENCY },
479 { NV_ENC_PRESET_LOSSLESS_DEFAULT_GUID, NVENC_LOSSLESS },
480 { NV_ENC_PRESET_LOSSLESS_HP_GUID, NVENC_LOSSLESS },
483 GUIDTuple *t = &presets[ctx->preset];
485 ctx->init_encode_params.presetGUID = t->guid;
486 ctx->flags = t->flags;
489 static av_cold void set_constqp(AVCodecContext *avctx)
491 NvencContext *ctx = avctx->priv_data;
492 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
494 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
495 rc->constQP.qpInterB = avctx->global_quality;
496 rc->constQP.qpInterP = avctx->global_quality;
497 rc->constQP.qpIntra = avctx->global_quality;
503 static av_cold void set_vbr(AVCodecContext *avctx)
505 NvencContext *ctx = avctx->priv_data;
506 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
509 if (avctx->qmin >= 0 && avctx->qmax >= 0) {
513 rc->minQP.qpInterB = avctx->qmin;
514 rc->minQP.qpInterP = avctx->qmin;
515 rc->minQP.qpIntra = avctx->qmin;
517 rc->maxQP.qpInterB = avctx->qmax;
518 rc->maxQP.qpInterP = avctx->qmax;
519 rc->maxQP.qpIntra = avctx->qmax;
521 qp_inter_p = (avctx->qmax + 3 * avctx->qmin) / 4; // biased towards Qmin
523 qp_inter_p = 26; // default to 26
526 rc->enableInitialRCQP = 1;
527 rc->initialRCQP.qpInterP = qp_inter_p;
529 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
530 rc->initialRCQP.qpIntra = av_clip(
531 qp_inter_p * fabs(avctx->i_quant_factor) + avctx->i_quant_offset, 0, 51);
532 rc->initialRCQP.qpInterB = av_clip(
533 qp_inter_p * fabs(avctx->b_quant_factor) + avctx->b_quant_offset, 0, 51);
535 rc->initialRCQP.qpIntra = qp_inter_p;
536 rc->initialRCQP.qpInterB = qp_inter_p;
540 static av_cold void set_lossless(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;
546 rc->constQP.qpInterB = 0;
547 rc->constQP.qpInterP = 0;
548 rc->constQP.qpIntra = 0;
554 static void nvenc_override_rate_control(AVCodecContext *avctx)
556 NvencContext *ctx = avctx->priv_data;
557 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
560 case NV_ENC_PARAMS_RC_CONSTQP:
561 if (avctx->global_quality <= 0) {
562 av_log(avctx, AV_LOG_WARNING,
563 "The constant quality rate-control requires "
564 "the 'global_quality' option set.\n");
569 case NV_ENC_PARAMS_RC_2_PASS_VBR:
570 case NV_ENC_PARAMS_RC_VBR:
571 if (avctx->qmin < 0 && avctx->qmax < 0) {
572 av_log(avctx, AV_LOG_WARNING,
573 "The variable bitrate rate-control requires "
574 "the 'qmin' and/or 'qmax' option set.\n");
578 case NV_ENC_PARAMS_RC_VBR_MINQP:
579 if (avctx->qmin < 0) {
580 av_log(avctx, AV_LOG_WARNING,
581 "The variable bitrate rate-control requires "
582 "the 'qmin' option set.\n");
588 case NV_ENC_PARAMS_RC_CBR:
590 case NV_ENC_PARAMS_RC_2_PASS_QUALITY:
591 case NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP:
592 if (!(ctx->flags & NVENC_LOWLATENCY)) {
593 av_log(avctx, AV_LOG_WARNING,
594 "The multipass rate-control requires "
595 "a low-latency preset.\n");
600 rc->rateControlMode = ctx->rc;
603 static av_cold void nvenc_setup_rate_control(AVCodecContext *avctx)
605 NvencContext *ctx = avctx->priv_data;
607 if (avctx->bit_rate > 0) {
608 ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
609 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
610 ctx->encode_config.rcParams.maxBitRate = ctx->encode_config.rcParams.averageBitRate;
613 if (avctx->rc_max_rate > 0)
614 ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
617 if (ctx->flags & NVENC_ONE_PASS)
619 if (ctx->flags & NVENC_TWO_PASSES)
622 if (ctx->twopass < 0)
623 ctx->twopass = (ctx->flags & NVENC_LOWLATENCY) != 0;
627 ctx->rc = NV_ENC_PARAMS_RC_2_PASS_QUALITY;
629 ctx->rc = NV_ENC_PARAMS_RC_CBR;
631 } else if (avctx->global_quality > 0) {
632 ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
633 } else if (ctx->twopass) {
634 ctx->rc = NV_ENC_PARAMS_RC_2_PASS_VBR;
635 } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
636 ctx->rc = NV_ENC_PARAMS_RC_VBR_MINQP;
640 if (ctx->flags & NVENC_LOSSLESS) {
642 } else if (ctx->rc > 0) {
643 nvenc_override_rate_control(avctx);
645 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
649 if (avctx->rc_buffer_size > 0) {
650 ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
651 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
652 ctx->encode_config.rcParams.vbvBufferSize = 2 * ctx->encode_config.rcParams.averageBitRate;
656 static av_cold int nvenc_setup_h264_config(AVCodecContext *avctx)
658 NvencContext *ctx = avctx->priv_data;
659 NV_ENC_CONFIG *cc = &ctx->encode_config;
660 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
661 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
663 vui->colourMatrix = avctx->colorspace;
664 vui->colourPrimaries = avctx->color_primaries;
665 vui->transferCharacteristics = avctx->color_trc;
666 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
667 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
669 vui->colourDescriptionPresentFlag =
670 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
672 vui->videoSignalTypePresentFlag =
673 (vui->colourDescriptionPresentFlag
674 || vui->videoFormat != 5
675 || vui->videoFullRangeFlag != 0);
678 h264->sliceModeData = 1;
680 h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
681 h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
684 if (avctx->refs >= 0) {
685 /* 0 means "let the hardware decide" */
686 h264->maxNumRefFrames = avctx->refs;
688 if (avctx->gop_size >= 0) {
689 h264->idrPeriod = cc->gopLength;
692 if (IS_CBR(cc->rcParams.rateControlMode)) {
693 h264->outputBufferingPeriodSEI = 1;
694 h264->outputPictureTimingSEI = 1;
697 if (cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_2_PASS_QUALITY ||
698 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP ||
699 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_2_PASS_VBR) {
700 h264->adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
701 h264->fmoMode = NV_ENC_H264_FMO_DISABLE;
704 if (ctx->flags & NVENC_LOSSLESS) {
705 h264->qpPrimeYZeroTransformBypassFlag = 1;
707 switch(ctx->profile) {
708 case NV_ENC_H264_PROFILE_BASELINE:
709 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
710 avctx->profile = FF_PROFILE_H264_BASELINE;
712 case NV_ENC_H264_PROFILE_MAIN:
713 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
714 avctx->profile = FF_PROFILE_H264_MAIN;
716 case NV_ENC_H264_PROFILE_HIGH:
717 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
718 avctx->profile = FF_PROFILE_H264_HIGH;
720 case NV_ENC_H264_PROFILE_HIGH_444P:
721 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
722 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
727 // force setting profile as high444p if input is AV_PIX_FMT_YUV444P
728 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P) {
729 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
730 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
733 h264->chromaFormatIDC = avctx->profile == FF_PROFILE_H264_HIGH_444_PREDICTIVE ? 3 : 1;
735 h264->level = ctx->level;
740 static av_cold int nvenc_setup_hevc_config(AVCodecContext *avctx)
742 NvencContext *ctx = avctx->priv_data;
743 NV_ENC_CONFIG *cc = &ctx->encode_config;
744 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
745 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
747 vui->colourMatrix = avctx->colorspace;
748 vui->colourPrimaries = avctx->color_primaries;
749 vui->transferCharacteristics = avctx->color_trc;
750 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
751 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
753 vui->colourDescriptionPresentFlag =
754 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
756 vui->videoSignalTypePresentFlag =
757 (vui->colourDescriptionPresentFlag
758 || vui->videoFormat != 5
759 || vui->videoFullRangeFlag != 0);
762 hevc->sliceModeData = 1;
764 hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
765 hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
768 if (avctx->refs >= 0) {
769 /* 0 means "let the hardware decide" */
770 hevc->maxNumRefFramesInDPB = avctx->refs;
772 if (avctx->gop_size >= 0) {
773 hevc->idrPeriod = cc->gopLength;
776 if (IS_CBR(cc->rcParams.rateControlMode)) {
777 hevc->outputBufferingPeriodSEI = 1;
778 hevc->outputPictureTimingSEI = 1;
781 /* No other profile is supported in the current SDK version 5 */
782 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
783 avctx->profile = FF_PROFILE_HEVC_MAIN;
785 hevc->level = ctx->level;
787 hevc->tier = ctx->tier;
792 static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx)
794 switch (avctx->codec->id) {
795 case AV_CODEC_ID_H264:
796 return nvenc_setup_h264_config(avctx);
797 case AV_CODEC_ID_HEVC:
798 return nvenc_setup_hevc_config(avctx);
799 /* Earlier switch/case will return if unknown codec is passed. */
805 static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
807 NvencContext *ctx = avctx->priv_data;
808 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
809 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
811 NV_ENC_PRESET_CONFIG preset_config = { 0 };
812 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
813 AVCPBProperties *cpb_props;
818 ctx->last_dts = AV_NOPTS_VALUE;
820 ctx->encode_config.version = NV_ENC_CONFIG_VER;
821 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
823 ctx->init_encode_params.encodeHeight = avctx->height;
824 ctx->init_encode_params.encodeWidth = avctx->width;
826 ctx->init_encode_params.encodeConfig = &ctx->encode_config;
828 nvenc_map_preset(ctx);
830 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
831 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
833 nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder,
834 ctx->init_encode_params.encodeGUID,
835 ctx->init_encode_params.presetGUID,
837 if (nv_status != NV_ENC_SUCCESS)
838 return nvenc_print_error(avctx, nv_status, "Cannot get the preset configuration");
840 memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
842 ctx->encode_config.version = NV_ENC_CONFIG_VER;
844 if (avctx->sample_aspect_ratio.num && avctx->sample_aspect_ratio.den &&
845 (avctx->sample_aspect_ratio.num != 1 || avctx->sample_aspect_ratio.num != 1)) {
847 avctx->width * avctx->sample_aspect_ratio.num,
848 avctx->height * avctx->sample_aspect_ratio.den,
850 ctx->init_encode_params.darHeight = dh;
851 ctx->init_encode_params.darWidth = dw;
853 ctx->init_encode_params.darHeight = avctx->height;
854 ctx->init_encode_params.darWidth = avctx->width;
857 // De-compensate for hardware, dubiously, trying to compensate for
858 // playback at 704 pixel width.
859 if (avctx->width == 720 &&
860 (avctx->height == 480 || avctx->height == 576)) {
862 ctx->init_encode_params.darWidth * 44,
863 ctx->init_encode_params.darHeight * 45,
865 ctx->init_encode_params.darHeight = dh;
866 ctx->init_encode_params.darWidth = dw;
869 ctx->init_encode_params.frameRateNum = avctx->time_base.den;
870 ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
872 num_mbs = ((avctx->width + 15) >> 4) * ((avctx->height + 15) >> 4);
873 ctx->max_surface_count = (num_mbs >= 8160) ? 32 : 48;
875 if (ctx->buffer_delay >= ctx->max_surface_count)
876 ctx->buffer_delay = ctx->max_surface_count - 1;
878 ctx->init_encode_params.enableEncodeAsync = 0;
879 ctx->init_encode_params.enablePTD = 1;
881 if (avctx->gop_size > 0) {
882 if (avctx->max_b_frames >= 0) {
883 /* 0 is intra-only, 1 is I/P only, 2 is one B Frame, 3 two B frames, and so on. */
884 ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
887 ctx->encode_config.gopLength = avctx->gop_size;
888 } else if (avctx->gop_size == 0) {
889 ctx->encode_config.frameIntervalP = 0;
890 ctx->encode_config.gopLength = 1;
893 /* when there're b frames, set dts offset */
894 if (ctx->encode_config.frameIntervalP >= 2)
897 nvenc_setup_rate_control(avctx);
899 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
900 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
902 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
905 res = nvenc_setup_codec_config(avctx);
909 nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
910 if (nv_status != NV_ENC_SUCCESS) {
911 return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
914 if (ctx->encode_config.frameIntervalP > 1)
915 avctx->has_b_frames = 2;
917 if (ctx->encode_config.rcParams.averageBitRate > 0)
918 avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
920 cpb_props = ff_add_cpb_side_data(avctx);
922 return AVERROR(ENOMEM);
923 cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
924 cpb_props->avg_bitrate = avctx->bit_rate;
925 cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
930 static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
932 NvencContext *ctx = avctx->priv_data;
933 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
934 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
936 NVENCSTATUS nv_status;
937 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
938 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
940 switch (ctx->data_pix_fmt) {
941 case AV_PIX_FMT_YUV420P:
942 ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_YV12_PL;
945 case AV_PIX_FMT_NV12:
946 ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_NV12_PL;
949 case AV_PIX_FMT_YUV444P:
950 ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_YUV444_PL;
954 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format\n");
955 return AVERROR(EINVAL);
958 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
959 ctx->surfaces[idx].in_ref = av_frame_alloc();
960 if (!ctx->surfaces[idx].in_ref)
961 return AVERROR(ENOMEM);
963 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
964 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
965 allocSurf.width = (avctx->width + 31) & ~31;
966 allocSurf.height = (avctx->height + 31) & ~31;
967 allocSurf.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
968 allocSurf.bufferFmt = ctx->surfaces[idx].format;
970 nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
971 if (nv_status != NV_ENC_SUCCESS) {
972 return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
975 ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
976 ctx->surfaces[idx].width = allocSurf.width;
977 ctx->surfaces[idx].height = allocSurf.height;
980 ctx->surfaces[idx].lockCount = 0;
982 /* 1MB is large enough to hold most output frames. NVENC increases this automaticaly if it's not enough. */
983 allocOut.size = 1024 * 1024;
985 allocOut.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
987 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
988 if (nv_status != NV_ENC_SUCCESS) {
989 int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
990 if (avctx->pix_fmt != AV_PIX_FMT_CUDA)
991 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
992 av_frame_free(&ctx->surfaces[idx].in_ref);
996 ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
997 ctx->surfaces[idx].size = allocOut.size;
1002 static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx, int* surfaceCount)
1005 NvencContext *ctx = avctx->priv_data;
1007 ctx->surfaces = av_malloc(ctx->max_surface_count * sizeof(*ctx->surfaces));
1009 if (!ctx->surfaces) {
1010 return AVERROR(ENOMEM);
1013 ctx->timestamp_list = av_fifo_alloc(ctx->max_surface_count * sizeof(int64_t));
1014 if (!ctx->timestamp_list)
1015 return AVERROR(ENOMEM);
1016 ctx->output_surface_queue = av_fifo_alloc(ctx->max_surface_count * sizeof(NvencSurface*));
1017 if (!ctx->output_surface_queue)
1018 return AVERROR(ENOMEM);
1019 ctx->output_surface_ready_queue = av_fifo_alloc(ctx->max_surface_count * sizeof(NvencSurface*));
1020 if (!ctx->output_surface_ready_queue)
1021 return AVERROR(ENOMEM);
1023 for (*surfaceCount = 0; *surfaceCount < ctx->max_surface_count; ++*surfaceCount) {
1024 res = nvenc_alloc_surface(avctx, *surfaceCount);
1032 static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
1034 NvencContext *ctx = avctx->priv_data;
1035 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1036 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1038 NVENCSTATUS nv_status;
1039 uint32_t outSize = 0;
1040 char tmpHeader[256];
1041 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1042 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1044 payload.spsppsBuffer = tmpHeader;
1045 payload.inBufferSize = sizeof(tmpHeader);
1046 payload.outSPSPPSPayloadSize = &outSize;
1048 nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
1049 if (nv_status != NV_ENC_SUCCESS) {
1050 return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
1053 avctx->extradata_size = outSize;
1054 avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
1056 if (!avctx->extradata) {
1057 return AVERROR(ENOMEM);
1060 memcpy(avctx->extradata, tmpHeader, outSize);
1065 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
1067 NvencContext *ctx = avctx->priv_data;
1068 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1069 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1073 int surfaceCount = 0;
1075 if (!nvenc_dyload_nvenc(avctx))
1076 return AVERROR_EXTERNAL;
1078 res = nvenc_setup_device(avctx);
1082 res = nvenc_open_session(avctx);
1086 res = nvenc_setup_encoder(avctx);
1090 res = nvenc_setup_surfaces(avctx, &surfaceCount);
1094 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1095 res = nvenc_setup_extradata(avctx);
1103 av_fifo_freep(&ctx->timestamp_list);
1104 av_fifo_freep(&ctx->output_surface_ready_queue);
1105 av_fifo_freep(&ctx->output_surface_queue);
1107 for (i = 0; i < surfaceCount; ++i) {
1108 if (avctx->pix_fmt != AV_PIX_FMT_CUDA)
1109 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
1110 av_frame_free(&ctx->surfaces[i].in_ref);
1111 p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
1113 av_freep(&ctx->surfaces);
1116 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1117 ctx->nvencoder = NULL;
1119 if (ctx->cu_context_internal)
1120 dl_fn->cu_ctx_destroy(ctx->cu_context_internal);
1121 ctx->cu_context = ctx->cu_context_internal = NULL;
1123 nvenc_unload_nvenc(avctx);
1128 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
1130 NvencContext *ctx = avctx->priv_data;
1131 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1132 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1135 av_fifo_freep(&ctx->timestamp_list);
1136 av_fifo_freep(&ctx->output_surface_ready_queue);
1137 av_fifo_freep(&ctx->output_surface_queue);
1139 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1140 for (i = 0; i < ctx->max_surface_count; ++i) {
1141 if (ctx->surfaces[i].input_surface) {
1142 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->surfaces[i].in_map.mappedResource);
1145 for (i = 0; i < ctx->nb_registered_frames; i++) {
1146 if (ctx->registered_frames[i].regptr)
1147 p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1149 ctx->nb_registered_frames = 0;
1152 for (i = 0; i < ctx->max_surface_count; ++i) {
1153 if (avctx->pix_fmt != AV_PIX_FMT_CUDA)
1154 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
1155 av_frame_free(&ctx->surfaces[i].in_ref);
1156 p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
1158 av_freep(&ctx->surfaces);
1159 ctx->max_surface_count = 0;
1161 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1162 ctx->nvencoder = NULL;
1164 if (ctx->cu_context_internal)
1165 dl_fn->cu_ctx_destroy(ctx->cu_context_internal);
1166 ctx->cu_context = ctx->cu_context_internal = NULL;
1168 nvenc_unload_nvenc(avctx);
1173 static NvencSurface *get_free_frame(NvencContext *ctx)
1177 for (i = 0; i < ctx->max_surface_count; ++i) {
1178 if (!ctx->surfaces[i].lockCount) {
1179 ctx->surfaces[i].lockCount = 1;
1180 return &ctx->surfaces[i];
1187 static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *inSurf,
1188 NV_ENC_LOCK_INPUT_BUFFER *lockBufferParams, const AVFrame *frame)
1190 uint8_t *buf = lockBufferParams->bufferDataPtr;
1191 int off = inSurf->height * lockBufferParams->pitch;
1193 if (frame->format == AV_PIX_FMT_YUV420P) {
1194 av_image_copy_plane(buf, lockBufferParams->pitch,
1195 frame->data[0], frame->linesize[0],
1196 avctx->width, avctx->height);
1200 av_image_copy_plane(buf, lockBufferParams->pitch >> 1,
1201 frame->data[2], frame->linesize[2],
1202 avctx->width >> 1, avctx->height >> 1);
1206 av_image_copy_plane(buf, lockBufferParams->pitch >> 1,
1207 frame->data[1], frame->linesize[1],
1208 avctx->width >> 1, avctx->height >> 1);
1209 } else if (frame->format == AV_PIX_FMT_NV12) {
1210 av_image_copy_plane(buf, lockBufferParams->pitch,
1211 frame->data[0], frame->linesize[0],
1212 avctx->width, avctx->height);
1216 av_image_copy_plane(buf, lockBufferParams->pitch,
1217 frame->data[1], frame->linesize[1],
1218 avctx->width, avctx->height >> 1);
1219 } else if (frame->format == AV_PIX_FMT_YUV444P) {
1220 av_image_copy_plane(buf, lockBufferParams->pitch,
1221 frame->data[0], frame->linesize[0],
1222 avctx->width, avctx->height);
1226 av_image_copy_plane(buf, lockBufferParams->pitch,
1227 frame->data[1], frame->linesize[1],
1228 avctx->width, avctx->height);
1232 av_image_copy_plane(buf, lockBufferParams->pitch,
1233 frame->data[2], frame->linesize[2],
1234 avctx->width, avctx->height);
1236 av_log(avctx, AV_LOG_FATAL, "Invalid pixel format!\n");
1237 return AVERROR(EINVAL);
1243 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1245 NvencContext *ctx = avctx->priv_data;
1246 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1247 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1251 if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1252 for (i = 0; i < ctx->nb_registered_frames; i++) {
1253 if (!ctx->registered_frames[i].mapped) {
1254 if (ctx->registered_frames[i].regptr) {
1255 p_nvenc->nvEncUnregisterResource(ctx->nvencoder,
1256 ctx->registered_frames[i].regptr);
1257 ctx->registered_frames[i].regptr = NULL;
1263 return ctx->nb_registered_frames++;
1266 av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1267 return AVERROR(ENOMEM);
1270 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1272 NvencContext *ctx = avctx->priv_data;
1273 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1274 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1276 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1277 NV_ENC_REGISTER_RESOURCE reg;
1280 for (i = 0; i < ctx->nb_registered_frames; i++) {
1281 if (ctx->registered_frames[i].ptr == (CUdeviceptr)frame->data[0])
1285 idx = nvenc_find_free_reg_resource(avctx);
1289 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1290 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1291 reg.width = frames_ctx->width;
1292 reg.height = frames_ctx->height;
1293 reg.bufferFormat = ctx->surfaces[0].format;
1294 reg.pitch = frame->linesize[0];
1295 reg.resourceToRegister = frame->data[0];
1297 ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, ®);
1298 if (ret != NV_ENC_SUCCESS) {
1299 nvenc_print_error(avctx, ret, "Error registering an input resource");
1300 return AVERROR_UNKNOWN;
1303 ctx->registered_frames[idx].ptr = (CUdeviceptr)frame->data[0];
1304 ctx->registered_frames[idx].regptr = reg.registeredResource;
1308 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1309 NvencSurface *nvenc_frame)
1311 NvencContext *ctx = avctx->priv_data;
1312 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1313 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1316 NVENCSTATUS nv_status;
1318 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1319 int reg_idx = nvenc_register_frame(avctx, frame);
1321 av_log(avctx, AV_LOG_ERROR, "Could not register an input CUDA frame\n");
1325 res = av_frame_ref(nvenc_frame->in_ref, frame);
1329 nvenc_frame->in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1330 nvenc_frame->in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1331 nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &nvenc_frame->in_map);
1332 if (nv_status != NV_ENC_SUCCESS) {
1333 av_frame_unref(nvenc_frame->in_ref);
1334 return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
1337 ctx->registered_frames[reg_idx].mapped = 1;
1338 nvenc_frame->reg_idx = reg_idx;
1339 nvenc_frame->input_surface = nvenc_frame->in_map.mappedResource;
1342 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1344 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1345 lockBufferParams.inputBuffer = nvenc_frame->input_surface;
1347 nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
1348 if (nv_status != NV_ENC_SUCCESS) {
1349 return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
1352 res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
1354 nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
1355 if (nv_status != NV_ENC_SUCCESS) {
1356 return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
1363 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1364 NV_ENC_PIC_PARAMS *params)
1366 NvencContext *ctx = avctx->priv_data;
1368 switch (avctx->codec->id) {
1369 case AV_CODEC_ID_H264:
1370 params->codecPicParams.h264PicParams.sliceMode = ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1371 params->codecPicParams.h264PicParams.sliceModeData = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1373 case AV_CODEC_ID_H265:
1374 params->codecPicParams.hevcPicParams.sliceMode = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1375 params->codecPicParams.hevcPicParams.sliceModeData = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1380 static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
1382 NvencContext *ctx = avctx->priv_data;
1383 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1384 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1386 uint32_t slice_mode_data;
1387 uint32_t *slice_offsets;
1388 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1389 NVENCSTATUS nv_status;
1392 enum AVPictureType pict_type;
1394 switch (avctx->codec->id) {
1395 case AV_CODEC_ID_H264:
1396 slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1398 case AV_CODEC_ID_H265:
1399 slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1402 av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
1403 res = AVERROR(EINVAL);
1406 slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
1409 return AVERROR(ENOMEM);
1411 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1413 lock_params.doNotWait = 0;
1414 lock_params.outputBitstream = tmpoutsurf->output_surface;
1415 lock_params.sliceOffsets = slice_offsets;
1417 nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
1418 if (nv_status != NV_ENC_SUCCESS) {
1419 res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
1423 if (res = ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes,0)) {
1424 p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1428 memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1430 nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1431 if (nv_status != NV_ENC_SUCCESS)
1432 nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
1435 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1436 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, tmpoutsurf->in_map.mappedResource);
1437 av_frame_unref(tmpoutsurf->in_ref);
1438 ctx->registered_frames[tmpoutsurf->reg_idx].mapped = 0;
1440 tmpoutsurf->input_surface = NULL;
1443 switch (lock_params.pictureType) {
1444 case NV_ENC_PIC_TYPE_IDR:
1445 pkt->flags |= AV_PKT_FLAG_KEY;
1446 case NV_ENC_PIC_TYPE_I:
1447 pict_type = AV_PICTURE_TYPE_I;
1449 case NV_ENC_PIC_TYPE_P:
1450 pict_type = AV_PICTURE_TYPE_P;
1452 case NV_ENC_PIC_TYPE_B:
1453 pict_type = AV_PICTURE_TYPE_B;
1455 case NV_ENC_PIC_TYPE_BI:
1456 pict_type = AV_PICTURE_TYPE_BI;
1459 av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
1460 av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
1461 res = AVERROR_EXTERNAL;
1465 #if FF_API_CODED_FRAME
1466 FF_DISABLE_DEPRECATION_WARNINGS
1467 avctx->coded_frame->pict_type = pict_type;
1468 FF_ENABLE_DEPRECATION_WARNINGS
1471 ff_side_data_set_encoder_stats(pkt,
1472 (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
1474 pkt->pts = lock_params.outputTimeStamp;
1475 pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
1477 /* when there're b frame(s), set dts offset */
1478 if (ctx->encode_config.frameIntervalP >= 2)
1481 if (pkt->dts > pkt->pts)
1482 pkt->dts = pkt->pts;
1484 if (ctx->last_dts != AV_NOPTS_VALUE && pkt->dts <= ctx->last_dts)
1485 pkt->dts = ctx->last_dts + 1;
1487 ctx->last_dts = pkt->dts;
1489 av_free(slice_offsets);
1495 av_free(slice_offsets);
1496 timestamp_queue_dequeue(ctx->timestamp_list);
1501 static int output_ready(NvencContext *ctx, int flush)
1503 int nb_ready, nb_pending;
1505 nb_ready = av_fifo_size(ctx->output_surface_ready_queue) / sizeof(NvencSurface*);
1506 nb_pending = av_fifo_size(ctx->output_surface_queue) / sizeof(NvencSurface*);
1507 return nb_ready > 0 && (flush || nb_ready + nb_pending >= ctx->buffer_delay);
1510 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1511 const AVFrame *frame, int *got_packet)
1513 NVENCSTATUS nv_status;
1514 NvencSurface *tmpoutsurf, *inSurf;
1517 NvencContext *ctx = avctx->priv_data;
1518 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1519 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1521 NV_ENC_PIC_PARAMS pic_params = { 0 };
1522 pic_params.version = NV_ENC_PIC_PARAMS_VER;
1525 inSurf = get_free_frame(ctx);
1528 res = nvenc_upload_frame(avctx, frame, inSurf);
1530 inSurf->lockCount = 0;
1534 pic_params.inputBuffer = inSurf->input_surface;
1535 pic_params.bufferFmt = inSurf->format;
1536 pic_params.inputWidth = avctx->width;
1537 pic_params.inputHeight = avctx->height;
1538 pic_params.outputBitstream = inSurf->output_surface;
1539 pic_params.completionEvent = 0;
1541 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1542 if (frame->top_field_first) {
1543 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
1545 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
1548 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1551 pic_params.encodePicFlags = 0;
1552 pic_params.inputTimeStamp = frame->pts;
1553 pic_params.inputDuration = 0;
1555 nvenc_codec_specific_pic_params(avctx, &pic_params);
1557 timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
1559 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1562 nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
1564 if (frame && nv_status == NV_ENC_ERR_NEED_MORE_INPUT)
1565 av_fifo_generic_write(ctx->output_surface_queue, &inSurf, sizeof(inSurf), NULL);
1567 if (nv_status != NV_ENC_SUCCESS && nv_status != NV_ENC_ERR_NEED_MORE_INPUT) {
1568 return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
1571 if (nv_status != NV_ENC_ERR_NEED_MORE_INPUT) {
1572 while (av_fifo_size(ctx->output_surface_queue) > 0) {
1573 av_fifo_generic_read(ctx->output_surface_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
1574 av_fifo_generic_write(ctx->output_surface_ready_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
1578 av_fifo_generic_write(ctx->output_surface_ready_queue, &inSurf, sizeof(inSurf), NULL);
1581 if (output_ready(ctx, !frame)) {
1582 av_fifo_generic_read(ctx->output_surface_ready_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
1584 res = process_output_surface(avctx, pkt, tmpoutsurf);
1589 av_assert0(tmpoutsurf->lockCount);
1590 tmpoutsurf->lockCount--;