3 * Copyright (C) 2015 Luca Barbato
4 * Copyright (C) 2015 Philip Langdale <philipl@overt.org>
5 * Copyright (C) 2014 Timo Rothenpieler <timo@rothenpieler.org>
7 * This file is part of Libav.
9 * Libav is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * Libav is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with Libav; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 #include <nvEncodeAPI.h>
29 #define CUDA_LIBNAME "libcuda.so"
34 #define NVENC_LIBNAME "libnvidia-encode.so"
40 #define NVENC_LIBNAME "nvEncodeAPI64.dll"
42 #define NVENC_LIBNAME "nvEncodeAPI.dll"
45 #define dlopen(filename, flags) LoadLibrary((filename))
46 #define dlsym(handle, symbol) GetProcAddress(handle, symbol)
47 #define dlclose(handle) FreeLibrary(handle)
50 #include "libavutil/common.h"
51 #include "libavutil/hwcontext.h"
52 #include "libavutil/imgutils.h"
53 #include "libavutil/mem.h"
59 #include "libavutil/hwcontext_cuda.h"
62 #define NVENC_CAP 0x30
63 #define BITSTREAM_BUFFER_SIZE 1024 * 1024
64 #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR || \
65 rc == NV_ENC_PARAMS_RC_2_PASS_QUALITY || \
66 rc == NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP)
68 #define LOAD_LIBRARY(l, path) \
70 if (!((l) = dlopen(path, RTLD_LAZY))) { \
71 av_log(avctx, AV_LOG_ERROR, \
74 return AVERROR_UNKNOWN; \
78 #define LOAD_SYMBOL(fun, lib, symbol) \
80 if (!((fun) = dlsym(lib, symbol))) { \
81 av_log(avctx, AV_LOG_ERROR, \
84 return AVERROR_UNKNOWN; \
88 const enum AVPixelFormat ff_nvenc_pix_fmts[] = {
92 #if NVENCAPI_MAJOR_VERSION >= 7
102 #define IS_10BIT(pix_fmt) (pix_fmt == AV_PIX_FMT_P010 || \
103 pix_fmt == AV_PIX_FMT_YUV444P16)
105 #define IS_YUV444(pix_fmt) (pix_fmt == AV_PIX_FMT_YUV444P || \
106 pix_fmt == AV_PIX_FMT_YUV444P16)
108 static const struct {
113 { NV_ENC_SUCCESS, 0, "success" },
114 { NV_ENC_ERR_NO_ENCODE_DEVICE, AVERROR(ENOENT), "no encode device" },
115 { NV_ENC_ERR_UNSUPPORTED_DEVICE, AVERROR(ENOSYS), "unsupported device" },
116 { NV_ENC_ERR_INVALID_ENCODERDEVICE, AVERROR(EINVAL), "invalid encoder device" },
117 { NV_ENC_ERR_INVALID_DEVICE, AVERROR(EINVAL), "invalid device" },
118 { NV_ENC_ERR_DEVICE_NOT_EXIST, AVERROR(EIO), "device does not exist" },
119 { NV_ENC_ERR_INVALID_PTR, AVERROR(EFAULT), "invalid ptr" },
120 { NV_ENC_ERR_INVALID_EVENT, AVERROR(EINVAL), "invalid event" },
121 { NV_ENC_ERR_INVALID_PARAM, AVERROR(EINVAL), "invalid param" },
122 { NV_ENC_ERR_INVALID_CALL, AVERROR(EINVAL), "invalid call" },
123 { NV_ENC_ERR_OUT_OF_MEMORY, AVERROR(ENOMEM), "out of memory" },
124 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED, AVERROR(EINVAL), "encoder not initialized" },
125 { NV_ENC_ERR_UNSUPPORTED_PARAM, AVERROR(ENOSYS), "unsupported param" },
126 { NV_ENC_ERR_LOCK_BUSY, AVERROR(EAGAIN), "lock busy" },
127 { NV_ENC_ERR_NOT_ENOUGH_BUFFER, AVERROR(ENOBUFS), "not enough buffer" },
128 { NV_ENC_ERR_INVALID_VERSION, AVERROR(EINVAL), "invalid version" },
129 { NV_ENC_ERR_MAP_FAILED, AVERROR(EIO), "map failed" },
130 { NV_ENC_ERR_NEED_MORE_INPUT, AVERROR(EAGAIN), "need more input" },
131 { NV_ENC_ERR_ENCODER_BUSY, AVERROR(EAGAIN), "encoder busy" },
132 { NV_ENC_ERR_EVENT_NOT_REGISTERD, AVERROR(EBADF), "event not registered" },
133 { NV_ENC_ERR_GENERIC, AVERROR_UNKNOWN, "generic error" },
134 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY, AVERROR(EINVAL), "incompatible client key" },
135 { NV_ENC_ERR_UNIMPLEMENTED, AVERROR(ENOSYS), "unimplemented" },
136 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO), "resource register failed" },
137 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED, AVERROR(EBADF), "resource not registered" },
138 { NV_ENC_ERR_RESOURCE_NOT_MAPPED, AVERROR(EBADF), "resource not mapped" },
141 static int nvenc_map_error(NVENCSTATUS err, const char **desc)
144 for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
145 if (nvenc_errors[i].nverr == err) {
147 *desc = nvenc_errors[i].desc;
148 return nvenc_errors[i].averr;
152 *desc = "unknown error";
153 return AVERROR_UNKNOWN;
156 static int nvenc_print_error(void *log_ctx, NVENCSTATUS err,
157 const char *error_string)
161 ret = nvenc_map_error(err, &desc);
162 av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
166 static av_cold int nvenc_load_libraries(AVCodecContext *avctx)
168 NVENCContext *ctx = avctx->priv_data;
169 NVENCLibraryContext *nvel = &ctx->nvel;
170 PNVENCODEAPICREATEINSTANCE nvenc_create_instance;
174 nvel->cu_init = cuInit;
175 nvel->cu_device_get_count = cuDeviceGetCount;
176 nvel->cu_device_get = cuDeviceGet;
177 nvel->cu_device_get_name = cuDeviceGetName;
178 nvel->cu_device_compute_capability = cuDeviceComputeCapability;
179 nvel->cu_ctx_create = cuCtxCreate_v2;
180 nvel->cu_ctx_pop_current = cuCtxPopCurrent_v2;
181 nvel->cu_ctx_push_current = cuCtxPushCurrent_v2;
182 nvel->cu_ctx_destroy = cuCtxDestroy_v2;
184 LOAD_LIBRARY(nvel->cuda, CUDA_LIBNAME);
186 LOAD_SYMBOL(nvel->cu_init, nvel->cuda, "cuInit");
187 LOAD_SYMBOL(nvel->cu_device_get_count, nvel->cuda, "cuDeviceGetCount");
188 LOAD_SYMBOL(nvel->cu_device_get, nvel->cuda, "cuDeviceGet");
189 LOAD_SYMBOL(nvel->cu_device_get_name, nvel->cuda, "cuDeviceGetName");
190 LOAD_SYMBOL(nvel->cu_device_compute_capability, nvel->cuda,
191 "cuDeviceComputeCapability");
192 LOAD_SYMBOL(nvel->cu_ctx_create, nvel->cuda, "cuCtxCreate_v2");
193 LOAD_SYMBOL(nvel->cu_ctx_pop_current, nvel->cuda, "cuCtxPopCurrent_v2");
194 LOAD_SYMBOL(nvel->cu_ctx_push_current, nvel->cuda, "cuCtxPushCurrent_v2");
195 LOAD_SYMBOL(nvel->cu_ctx_destroy, nvel->cuda, "cuCtxDestroy_v2");
198 LOAD_LIBRARY(nvel->nvenc, NVENC_LIBNAME);
200 LOAD_SYMBOL(nvenc_create_instance, nvel->nvenc,
201 "NvEncodeAPICreateInstance");
203 nvel->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
205 err = nvenc_create_instance(&nvel->nvenc_funcs);
206 if (err != NV_ENC_SUCCESS)
207 return nvenc_print_error(avctx, err, "Cannot create the NVENC instance");
212 static int nvenc_open_session(AVCodecContext *avctx)
214 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
215 NVENCContext *ctx = avctx->priv_data;
216 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
219 params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
220 params.apiVersion = NVENCAPI_VERSION;
221 params.device = ctx->cu_context;
222 params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
224 ret = nv->nvEncOpenEncodeSessionEx(¶ms, &ctx->nvenc_ctx);
225 if (ret != NV_ENC_SUCCESS) {
226 ctx->nvenc_ctx = NULL;
227 return nvenc_print_error(avctx, ret, "Cannot open the NVENC Session");
233 static int nvenc_check_codec_support(AVCodecContext *avctx)
235 NVENCContext *ctx = avctx->priv_data;
236 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
237 int i, ret, count = 0;
240 ret = nv->nvEncGetEncodeGUIDCount(ctx->nvenc_ctx, &count);
242 if (ret != NV_ENC_SUCCESS || !count)
243 return AVERROR(ENOSYS);
245 guids = av_malloc(count * sizeof(GUID));
247 return AVERROR(ENOMEM);
249 ret = nv->nvEncGetEncodeGUIDs(ctx->nvenc_ctx, guids, count, &count);
250 if (ret != NV_ENC_SUCCESS) {
251 ret = AVERROR(ENOSYS);
255 ret = AVERROR(ENOSYS);
256 for (i = 0; i < count; i++) {
257 if (!memcmp(&guids[i], &ctx->params.encodeGUID, sizeof(*guids))) {
269 static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
271 NVENCContext *ctx = avctx->priv_data;
272 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
273 NV_ENC_CAPS_PARAM params = { 0 };
276 params.version = NV_ENC_CAPS_PARAM_VER;
277 params.capsToQuery = cap;
279 ret = nv->nvEncGetEncodeCaps(ctx->nvenc_ctx, ctx->params.encodeGUID, ¶ms, &val);
281 if (ret == NV_ENC_SUCCESS)
286 static int nvenc_check_capabilities(AVCodecContext *avctx)
288 NVENCContext *ctx = avctx->priv_data;
291 ret = nvenc_check_codec_support(avctx);
293 av_log(avctx, AV_LOG_VERBOSE, "Codec not supported\n");
297 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
298 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P && ret <= 0) {
299 av_log(avctx, AV_LOG_VERBOSE, "YUV444P not supported\n");
300 return AVERROR(ENOSYS);
303 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
304 if (ret < avctx->width) {
305 av_log(avctx, AV_LOG_VERBOSE, "Width %d exceeds %d\n",
307 return AVERROR(ENOSYS);
310 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
311 if (ret < avctx->height) {
312 av_log(avctx, AV_LOG_VERBOSE, "Height %d exceeds %d\n",
314 return AVERROR(ENOSYS);
317 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
318 if (ret < avctx->max_b_frames) {
319 av_log(avctx, AV_LOG_VERBOSE, "Max B-frames %d exceed %d\n",
320 avctx->max_b_frames, ret);
322 return AVERROR(ENOSYS);
328 static int nvenc_check_device(AVCodecContext *avctx, int idx)
330 NVENCContext *ctx = avctx->priv_data;
331 NVENCLibraryContext *nvel = &ctx->nvel;
332 char name[128] = { 0 };
333 int major, minor, ret;
336 int loglevel = AV_LOG_VERBOSE;
338 if (ctx->device == LIST_DEVICES)
339 loglevel = AV_LOG_INFO;
341 ret = nvel->cu_device_get(&cu_device, idx);
342 if (ret != CUDA_SUCCESS) {
343 av_log(avctx, AV_LOG_ERROR,
344 "Cannot access the CUDA device %d\n",
349 ret = nvel->cu_device_get_name(name, sizeof(name), cu_device);
350 if (ret != CUDA_SUCCESS)
353 ret = nvel->cu_device_compute_capability(&major, &minor, cu_device);
354 if (ret != CUDA_SUCCESS)
357 av_log(avctx, loglevel, "Device %d [%s] ", cu_device, name);
359 if (((major << 4) | minor) < NVENC_CAP)
362 if (ctx->device != idx && ctx->device != ANY_DEVICE)
365 ret = nvel->cu_ctx_create(&ctx->cu_context_internal, 0, cu_device);
366 if (ret != CUDA_SUCCESS)
369 ctx->cu_context = ctx->cu_context_internal;
371 ret = nvel->cu_ctx_pop_current(&dummy);
372 if (ret != CUDA_SUCCESS)
375 if ((ret = nvenc_open_session(avctx)) < 0)
378 if ((ret = nvenc_check_capabilities(avctx)) < 0)
381 av_log(avctx, loglevel, "supports NVENC\n");
383 if (ctx->device == idx || ctx->device == ANY_DEVICE)
387 nvel->nvenc_funcs.nvEncDestroyEncoder(ctx->nvenc_ctx);
388 ctx->nvenc_ctx = NULL;
391 nvel->cu_ctx_destroy(ctx->cu_context_internal);
392 ctx->cu_context_internal = NULL;
396 av_log(avctx, loglevel, "does not support NVENC (major %d minor %d)\n",
399 return AVERROR(ENOSYS);
402 static int nvenc_setup_device(AVCodecContext *avctx)
404 NVENCContext *ctx = avctx->priv_data;
405 NVENCLibraryContext *nvel = &ctx->nvel;
407 switch (avctx->codec->id) {
408 case AV_CODEC_ID_H264:
409 ctx->params.encodeGUID = NV_ENC_CODEC_H264_GUID;
411 case AV_CODEC_ID_HEVC:
412 ctx->params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
418 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
420 AVHWFramesContext *frames_ctx;
421 AVCUDADeviceContext *device_hwctx;
424 if (!avctx->hw_frames_ctx)
425 return AVERROR(EINVAL);
427 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
428 device_hwctx = frames_ctx->device_ctx->hwctx;
430 ctx->cu_context = device_hwctx->cuda_ctx;
432 ret = nvenc_open_session(avctx);
436 ret = nvenc_check_capabilities(avctx);
443 int i, nb_devices = 0;
445 if ((nvel->cu_init(0)) != CUDA_SUCCESS) {
446 av_log(avctx, AV_LOG_ERROR,
447 "Cannot init CUDA\n");
448 return AVERROR_UNKNOWN;
451 if ((nvel->cu_device_get_count(&nb_devices)) != CUDA_SUCCESS) {
452 av_log(avctx, AV_LOG_ERROR,
453 "Cannot enumerate the CUDA devices\n");
454 return AVERROR_UNKNOWN;
458 for (i = 0; i < nb_devices; ++i) {
459 if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
463 if (ctx->device == LIST_DEVICES)
466 return AVERROR(ENOSYS);
472 typedef struct GUIDTuple {
477 #define PRESET_ALIAS(alias, name, ...) \
478 [PRESET_ ## alias] = { NV_ENC_PRESET_ ## name ## _GUID, __VA_ARGS__ }
480 #define PRESET(name, ...) PRESET_ALIAS(name, name, __VA_ARGS__)
482 static int nvenc_map_preset(NVENCContext *ctx)
484 GUIDTuple presets[] = {
489 PRESET(LOW_LATENCY_DEFAULT, NVENC_LOWLATENCY),
490 PRESET(LOW_LATENCY_HP, NVENC_LOWLATENCY),
491 PRESET(LOW_LATENCY_HQ, NVENC_LOWLATENCY),
492 PRESET(LOSSLESS_DEFAULT, NVENC_LOSSLESS),
493 PRESET(LOSSLESS_HP, NVENC_LOSSLESS),
494 PRESET_ALIAS(SLOW, HQ, NVENC_TWO_PASSES),
495 PRESET_ALIAS(MEDIUM, HQ, NVENC_ONE_PASS),
496 PRESET_ALIAS(FAST, HP, NVENC_ONE_PASS),
500 GUIDTuple *t = &presets[ctx->preset];
502 ctx->params.presetGUID = t->guid;
503 ctx->flags = t->flags;
505 return AVERROR(EINVAL);
511 static void set_constqp(AVCodecContext *avctx, NV_ENC_RC_PARAMS *rc)
513 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
514 rc->constQP.qpInterB = avctx->global_quality;
515 rc->constQP.qpInterP = avctx->global_quality;
516 rc->constQP.qpIntra = avctx->global_quality;
519 static void set_vbr(AVCodecContext *avctx, NV_ENC_RC_PARAMS *rc)
521 if (avctx->qmin >= 0) {
523 rc->minQP.qpInterB = avctx->qmin;
524 rc->minQP.qpInterP = avctx->qmin;
525 rc->minQP.qpIntra = avctx->qmin;
528 if (avctx->qmax >= 0) {
530 rc->maxQP.qpInterB = avctx->qmax;
531 rc->maxQP.qpInterP = avctx->qmax;
532 rc->maxQP.qpIntra = avctx->qmax;
536 static void set_lossless(AVCodecContext *avctx, NV_ENC_RC_PARAMS *rc)
538 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
539 rc->constQP.qpInterB = 0;
540 rc->constQP.qpInterP = 0;
541 rc->constQP.qpIntra = 0;
544 static void nvenc_override_rate_control(AVCodecContext *avctx,
545 NV_ENC_RC_PARAMS *rc)
547 NVENCContext *ctx = avctx->priv_data;
550 case NV_ENC_PARAMS_RC_CONSTQP:
551 if (avctx->global_quality < 0) {
552 av_log(avctx, AV_LOG_WARNING,
553 "The constant quality rate-control requires "
554 "the 'global_quality' option set.\n");
557 set_constqp(avctx, rc);
559 case NV_ENC_PARAMS_RC_2_PASS_VBR:
560 case NV_ENC_PARAMS_RC_VBR:
561 if (avctx->qmin < 0 && avctx->qmax < 0) {
562 av_log(avctx, AV_LOG_WARNING,
563 "The variable bitrate rate-control requires "
564 "the 'qmin' and/or 'qmax' option set.\n");
567 case NV_ENC_PARAMS_RC_VBR_MINQP:
568 if (avctx->qmin < 0) {
569 av_log(avctx, AV_LOG_WARNING,
570 "The variable bitrate rate-control requires "
571 "the 'qmin' option set.\n");
576 case NV_ENC_PARAMS_RC_CBR:
578 case NV_ENC_PARAMS_RC_2_PASS_QUALITY:
579 case NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP:
580 if (!(ctx->flags & NVENC_LOWLATENCY)) {
581 av_log(avctx, AV_LOG_WARNING,
582 "The multipass rate-control requires "
583 "a low-latency preset.\n");
588 rc->rateControlMode = ctx->rc;
591 static void nvenc_setup_rate_control(AVCodecContext *avctx)
593 NVENCContext *ctx = avctx->priv_data;
594 NV_ENC_RC_PARAMS *rc = &ctx->config.rcParams;
596 if (avctx->bit_rate > 0)
597 rc->averageBitRate = avctx->bit_rate;
599 if (avctx->rc_max_rate > 0)
600 rc->maxBitRate = avctx->rc_max_rate;
603 nvenc_override_rate_control(avctx, rc);
604 } else if (ctx->flags & NVENC_LOSSLESS) {
605 set_lossless(avctx, rc);
606 } else if (avctx->global_quality > 0) {
607 set_constqp(avctx, rc);
608 } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
609 rc->rateControlMode = NV_ENC_PARAMS_RC_VBR;
613 if (avctx->rc_buffer_size > 0)
614 rc->vbvBufferSize = avctx->rc_buffer_size;
616 if (rc->averageBitRate > 0)
617 avctx->bit_rate = rc->averageBitRate;
619 #if NVENCAPI_MAJOR_VERSION >= 7
621 ctx->config.rcParams.enableAQ = 1;
622 ctx->config.rcParams.aqStrength = ctx->aq_strength;
623 av_log(avctx, AV_LOG_VERBOSE, "AQ enabled.\n");
626 if (ctx->temporal_aq) {
627 ctx->config.rcParams.enableTemporalAQ = 1;
628 av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ enabled.\n");
631 if (ctx->rc_lookahead > 0) {
632 int lkd_bound = FFMIN(ctx->nb_surfaces, ctx->async_depth) -
633 ctx->config.frameIntervalP - 4;
636 av_log(avctx, AV_LOG_WARNING,
637 "Lookahead not enabled. Increase buffer delay (-delay).\n");
639 ctx->config.rcParams.enableLookahead = 1;
640 ctx->config.rcParams.lookaheadDepth = av_clip(ctx->rc_lookahead, 0, lkd_bound);
641 ctx->config.rcParams.disableIadapt = ctx->no_scenecut;
642 ctx->config.rcParams.disableBadapt = !ctx->b_adapt;
643 av_log(avctx, AV_LOG_VERBOSE,
644 "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",
645 ctx->config.rcParams.lookaheadDepth,
646 ctx->config.rcParams.disableIadapt ? "disabled" : "enabled",
647 ctx->config.rcParams.disableBadapt ? "disabled" : "enabled");
651 if (ctx->strict_gop) {
652 ctx->config.rcParams.strictGOPTarget = 1;
653 av_log(avctx, AV_LOG_VERBOSE, "Strict GOP target enabled.\n");
657 ctx->config.rcParams.enableNonRefP = 1;
659 if (ctx->zerolatency)
660 ctx->config.rcParams.zeroReorderDelay = 1;
663 ctx->config.rcParams.targetQuality = ctx->quality;
664 #endif /* NVENCAPI_MAJOR_VERSION >= 7 */
667 static int nvenc_setup_h264_config(AVCodecContext *avctx)
669 NVENCContext *ctx = avctx->priv_data;
670 NV_ENC_CONFIG *cc = &ctx->config;
671 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
672 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
674 vui->colourDescriptionPresentFlag = avctx->colorspace != AVCOL_SPC_UNSPECIFIED ||
675 avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
676 avctx->color_trc != AVCOL_TRC_UNSPECIFIED;
678 vui->colourMatrix = avctx->colorspace;
679 vui->colourPrimaries = avctx->color_primaries;
680 vui->transferCharacteristics = avctx->color_trc;
682 vui->videoFullRangeFlag = avctx->color_range == AVCOL_RANGE_JPEG;
684 vui->videoSignalTypePresentFlag = vui->colourDescriptionPresentFlag ||
685 vui->videoFullRangeFlag;
687 h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
688 h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
691 h264->maxNumRefFrames = avctx->refs;
692 h264->idrPeriod = cc->gopLength;
695 h264->sliceModeData = FFMAX(avctx->slices, 1);
697 if (ctx->flags & NVENC_LOSSLESS)
698 h264->qpPrimeYZeroTransformBypassFlag = 1;
700 if (IS_CBR(cc->rcParams.rateControlMode)) {
701 h264->outputBufferingPeriodSEI = 1;
702 h264->outputPictureTimingSEI = 1;
706 avctx->profile = ctx->profile;
708 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P)
709 h264->chromaFormatIDC = 3;
711 h264->chromaFormatIDC = 1;
713 switch (ctx->profile) {
714 case NV_ENC_H264_PROFILE_BASELINE:
715 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
717 case NV_ENC_H264_PROFILE_MAIN:
718 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
720 case NV_ENC_H264_PROFILE_HIGH:
721 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
723 case NV_ENC_H264_PROFILE_HIGH_444:
724 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
726 case NV_ENC_H264_PROFILE_CONSTRAINED_HIGH:
727 cc->profileGUID = NV_ENC_H264_PROFILE_CONSTRAINED_HIGH_GUID;
731 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P) {
732 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
733 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
736 h264->level = ctx->level;
741 static int nvenc_setup_hevc_config(AVCodecContext *avctx)
743 NVENCContext *ctx = avctx->priv_data;
744 NV_ENC_CONFIG *cc = &ctx->config;
745 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
746 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
748 vui->colourDescriptionPresentFlag = avctx->colorspace != AVCOL_SPC_UNSPECIFIED ||
749 avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
750 avctx->color_trc != AVCOL_TRC_UNSPECIFIED;
752 vui->colourMatrix = avctx->colorspace;
753 vui->colourPrimaries = avctx->color_primaries;
754 vui->transferCharacteristics = avctx->color_trc;
756 vui->videoFullRangeFlag = avctx->color_range == AVCOL_RANGE_JPEG;
758 vui->videoSignalTypePresentFlag = vui->colourDescriptionPresentFlag ||
759 vui->videoFullRangeFlag;
761 hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
762 hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
765 hevc->maxNumRefFramesInDPB = avctx->refs;
766 hevc->idrPeriod = cc->gopLength;
768 if (IS_CBR(cc->rcParams.rateControlMode)) {
769 hevc->outputBufferingPeriodSEI = 1;
770 hevc->outputPictureTimingSEI = 1;
773 switch (ctx->profile) {
774 case NV_ENC_HEVC_PROFILE_MAIN:
775 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
776 avctx->profile = FF_PROFILE_HEVC_MAIN;
778 #if NVENCAPI_MAJOR_VERSION >= 7
779 case NV_ENC_HEVC_PROFILE_MAIN_10:
780 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
781 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
783 case NV_ENC_HEVC_PROFILE_REXT:
784 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
785 avctx->profile = FF_PROFILE_HEVC_REXT;
787 #endif /* NVENCAPI_MAJOR_VERSION >= 7 */
790 // force setting profile for various input formats
791 switch (ctx->data_pix_fmt) {
792 case AV_PIX_FMT_YUV420P:
793 case AV_PIX_FMT_NV12:
794 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
795 avctx->profile = FF_PROFILE_HEVC_MAIN;
797 #if NVENCAPI_MAJOR_VERSION >= 7
798 case AV_PIX_FMT_P010:
799 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
800 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
802 case AV_PIX_FMT_YUV444P:
803 case AV_PIX_FMT_YUV444P16:
804 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
805 avctx->profile = FF_PROFILE_HEVC_REXT;
807 #endif /* NVENCAPI_MAJOR_VERSION >= 7 */
810 #if NVENCAPI_MAJOR_VERSION >= 7
811 hevc->chromaFormatIDC = IS_YUV444(ctx->data_pix_fmt) ? 3 : 1;
812 hevc->pixelBitDepthMinus8 = IS_10BIT(ctx->data_pix_fmt) ? 2 : 0;
813 #endif /* NVENCAPI_MAJOR_VERSION >= 7 */
816 hevc->sliceModeData = FFMAX(avctx->slices, 1);
819 hevc->level = ctx->level;
821 hevc->level = NV_ENC_LEVEL_AUTOSELECT;
825 hevc->tier = ctx->tier;
830 static int nvenc_setup_codec_config(AVCodecContext *avctx)
832 switch (avctx->codec->id) {
833 case AV_CODEC_ID_H264:
834 return nvenc_setup_h264_config(avctx);
835 case AV_CODEC_ID_HEVC:
836 return nvenc_setup_hevc_config(avctx);
841 static int nvenc_setup_encoder(AVCodecContext *avctx)
843 NVENCContext *ctx = avctx->priv_data;
844 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
845 NV_ENC_PRESET_CONFIG preset_cfg = { 0 };
846 AVCPBProperties *cpb_props;
849 ctx->params.version = NV_ENC_INITIALIZE_PARAMS_VER;
851 ctx->params.encodeHeight = avctx->height;
852 ctx->params.encodeWidth = avctx->width;
854 if (avctx->sample_aspect_ratio.num &&
855 avctx->sample_aspect_ratio.den &&
856 (avctx->sample_aspect_ratio.num != 1 ||
857 avctx->sample_aspect_ratio.den != 1)) {
858 av_reduce(&ctx->params.darWidth,
859 &ctx->params.darHeight,
860 avctx->width * avctx->sample_aspect_ratio.num,
861 avctx->height * avctx->sample_aspect_ratio.den,
864 ctx->params.darHeight = avctx->height;
865 ctx->params.darWidth = avctx->width;
868 // De-compensate for hardware, dubiously, trying to compensate for
869 // playback at 704 pixel width.
870 if (avctx->width == 720 && (avctx->height == 480 || avctx->height == 576)) {
871 av_reduce(&ctx->params.darWidth, &ctx->params.darHeight,
872 ctx->params.darWidth * 44,
873 ctx->params.darHeight * 45,
877 ctx->params.frameRateNum = avctx->time_base.den;
878 ctx->params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
880 ctx->params.enableEncodeAsync = 0;
881 ctx->params.enablePTD = 1;
883 ctx->params.encodeConfig = &ctx->config;
885 nvenc_map_preset(ctx);
887 preset_cfg.version = NV_ENC_PRESET_CONFIG_VER;
888 preset_cfg.presetCfg.version = NV_ENC_CONFIG_VER;
890 ret = nv->nvEncGetEncodePresetConfig(ctx->nvenc_ctx,
891 ctx->params.encodeGUID,
892 ctx->params.presetGUID,
894 if (ret != NV_ENC_SUCCESS)
895 return nvenc_print_error(avctx, ret, "Cannot get the preset configuration");
897 memcpy(&ctx->config, &preset_cfg.presetCfg, sizeof(ctx->config));
899 ctx->config.version = NV_ENC_CONFIG_VER;
901 if (avctx->gop_size > 0) {
902 if (avctx->max_b_frames > 0) {
906 * 3 two B-frames, and so on. */
907 ctx->config.frameIntervalP = avctx->max_b_frames + 1;
908 } else if (avctx->max_b_frames == 0) {
909 ctx->config.frameIntervalP = 1;
911 ctx->config.gopLength = avctx->gop_size;
912 } else if (avctx->gop_size == 0) {
913 ctx->config.frameIntervalP = 0;
914 ctx->config.gopLength = 1;
917 if (ctx->config.frameIntervalP > 1)
918 avctx->max_b_frames = ctx->config.frameIntervalP - 1;
920 ctx->initial_pts[0] = AV_NOPTS_VALUE;
921 ctx->initial_pts[1] = AV_NOPTS_VALUE;
923 nvenc_setup_rate_control(avctx);
925 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
926 ctx->config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
928 ctx->config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
931 if ((ret = nvenc_setup_codec_config(avctx)) < 0)
934 ret = nv->nvEncInitializeEncoder(ctx->nvenc_ctx, &ctx->params);
935 if (ret != NV_ENC_SUCCESS)
936 return nvenc_print_error(avctx, ret, "InitializeEncoder failed");
938 cpb_props = ff_add_cpb_side_data(avctx);
940 return AVERROR(ENOMEM);
941 cpb_props->max_bitrate = avctx->rc_max_rate;
942 cpb_props->min_bitrate = avctx->rc_min_rate;
943 cpb_props->avg_bitrate = avctx->bit_rate;
944 cpb_props->buffer_size = avctx->rc_buffer_size;
949 static int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
951 NVENCContext *ctx = avctx->priv_data;
952 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
954 NV_ENC_CREATE_BITSTREAM_BUFFER out_buffer = { 0 };
956 switch (ctx->data_pix_fmt) {
957 case AV_PIX_FMT_YUV420P:
958 ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YV12_PL;
960 case AV_PIX_FMT_NV12:
961 ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_NV12_PL;
963 case AV_PIX_FMT_YUV444P:
964 ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YUV444_PL;
966 #if NVENCAPI_MAJOR_VERSION >= 7
967 case AV_PIX_FMT_P010:
968 ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
970 case AV_PIX_FMT_YUV444P16:
971 ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
973 #endif /* NVENCAPI_MAJOR_VERSION >= 7 */
978 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
979 ctx->frames[idx].in_ref = av_frame_alloc();
980 if (!ctx->frames[idx].in_ref)
981 return AVERROR(ENOMEM);
983 NV_ENC_CREATE_INPUT_BUFFER in_buffer = { 0 };
985 in_buffer.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
987 in_buffer.width = avctx->width;
988 in_buffer.height = avctx->height;
990 in_buffer.bufferFmt = ctx->frames[idx].format;
991 in_buffer.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED;
993 ret = nv->nvEncCreateInputBuffer(ctx->nvenc_ctx, &in_buffer);
994 if (ret != NV_ENC_SUCCESS)
995 return nvenc_print_error(avctx, ret, "CreateInputBuffer failed");
997 ctx->frames[idx].in = in_buffer.inputBuffer;
1000 out_buffer.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1001 /* 1MB is large enough to hold most output frames.
1002 * NVENC increases this automatically if it is not enough. */
1003 out_buffer.size = BITSTREAM_BUFFER_SIZE;
1005 out_buffer.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED;
1007 ret = nv->nvEncCreateBitstreamBuffer(ctx->nvenc_ctx, &out_buffer);
1008 if (ret != NV_ENC_SUCCESS)
1009 return nvenc_print_error(avctx, ret, "CreateBitstreamBuffer failed");
1011 ctx->frames[idx].out = out_buffer.bitstreamBuffer;
1016 static int nvenc_setup_surfaces(AVCodecContext *avctx)
1018 NVENCContext *ctx = avctx->priv_data;
1021 ctx->nb_surfaces = FFMAX(4 + avctx->max_b_frames,
1023 ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
1026 ctx->frames = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->frames));
1028 return AVERROR(ENOMEM);
1030 ctx->timestamps = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
1031 if (!ctx->timestamps)
1032 return AVERROR(ENOMEM);
1033 ctx->pending = av_fifo_alloc(ctx->nb_surfaces * sizeof(*ctx->frames));
1035 return AVERROR(ENOMEM);
1036 ctx->ready = av_fifo_alloc(ctx->nb_surfaces * sizeof(*ctx->frames));
1038 return AVERROR(ENOMEM);
1040 for (i = 0; i < ctx->nb_surfaces; i++) {
1041 if ((ret = nvenc_alloc_surface(avctx, i)) < 0)
1048 #define EXTRADATA_SIZE 512
1050 static int nvenc_setup_extradata(AVCodecContext *avctx)
1052 NVENCContext *ctx = avctx->priv_data;
1053 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1054 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1057 avctx->extradata = av_mallocz(EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
1058 if (!avctx->extradata)
1059 return AVERROR(ENOMEM);
1061 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1062 payload.spsppsBuffer = avctx->extradata;
1063 payload.inBufferSize = EXTRADATA_SIZE;
1064 payload.outSPSPPSPayloadSize = &avctx->extradata_size;
1066 ret = nv->nvEncGetSequenceParams(ctx->nvenc_ctx, &payload);
1067 if (ret != NV_ENC_SUCCESS)
1068 return nvenc_print_error(avctx, ret, "Cannot get the extradata");
1073 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
1075 NVENCContext *ctx = avctx->priv_data;
1076 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1079 /* the encoder has to be flushed before it can be closed */
1080 if (ctx->nvenc_ctx) {
1081 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
1082 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
1084 nv->nvEncEncodePicture(ctx->nvenc_ctx, ¶ms);
1087 av_fifo_free(ctx->timestamps);
1088 av_fifo_free(ctx->pending);
1089 av_fifo_free(ctx->ready);
1092 for (i = 0; i < ctx->nb_surfaces; ++i) {
1093 if (avctx->pix_fmt != AV_PIX_FMT_CUDA) {
1094 nv->nvEncDestroyInputBuffer(ctx->nvenc_ctx, ctx->frames[i].in);
1095 } else if (ctx->frames[i].in) {
1096 nv->nvEncUnmapInputResource(ctx->nvenc_ctx, ctx->frames[i].in_map.mappedResource);
1099 av_frame_free(&ctx->frames[i].in_ref);
1100 nv->nvEncDestroyBitstreamBuffer(ctx->nvenc_ctx, ctx->frames[i].out);
1103 for (i = 0; i < ctx->nb_registered_frames; i++) {
1104 if (ctx->registered_frames[i].regptr)
1105 nv->nvEncUnregisterResource(ctx->nvenc_ctx, ctx->registered_frames[i].regptr);
1107 ctx->nb_registered_frames = 0;
1109 av_freep(&ctx->frames);
1112 nv->nvEncDestroyEncoder(ctx->nvenc_ctx);
1114 if (ctx->cu_context_internal)
1115 ctx->nvel.cu_ctx_destroy(ctx->cu_context_internal);
1117 if (ctx->nvel.nvenc)
1118 dlclose(ctx->nvel.nvenc);
1122 dlclose(ctx->nvel.cuda);
1128 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
1130 NVENCContext *ctx = avctx->priv_data;
1133 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1134 AVHWFramesContext *frames_ctx;
1135 if (!avctx->hw_frames_ctx) {
1136 av_log(avctx, AV_LOG_ERROR,
1137 "hw_frames_ctx must be set when using GPU frames as input\n");
1138 return AVERROR(EINVAL);
1140 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1141 ctx->data_pix_fmt = frames_ctx->sw_format;
1143 ctx->data_pix_fmt = avctx->pix_fmt;
1146 if ((ret = nvenc_load_libraries(avctx)) < 0)
1149 if ((ret = nvenc_setup_device(avctx)) < 0)
1152 if ((ret = nvenc_setup_encoder(avctx)) < 0)
1155 if ((ret = nvenc_setup_surfaces(avctx)) < 0)
1158 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1159 if ((ret = nvenc_setup_extradata(avctx)) < 0)
1166 static NVENCFrame *get_free_frame(NVENCContext *ctx)
1170 for (i = 0; i < ctx->nb_surfaces; i++) {
1171 if (!ctx->frames[i].locked) {
1172 ctx->frames[i].locked = 1;
1173 return &ctx->frames[i];
1180 static int nvenc_copy_frame(NV_ENC_LOCK_INPUT_BUFFER *in, const AVFrame *frame)
1182 uint8_t *buf = in->bufferDataPtr;
1183 int off = frame->height * in->pitch;
1185 switch (frame->format) {
1186 case AV_PIX_FMT_YUV420P:
1187 av_image_copy_plane(buf, in->pitch,
1188 frame->data[0], frame->linesize[0],
1189 frame->width, frame->height);
1192 av_image_copy_plane(buf, in->pitch >> 1,
1193 frame->data[2], frame->linesize[2],
1194 frame->width >> 1, frame->height >> 1);
1198 av_image_copy_plane(buf, in->pitch >> 1,
1199 frame->data[1], frame->linesize[1],
1200 frame->width >> 1, frame->height >> 1);
1202 case AV_PIX_FMT_NV12:
1203 av_image_copy_plane(buf, in->pitch,
1204 frame->data[0], frame->linesize[0],
1205 frame->width, frame->height);
1208 av_image_copy_plane(buf, in->pitch,
1209 frame->data[1], frame->linesize[1],
1210 frame->width, frame->height >> 1);
1212 case AV_PIX_FMT_P010:
1213 av_image_copy_plane(buf, in->pitch,
1214 frame->data[0], frame->linesize[0],
1215 frame->width << 1, frame->height);
1218 av_image_copy_plane(buf, in->pitch,
1219 frame->data[1], frame->linesize[1],
1220 frame->width << 1, frame->height >> 1);
1222 case AV_PIX_FMT_YUV444P:
1223 av_image_copy_plane(buf, in->pitch,
1224 frame->data[0], frame->linesize[0],
1225 frame->width, frame->height);
1228 av_image_copy_plane(buf, in->pitch,
1229 frame->data[1], frame->linesize[1],
1230 frame->width, frame->height);
1233 av_image_copy_plane(buf, in->pitch,
1234 frame->data[2], frame->linesize[2],
1235 frame->width, frame->height);
1237 case AV_PIX_FMT_YUV444P16:
1238 av_image_copy_plane(buf, in->pitch,
1239 frame->data[0], frame->linesize[0],
1240 frame->width << 1, frame->height);
1243 av_image_copy_plane(buf, in->pitch,
1244 frame->data[1], frame->linesize[1],
1245 frame->width << 1, frame->height);
1248 av_image_copy_plane(buf, in->pitch,
1249 frame->data[2], frame->linesize[2],
1250 frame->width << 1, frame->height);
1259 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1261 NVENCContext *ctx = avctx->priv_data;
1262 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1265 if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1266 for (i = 0; i < ctx->nb_registered_frames; i++) {
1267 if (!ctx->registered_frames[i].mapped) {
1268 if (ctx->registered_frames[i].regptr) {
1269 nv->nvEncUnregisterResource(ctx->nvenc_ctx,
1270 ctx->registered_frames[i].regptr);
1271 ctx->registered_frames[i].regptr = NULL;
1277 return ctx->nb_registered_frames++;
1280 av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1281 return AVERROR(ENOMEM);
1284 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1286 NVENCContext *ctx = avctx->priv_data;
1287 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1288 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1289 NV_ENC_REGISTER_RESOURCE reg;
1292 for (i = 0; i < ctx->nb_registered_frames; i++) {
1293 if (ctx->registered_frames[i].ptr == (CUdeviceptr)frame->data[0])
1297 idx = nvenc_find_free_reg_resource(avctx);
1301 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1302 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1303 reg.width = frames_ctx->width;
1304 reg.height = frames_ctx->height;
1305 reg.bufferFormat = ctx->frames[0].format;
1306 reg.pitch = frame->linesize[0];
1307 reg.resourceToRegister = frame->data[0];
1309 ret = nv->nvEncRegisterResource(ctx->nvenc_ctx, ®);
1310 if (ret != NV_ENC_SUCCESS) {
1311 nvenc_print_error(avctx, ret, "Error registering an input resource");
1312 return AVERROR_UNKNOWN;
1315 ctx->registered_frames[idx].ptr = (CUdeviceptr)frame->data[0];
1316 ctx->registered_frames[idx].regptr = reg.registeredResource;
1320 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1321 NVENCFrame *nvenc_frame)
1323 NVENCContext *ctx = avctx->priv_data;
1324 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1327 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1330 ret = nvenc_register_frame(avctx, frame);
1332 av_log(avctx, AV_LOG_ERROR, "Could not register an input CUDA frame\n");
1337 ret = av_frame_ref(nvenc_frame->in_ref, frame);
1341 nvenc_frame->in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1342 nvenc_frame->in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1344 ret = nv->nvEncMapInputResource(ctx->nvenc_ctx, &nvenc_frame->in_map);
1345 if (ret != NV_ENC_SUCCESS) {
1346 av_frame_unref(nvenc_frame->in_ref);
1347 return nvenc_print_error(avctx, ret, "Error mapping an input resource");
1350 ctx->registered_frames[reg_idx].mapped = 1;
1351 nvenc_frame->reg_idx = reg_idx;
1352 nvenc_frame->in = nvenc_frame->in_map.mappedResource;
1354 NV_ENC_LOCK_INPUT_BUFFER params = { 0 };
1356 params.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1357 params.inputBuffer = nvenc_frame->in;
1359 ret = nv->nvEncLockInputBuffer(ctx->nvenc_ctx, ¶ms);
1360 if (ret != NV_ENC_SUCCESS)
1361 return nvenc_print_error(avctx, ret, "Cannot lock the buffer");
1363 ret = nvenc_copy_frame(¶ms, frame);
1365 nv->nvEncUnlockInputBuffer(ctx->nvenc_ctx, nvenc_frame->in);
1369 ret = nv->nvEncUnlockInputBuffer(ctx->nvenc_ctx, nvenc_frame->in);
1370 if (ret != NV_ENC_SUCCESS)
1371 return nvenc_print_error(avctx, ret, "Cannot unlock the buffer");
1377 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1378 NV_ENC_PIC_PARAMS *params)
1380 NVENCContext *ctx = avctx->priv_data;
1382 switch (avctx->codec->id) {
1383 case AV_CODEC_ID_H264:
1384 params->codecPicParams.h264PicParams.sliceMode =
1385 ctx->config.encodeCodecConfig.h264Config.sliceMode;
1386 params->codecPicParams.h264PicParams.sliceModeData =
1387 ctx->config.encodeCodecConfig.h264Config.sliceModeData;
1389 case AV_CODEC_ID_HEVC:
1390 params->codecPicParams.hevcPicParams.sliceMode =
1391 ctx->config.encodeCodecConfig.hevcConfig.sliceMode;
1392 params->codecPicParams.hevcPicParams.sliceModeData =
1393 ctx->config.encodeCodecConfig.hevcConfig.sliceModeData;
1398 static inline int nvenc_enqueue_timestamp(AVFifoBuffer *f, int64_t pts)
1400 return av_fifo_generic_write(f, &pts, sizeof(pts), NULL);
1403 static inline int nvenc_dequeue_timestamp(AVFifoBuffer *f, int64_t *pts)
1405 return av_fifo_generic_read(f, pts, sizeof(*pts), NULL);
1408 static int nvenc_set_timestamp(AVCodecContext *avctx,
1409 NV_ENC_LOCK_BITSTREAM *params,
1412 NVENCContext *ctx = avctx->priv_data;
1414 pkt->pts = params->outputTimeStamp;
1415 pkt->duration = params->outputDuration;
1417 /* generate the first dts by linearly extrapolating the
1418 * first two pts values to the past */
1419 if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
1420 ctx->initial_pts[1] != AV_NOPTS_VALUE) {
1421 int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
1424 if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
1425 (ts0 > 0 && ts1 < INT64_MIN + ts0))
1426 return AVERROR(ERANGE);
1429 if ((delta < 0 && ts0 > INT64_MAX + delta) ||
1430 (delta > 0 && ts0 < INT64_MIN + delta))
1431 return AVERROR(ERANGE);
1432 pkt->dts = ts0 - delta;
1434 ctx->first_packet_output = 1;
1437 return nvenc_dequeue_timestamp(ctx->timestamps, &pkt->dts);
1440 static int nvenc_get_output(AVCodecContext *avctx, AVPacket *pkt)
1442 NVENCContext *ctx = avctx->priv_data;
1443 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1444 NV_ENC_LOCK_BITSTREAM params = { 0 };
1448 ret = av_fifo_generic_read(ctx->ready, &frame, sizeof(frame), NULL);
1452 params.version = NV_ENC_LOCK_BITSTREAM_VER;
1453 params.outputBitstream = frame->out;
1455 ret = nv->nvEncLockBitstream(ctx->nvenc_ctx, ¶ms);
1457 return nvenc_print_error(avctx, ret, "Cannot lock the bitstream");
1459 ret = ff_alloc_packet(pkt, params.bitstreamSizeInBytes);
1463 memcpy(pkt->data, params.bitstreamBufferPtr, pkt->size);
1465 ret = nv->nvEncUnlockBitstream(ctx->nvenc_ctx, frame->out);
1467 return nvenc_print_error(avctx, ret, "Cannot unlock the bitstream");
1469 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1470 nv->nvEncUnmapInputResource(ctx->nvenc_ctx, frame->in_map.mappedResource);
1471 av_frame_unref(frame->in_ref);
1472 ctx->registered_frames[frame->reg_idx].mapped = 0;
1479 ret = nvenc_set_timestamp(avctx, ¶ms, pkt);
1483 switch (params.pictureType) {
1484 case NV_ENC_PIC_TYPE_IDR:
1485 pkt->flags |= AV_PKT_FLAG_KEY;
1486 #if FF_API_CODED_FRAME
1487 FF_DISABLE_DEPRECATION_WARNINGS
1488 case NV_ENC_PIC_TYPE_INTRA_REFRESH:
1489 case NV_ENC_PIC_TYPE_I:
1490 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
1492 case NV_ENC_PIC_TYPE_P:
1493 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
1495 case NV_ENC_PIC_TYPE_B:
1496 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;
1498 case NV_ENC_PIC_TYPE_BI:
1499 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_BI;
1501 FF_ENABLE_DEPRECATION_WARNINGS
1508 static int output_ready(AVCodecContext *avctx, int flush)
1510 NVENCContext *ctx = avctx->priv_data;
1511 int nb_ready, nb_pending;
1513 /* when B-frames are enabled, we wait for two initial timestamps to
1514 * calculate the first dts */
1515 if (!flush && avctx->max_b_frames > 0 &&
1516 (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
1519 nb_ready = av_fifo_size(ctx->ready) / sizeof(NVENCFrame*);
1520 nb_pending = av_fifo_size(ctx->pending) / sizeof(NVENCFrame*);
1522 return nb_ready > 0;
1523 return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
1526 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1527 const AVFrame *frame, int *got_packet)
1529 NVENCContext *ctx = avctx->priv_data;
1530 NVENCLibraryContext *nvel = &ctx->nvel;
1531 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1532 NV_ENC_PIC_PARAMS params = { 0 };
1533 NVENCFrame *nvenc_frame = NULL;
1537 params.version = NV_ENC_PIC_PARAMS_VER;
1540 nvenc_frame = get_free_frame(ctx);
1542 av_log(avctx, AV_LOG_ERROR, "No free surfaces\n");
1546 ret = nvenc_upload_frame(avctx, frame, nvenc_frame);
1550 params.inputBuffer = nvenc_frame->in;
1551 params.bufferFmt = nvenc_frame->format;
1552 params.inputWidth = frame->width;
1553 params.inputHeight = frame->height;
1554 params.outputBitstream = nvenc_frame->out;
1555 params.inputTimeStamp = frame->pts;
1557 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1558 if (frame->top_field_first)
1559 params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
1561 params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
1563 params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1566 nvenc_codec_specific_pic_params(avctx, ¶ms);
1568 ret = nvenc_enqueue_timestamp(ctx->timestamps, frame->pts);
1572 if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
1573 ctx->initial_pts[0] = frame->pts;
1574 else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
1575 ctx->initial_pts[1] = frame->pts;
1577 params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1580 nvel->cu_ctx_push_current(ctx->cu_context);
1581 enc_ret = nv->nvEncEncodePicture(ctx->nvenc_ctx, ¶ms);
1582 nvel->cu_ctx_pop_current(&dummy);
1584 if (enc_ret != NV_ENC_SUCCESS &&
1585 enc_ret != NV_ENC_ERR_NEED_MORE_INPUT)
1586 return nvenc_print_error(avctx, enc_ret, "Error encoding the frame");
1589 ret = av_fifo_generic_write(ctx->pending, &nvenc_frame, sizeof(nvenc_frame), NULL);
1594 /* all the pending buffers are now ready for output */
1595 if (enc_ret == NV_ENC_SUCCESS) {
1596 while (av_fifo_size(ctx->pending) > 0) {
1597 av_fifo_generic_read(ctx->pending, &nvenc_frame, sizeof(nvenc_frame), NULL);
1598 av_fifo_generic_write(ctx->ready, &nvenc_frame, sizeof(nvenc_frame), NULL);
1602 if (output_ready(avctx, !frame)) {
1603 ret = nvenc_get_output(avctx, pkt);