3 * Copyright (C) 2015 Luca Barbato
5 * This file is part of Libav.
7 * Libav 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 * Libav 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 Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 #include <nvEncodeAPI.h>
28 #define CUDA_LIBNAME "libcuda.so"
33 #define NVENC_LIBNAME "libnvidia-encode.so"
39 #define NVENC_LIBNAME "nvEncodeAPI64.dll"
41 #define NVENC_LIBNAME "nvEncodeAPI.dll"
44 #define dlopen(filename, flags) LoadLibrary((filename))
45 #define dlsym(handle, symbol) GetProcAddress(handle, symbol)
46 #define dlclose(handle) FreeLibrary(handle)
49 #include "libavutil/common.h"
50 #include "libavutil/imgutils.h"
51 #include "libavutil/mem.h"
56 #define NVENC_CAP 0x30
57 #define BITSTREAM_BUFFER_SIZE 1024 * 1024
59 #define LOAD_LIBRARY(l, path) \
61 if (!((l) = dlopen(path, RTLD_LAZY))) { \
62 av_log(avctx, AV_LOG_ERROR, \
65 return AVERROR_UNKNOWN; \
69 #define LOAD_SYMBOL(fun, lib, symbol) \
71 if (!((fun) = dlsym(lib, symbol))) { \
72 av_log(avctx, AV_LOG_ERROR, \
75 return AVERROR_UNKNOWN; \
79 const enum AVPixelFormat ff_nvenc_pix_fmts[] = {
91 { NV_ENC_SUCCESS, 0, "success" },
92 { NV_ENC_ERR_NO_ENCODE_DEVICE, AVERROR(ENOENT), "no encode device" },
93 { NV_ENC_ERR_UNSUPPORTED_DEVICE, AVERROR(ENOSYS), "unsupported device" },
94 { NV_ENC_ERR_INVALID_ENCODERDEVICE, AVERROR(EINVAL), "invalid encoder device" },
95 { NV_ENC_ERR_INVALID_DEVICE, AVERROR(EINVAL), "invalid device" },
96 { NV_ENC_ERR_DEVICE_NOT_EXIST, AVERROR(EIO), "device does not exist" },
97 { NV_ENC_ERR_INVALID_PTR, AVERROR(EFAULT), "invalid ptr" },
98 { NV_ENC_ERR_INVALID_EVENT, AVERROR(EINVAL), "invalid event" },
99 { NV_ENC_ERR_INVALID_PARAM, AVERROR(EINVAL), "invalid param" },
100 { NV_ENC_ERR_INVALID_CALL, AVERROR(EINVAL), "invalid call" },
101 { NV_ENC_ERR_OUT_OF_MEMORY, AVERROR(ENOMEM), "out of memory" },
102 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED, AVERROR(EINVAL), "encoder not initialized" },
103 { NV_ENC_ERR_UNSUPPORTED_PARAM, AVERROR(ENOSYS), "unsupported param" },
104 { NV_ENC_ERR_LOCK_BUSY, AVERROR(EAGAIN), "lock busy" },
105 { NV_ENC_ERR_NOT_ENOUGH_BUFFER, AVERROR(ENOBUFS), "not enough buffer" },
106 { NV_ENC_ERR_INVALID_VERSION, AVERROR(EINVAL), "invalid version" },
107 { NV_ENC_ERR_MAP_FAILED, AVERROR(EIO), "map failed" },
108 { NV_ENC_ERR_NEED_MORE_INPUT, AVERROR(EAGAIN), "need more input" },
109 { NV_ENC_ERR_ENCODER_BUSY, AVERROR(EAGAIN), "encoder busy" },
110 { NV_ENC_ERR_EVENT_NOT_REGISTERD, AVERROR(EBADF), "event not registered" },
111 { NV_ENC_ERR_GENERIC, AVERROR_UNKNOWN, "generic error" },
112 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY, AVERROR(EINVAL), "incompatible client key" },
113 { NV_ENC_ERR_UNIMPLEMENTED, AVERROR(ENOSYS), "unimplemented" },
114 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO), "resource register failed" },
115 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED, AVERROR(EBADF), "resource not registered" },
116 { NV_ENC_ERR_RESOURCE_NOT_MAPPED, AVERROR(EBADF), "resource not mapped" },
119 static int nvenc_map_error(NVENCSTATUS err, const char **desc)
122 for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
123 if (nvenc_errors[i].nverr == err) {
125 *desc = nvenc_errors[i].desc;
126 return nvenc_errors[i].averr;
130 *desc = "unknown error";
131 return AVERROR_UNKNOWN;
134 static int nvenc_print_error(void *log_ctx, NVENCSTATUS err,
135 const char *error_string)
139 ret = nvenc_map_error(err, &desc);
140 av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
144 static av_cold int nvenc_load_libraries(AVCodecContext *avctx)
146 NVENCContext *ctx = avctx->priv_data;
147 NVENCLibraryContext *nvel = &ctx->nvel;
148 PNVENCODEAPICREATEINSTANCE nvenc_create_instance;
151 LOAD_LIBRARY(nvel->cuda, CUDA_LIBNAME);
153 LOAD_SYMBOL(nvel->cu_init, nvel->cuda, "cuInit");
154 LOAD_SYMBOL(nvel->cu_device_get_count, nvel->cuda, "cuDeviceGetCount");
155 LOAD_SYMBOL(nvel->cu_device_get, nvel->cuda, "cuDeviceGet");
156 LOAD_SYMBOL(nvel->cu_device_get_name, nvel->cuda, "cuDeviceGetName");
157 LOAD_SYMBOL(nvel->cu_device_compute_capability, nvel->cuda,
158 "cuDeviceComputeCapability");
159 LOAD_SYMBOL(nvel->cu_ctx_create, nvel->cuda, "cuCtxCreate_v2");
160 LOAD_SYMBOL(nvel->cu_ctx_pop_current, nvel->cuda, "cuCtxPopCurrent_v2");
161 LOAD_SYMBOL(nvel->cu_ctx_destroy, nvel->cuda, "cuCtxDestroy_v2");
163 LOAD_LIBRARY(nvel->nvenc, NVENC_LIBNAME);
165 LOAD_SYMBOL(nvenc_create_instance, nvel->nvenc,
166 "NvEncodeAPICreateInstance");
168 nvel->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
170 err = nvenc_create_instance(&nvel->nvenc_funcs);
171 if (err != NV_ENC_SUCCESS)
172 return nvenc_print_error(avctx, err, "Cannot create the NVENC instance");
177 static int nvenc_open_session(AVCodecContext *avctx)
179 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
180 NVENCContext *ctx = avctx->priv_data;
181 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
184 params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
185 params.apiVersion = NVENCAPI_VERSION;
186 params.device = ctx->cu_context;
187 params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
189 ret = nv->nvEncOpenEncodeSessionEx(¶ms, &ctx->nvenc_ctx);
190 if (ret != NV_ENC_SUCCESS) {
191 ctx->nvenc_ctx = NULL;
192 return nvenc_print_error(avctx, ret, "Cannot open the NVENC Session");
198 static int nvenc_check_codec_support(AVCodecContext *avctx)
200 NVENCContext *ctx = avctx->priv_data;
201 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
202 int i, ret, count = 0;
205 ret = nv->nvEncGetEncodeGUIDCount(ctx->nvenc_ctx, &count);
207 if (ret != NV_ENC_SUCCESS || !count)
208 return AVERROR(ENOSYS);
210 guids = av_malloc(count * sizeof(GUID));
212 return AVERROR(ENOMEM);
214 ret = nv->nvEncGetEncodeGUIDs(ctx->nvenc_ctx, guids, count, &count);
215 if (ret != NV_ENC_SUCCESS) {
216 ret = AVERROR(ENOSYS);
220 ret = AVERROR(ENOSYS);
221 for (i = 0; i < count; i++) {
222 if (!memcmp(&guids[i], &ctx->params.encodeGUID, sizeof(*guids))) {
234 static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
236 NVENCContext *ctx = avctx->priv_data;
237 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
238 NV_ENC_CAPS_PARAM params = { 0 };
241 params.version = NV_ENC_CAPS_PARAM_VER;
242 params.capsToQuery = cap;
244 ret = nv->nvEncGetEncodeCaps(ctx->nvenc_ctx, ctx->params.encodeGUID, ¶ms, &val);
246 if (ret == NV_ENC_SUCCESS)
251 static int nvenc_check_capabilities(AVCodecContext *avctx)
255 ret = nvenc_check_codec_support(avctx);
257 av_log(avctx, AV_LOG_VERBOSE, "Codec not supported\n");
261 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
262 if (avctx->pix_fmt == AV_PIX_FMT_YUV444P && ret <= 0) {
263 av_log(avctx, AV_LOG_VERBOSE, "YUV444P not supported\n");
264 return AVERROR(ENOSYS);
267 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
268 if (ret < avctx->width) {
269 av_log(avctx, AV_LOG_VERBOSE, "Width %d exceeds %d\n",
271 return AVERROR(ENOSYS);
274 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
275 if (ret < avctx->height) {
276 av_log(avctx, AV_LOG_VERBOSE, "Height %d exceeds %d\n",
278 return AVERROR(ENOSYS);
281 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
282 if (ret < avctx->max_b_frames) {
283 av_log(avctx, AV_LOG_VERBOSE, "Max b-frames %d exceed %d\n",
284 avctx->max_b_frames, ret);
286 return AVERROR(ENOSYS);
292 static int nvenc_check_device(AVCodecContext *avctx, int idx)
294 NVENCContext *ctx = avctx->priv_data;
295 NVENCLibraryContext *nvel = &ctx->nvel;
296 char name[128] = { 0 };
297 int major, minor, ret;
300 int loglevel = AV_LOG_VERBOSE;
302 if (ctx->device == LIST_DEVICES)
303 loglevel = AV_LOG_INFO;
305 ret = nvel->cu_device_get(&cu_device, idx);
306 if (ret != CUDA_SUCCESS) {
307 av_log(avctx, AV_LOG_ERROR,
308 "Cannot access the CUDA device %d\n",
313 ret = nvel->cu_device_get_name(name, sizeof(name), cu_device);
314 if (ret != CUDA_SUCCESS)
317 ret = nvel->cu_device_compute_capability(&major, &minor, cu_device);
318 if (ret != CUDA_SUCCESS)
321 av_log(avctx, loglevel, "Device %d [%s] ", cu_device, name);
323 if (((major << 4) | minor) < NVENC_CAP)
326 ret = nvel->cu_ctx_create(&ctx->cu_context, 0, cu_device);
327 if (ret != CUDA_SUCCESS)
330 ret = nvel->cu_ctx_pop_current(&dummy);
331 if (ret != CUDA_SUCCESS)
334 if ((ret = nvenc_open_session(avctx)) < 0)
337 if ((ret = nvenc_check_capabilities(avctx)) < 0)
340 av_log(avctx, loglevel, "supports NVENC\n");
342 if (ctx->device == cu_device || ctx->device == ANY_DEVICE)
346 nvel->nvenc_funcs.nvEncDestroyEncoder(ctx->nvenc_ctx);
347 ctx->nvenc_ctx = NULL;
350 nvel->cu_ctx_destroy(ctx->cu_context);
351 ctx->cu_context = NULL;
355 av_log(avctx, loglevel, "does not support NVENC (major %d minor %d)\n",
358 return AVERROR(ENOSYS);
361 static int nvenc_setup_device(AVCodecContext *avctx)
363 NVENCContext *ctx = avctx->priv_data;
364 NVENCLibraryContext *nvel = &ctx->nvel;
365 int i, nb_devices = 0;
367 if ((nvel->cu_init(0)) != CUDA_SUCCESS) {
368 av_log(avctx, AV_LOG_ERROR,
369 "Cannot init CUDA\n");
370 return AVERROR_UNKNOWN;
373 if ((nvel->cu_device_get_count(&nb_devices)) != CUDA_SUCCESS) {
374 av_log(avctx, AV_LOG_ERROR,
375 "Cannot enumerate the CUDA devices\n");
376 return AVERROR_UNKNOWN;
379 switch (avctx->codec->id) {
380 case AV_CODEC_ID_H264:
381 ctx->params.encodeGUID = NV_ENC_CODEC_H264_GUID;
383 case AV_CODEC_ID_HEVC:
384 ctx->params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
390 for (i = 0; i < nb_devices; ++i) {
391 if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
395 if (ctx->device == LIST_DEVICES)
398 return AVERROR(ENOSYS);
401 typedef struct GUIDTuple {
406 static int nvec_map_preset(NVENCContext *ctx)
408 GUIDTuple presets[] = {
409 { NV_ENC_PRESET_DEFAULT_GUID },
410 { NV_ENC_PRESET_HP_GUID },
411 { NV_ENC_PRESET_HQ_GUID },
412 { NV_ENC_PRESET_BD_GUID },
413 { NV_ENC_PRESET_LOW_LATENCY_DEFAULT_GUID, NVENC_LOWLATENCY },
414 { NV_ENC_PRESET_LOW_LATENCY_HP_GUID, NVENC_LOWLATENCY },
415 { NV_ENC_PRESET_LOW_LATENCY_HQ_GUID, NVENC_LOWLATENCY },
416 { NV_ENC_PRESET_LOSSLESS_DEFAULT_GUID, NVENC_LOSSLESS },
417 { NV_ENC_PRESET_LOSSLESS_HP_GUID, NVENC_LOSSLESS },
421 GUIDTuple *t = &presets[ctx->preset];
423 ctx->params.presetGUID = t->guid;
424 ctx->flags = t->flags;
426 return AVERROR(EINVAL);
429 static void set_constqp(AVCodecContext *avctx, NV_ENC_RC_PARAMS *rc)
431 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
432 rc->constQP.qpInterB = avctx->global_quality;
433 rc->constQP.qpInterP = avctx->global_quality;
434 rc->constQP.qpIntra = avctx->global_quality;
437 static void set_vbr(AVCodecContext *avctx, NV_ENC_RC_PARAMS *rc)
439 if (avctx->qmin >= 0) {
441 rc->minQP.qpInterB = avctx->qmin;
442 rc->minQP.qpInterP = avctx->qmin;
443 rc->minQP.qpIntra = avctx->qmin;
446 if (avctx->qmax >= 0) {
448 rc->maxQP.qpInterB = avctx->qmax;
449 rc->maxQP.qpInterP = avctx->qmax;
450 rc->maxQP.qpIntra = avctx->qmax;
454 static void nvenc_override_rate_control(AVCodecContext *avctx,
455 NV_ENC_RC_PARAMS *rc)
457 NVENCContext *ctx = avctx->priv_data;
460 case NV_ENC_PARAMS_RC_CONSTQP:
461 if (avctx->global_quality < 0) {
462 av_log(avctx, AV_LOG_WARNING,
463 "The constant quality rate-control requires "
464 "the 'global_quality' option set.\n");
467 set_constqp(avctx, rc);
469 case NV_ENC_PARAMS_RC_2_PASS_VBR:
470 case NV_ENC_PARAMS_RC_VBR:
471 if (avctx->qmin < 0 && avctx->qmax < 0) {
472 av_log(avctx, AV_LOG_WARNING,
473 "The variable bitrate rate-control requires "
474 "the 'qmin' and/or 'qmax' option set.\n");
477 case NV_ENC_PARAMS_RC_VBR_MINQP:
478 if (avctx->qmin < 0) {
479 av_log(avctx, AV_LOG_WARNING,
480 "The variable bitrate rate-control requires "
481 "the 'qmin' option set.\n");
486 case NV_ENC_PARAMS_RC_CBR:
488 case NV_ENC_PARAMS_RC_2_PASS_QUALITY:
489 case NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP:
490 if (!(ctx->flags & NVENC_LOWLATENCY)) {
491 av_log(avctx, AV_LOG_WARNING,
492 "The multipass rate-control requires "
493 "a low-latency preset.\n");
498 rc->rateControlMode = ctx->rc;
501 static void nvenc_setup_rate_control(AVCodecContext *avctx)
503 NVENCContext *ctx = avctx->priv_data;
504 NV_ENC_RC_PARAMS *rc = &ctx->config.rcParams;
506 if (avctx->bit_rate > 0)
507 rc->averageBitRate = avctx->bit_rate;
509 if (avctx->rc_max_rate > 0)
510 rc->maxBitRate = avctx->rc_max_rate;
513 nvenc_override_rate_control(avctx, rc);
514 } else if (avctx->global_quality > 0) {
515 set_constqp(avctx, rc);
516 } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
517 rc->rateControlMode = NV_ENC_PARAMS_RC_VBR;
521 if (avctx->rc_buffer_size > 0)
522 rc->vbvBufferSize = avctx->rc_buffer_size;
524 if (rc->averageBitRate > 0)
525 avctx->bit_rate = rc->averageBitRate;
528 static int nvenc_setup_h264_config(AVCodecContext *avctx)
530 NVENCContext *ctx = avctx->priv_data;
531 NV_ENC_CONFIG *cc = &ctx->config;
532 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
533 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
535 vui->colourDescriptionPresentFlag = 1;
536 vui->videoSignalTypePresentFlag = 1;
538 vui->colourMatrix = avctx->colorspace;
539 vui->colourPrimaries = avctx->color_primaries;
540 vui->transferCharacteristics = avctx->color_trc;
542 vui->videoFullRangeFlag = avctx->color_range == AVCOL_RANGE_JPEG;
544 h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
545 h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
547 h264->maxNumRefFrames = avctx->refs;
548 h264->idrPeriod = cc->gopLength;
551 avctx->profile = ctx->profile;
553 if (avctx->pix_fmt == AV_PIX_FMT_YUV444P)
554 h264->chromaFormatIDC = 3;
556 h264->chromaFormatIDC = 1;
558 switch (ctx->profile) {
559 case NV_ENC_H264_PROFILE_BASELINE:
560 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
562 case NV_ENC_H264_PROFILE_MAIN:
563 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
565 case NV_ENC_H264_PROFILE_HIGH:
566 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
568 case NV_ENC_H264_PROFILE_HIGH_444:
569 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
571 case NV_ENC_H264_PROFILE_CONSTRAINED_HIGH:
572 cc->profileGUID = NV_ENC_H264_PROFILE_CONSTRAINED_HIGH_GUID;
576 h264->level = ctx->level;
581 static int nvenc_setup_hevc_config(AVCodecContext *avctx)
583 NVENCContext *ctx = avctx->priv_data;
584 NV_ENC_CONFIG *cc = &ctx->config;
585 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
587 hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
588 hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
590 hevc->maxNumRefFramesInDPB = avctx->refs;
591 hevc->idrPeriod = cc->gopLength;
593 /* No other profile is supported in the current SDK version 5 */
594 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
595 avctx->profile = FF_PROFILE_HEVC_MAIN;
598 hevc->level = ctx->level;
600 hevc->level = NV_ENC_LEVEL_AUTOSELECT;
604 hevc->tier = ctx->tier;
609 static int nvenc_setup_codec_config(AVCodecContext *avctx)
611 switch (avctx->codec->id) {
612 case AV_CODEC_ID_H264:
613 return nvenc_setup_h264_config(avctx);
614 case AV_CODEC_ID_HEVC:
615 return nvenc_setup_hevc_config(avctx);
620 static int nvenc_setup_encoder(AVCodecContext *avctx)
622 NVENCContext *ctx = avctx->priv_data;
623 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
624 NV_ENC_PRESET_CONFIG preset_cfg = { 0 };
625 AVCPBProperties *cpb_props;
628 ctx->params.version = NV_ENC_INITIALIZE_PARAMS_VER;
630 ctx->params.encodeHeight = avctx->height;
631 ctx->params.encodeWidth = avctx->width;
633 if (avctx->sample_aspect_ratio.num &&
634 avctx->sample_aspect_ratio.den &&
635 (avctx->sample_aspect_ratio.num != 1 ||
636 avctx->sample_aspect_ratio.den != 1)) {
637 av_reduce(&ctx->params.darWidth,
638 &ctx->params.darHeight,
639 avctx->width * avctx->sample_aspect_ratio.num,
640 avctx->height * avctx->sample_aspect_ratio.den,
643 ctx->params.darHeight = avctx->height;
644 ctx->params.darWidth = avctx->width;
647 ctx->params.frameRateNum = avctx->time_base.den;
648 ctx->params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
650 ctx->params.enableEncodeAsync = 0;
651 ctx->params.enablePTD = 1;
653 ctx->params.encodeConfig = &ctx->config;
655 nvec_map_preset(ctx);
657 preset_cfg.version = NV_ENC_PRESET_CONFIG_VER;
658 preset_cfg.presetCfg.version = NV_ENC_CONFIG_VER;
660 ret = nv->nvEncGetEncodePresetConfig(ctx->nvenc_ctx,
661 ctx->params.encodeGUID,
662 ctx->params.presetGUID,
664 if (ret != NV_ENC_SUCCESS)
665 return nvenc_print_error(avctx, ret, "Cannot get the preset configuration");
667 memcpy(&ctx->config, &preset_cfg.presetCfg, sizeof(ctx->config));
669 ctx->config.version = NV_ENC_CONFIG_VER;
671 if (avctx->gop_size > 0) {
672 if (avctx->max_b_frames > 0) {
676 * 3 two B frames, and so on. */
677 ctx->config.frameIntervalP = avctx->max_b_frames + 1;
678 } else if (avctx->max_b_frames == 0) {
679 ctx->config.frameIntervalP = 1;
681 ctx->config.gopLength = avctx->gop_size;
682 } else if (avctx->gop_size == 0) {
683 ctx->config.frameIntervalP = 0;
684 ctx->config.gopLength = 1;
687 if (ctx->config.frameIntervalP > 1)
688 avctx->max_b_frames = ctx->config.frameIntervalP - 1;
690 ctx->initial_pts[0] = AV_NOPTS_VALUE;
691 ctx->initial_pts[1] = AV_NOPTS_VALUE;
693 nvenc_setup_rate_control(avctx);
695 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
696 ctx->config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
698 ctx->config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
701 if ((ret = nvenc_setup_codec_config(avctx)) < 0)
704 ret = nv->nvEncInitializeEncoder(ctx->nvenc_ctx, &ctx->params);
705 if (ret != NV_ENC_SUCCESS)
706 return nvenc_print_error(avctx, ret, "Cannot initialize the decoder");
708 cpb_props = ff_add_cpb_side_data(avctx);
710 return AVERROR(ENOMEM);
711 cpb_props->max_bitrate = avctx->rc_max_rate;
712 cpb_props->min_bitrate = avctx->rc_min_rate;
713 cpb_props->avg_bitrate = avctx->bit_rate;
714 cpb_props->buffer_size = avctx->rc_buffer_size;
719 static int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
721 NVENCContext *ctx = avctx->priv_data;
722 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
724 NV_ENC_CREATE_INPUT_BUFFER in_buffer = { 0 };
725 NV_ENC_CREATE_BITSTREAM_BUFFER out_buffer = { 0 };
727 in_buffer.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
728 out_buffer.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
730 in_buffer.width = avctx->width;
731 in_buffer.height = avctx->height;
733 in_buffer.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED;
735 switch (avctx->pix_fmt) {
736 case AV_PIX_FMT_YUV420P:
737 in_buffer.bufferFmt = NV_ENC_BUFFER_FORMAT_YV12_PL;
739 case AV_PIX_FMT_NV12:
740 in_buffer.bufferFmt = NV_ENC_BUFFER_FORMAT_NV12_PL;
742 case AV_PIX_FMT_YUV444P:
743 in_buffer.bufferFmt = NV_ENC_BUFFER_FORMAT_YUV444_PL;
749 ret = nv->nvEncCreateInputBuffer(ctx->nvenc_ctx, &in_buffer);
750 if (ret != NV_ENC_SUCCESS)
751 return nvenc_print_error(avctx, ret, "CreateInputBuffer failed");
753 ctx->frames[idx].in = in_buffer.inputBuffer;
754 ctx->frames[idx].format = in_buffer.bufferFmt;
756 /* 1MB is large enough to hold most output frames.
757 * NVENC increases this automaticaly if it's not enough. */
758 out_buffer.size = BITSTREAM_BUFFER_SIZE;
760 out_buffer.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED;
762 ret = nv->nvEncCreateBitstreamBuffer(ctx->nvenc_ctx, &out_buffer);
763 if (ret != NV_ENC_SUCCESS)
764 return nvenc_print_error(avctx, ret, "CreateBitstreamBuffer failed");
766 ctx->frames[idx].out = out_buffer.bitstreamBuffer;
771 static int nvenc_setup_surfaces(AVCodecContext *avctx)
773 NVENCContext *ctx = avctx->priv_data;
776 ctx->nb_surfaces = FFMAX(4 + avctx->max_b_frames,
779 ctx->frames = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->frames));
781 return AVERROR(ENOMEM);
783 ctx->timestamps = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
784 if (!ctx->timestamps)
785 return AVERROR(ENOMEM);
786 ctx->pending = av_fifo_alloc(ctx->nb_surfaces * sizeof(*ctx->frames));
788 return AVERROR(ENOMEM);
789 ctx->ready = av_fifo_alloc(ctx->nb_surfaces * sizeof(*ctx->frames));
791 return AVERROR(ENOMEM);
793 for (i = 0; i < ctx->nb_surfaces; i++) {
794 if ((ret = nvenc_alloc_surface(avctx, i)) < 0)
801 #define EXTRADATA_SIZE 512
803 static int nvenc_setup_extradata(AVCodecContext *avctx)
805 NVENCContext *ctx = avctx->priv_data;
806 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
807 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
810 avctx->extradata = av_mallocz(EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
811 if (!avctx->extradata)
812 return AVERROR(ENOMEM);
814 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
815 payload.spsppsBuffer = avctx->extradata;
816 payload.inBufferSize = EXTRADATA_SIZE;
817 payload.outSPSPPSPayloadSize = &avctx->extradata_size;
819 ret = nv->nvEncGetSequenceParams(ctx->nvenc_ctx, &payload);
820 if (ret != NV_ENC_SUCCESS)
821 return nvenc_print_error(avctx, ret, "Cannot get the extradata");
826 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
828 NVENCContext *ctx = avctx->priv_data;
829 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
832 /* the encoder has to be flushed before it can be closed */
833 if (ctx->nvenc_ctx) {
834 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
835 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
837 nv->nvEncEncodePicture(ctx->nvenc_ctx, ¶ms);
840 av_fifo_free(ctx->timestamps);
841 av_fifo_free(ctx->pending);
842 av_fifo_free(ctx->ready);
845 for (i = 0; i < ctx->nb_surfaces; ++i) {
846 nv->nvEncDestroyInputBuffer(ctx->nvenc_ctx, ctx->frames[i].in);
847 nv->nvEncDestroyBitstreamBuffer(ctx->nvenc_ctx, ctx->frames[i].out);
851 av_freep(&ctx->frames);
854 nv->nvEncDestroyEncoder(ctx->nvenc_ctx);
857 ctx->nvel.cu_ctx_destroy(ctx->cu_context);
860 dlclose(ctx->nvel.nvenc);
863 dlclose(ctx->nvel.cuda);
868 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
872 if ((ret = nvenc_load_libraries(avctx)) < 0)
875 if ((ret = nvenc_setup_device(avctx)) < 0)
878 if ((ret = nvenc_setup_encoder(avctx)) < 0)
881 if ((ret = nvenc_setup_surfaces(avctx)) < 0)
884 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
885 if ((ret = nvenc_setup_extradata(avctx)) < 0)
892 static NVENCFrame *get_free_frame(NVENCContext *ctx)
896 for (i = 0; i < ctx->nb_surfaces; i++) {
897 if (!ctx->frames[i].locked) {
898 ctx->frames[i].locked = 1;
899 return &ctx->frames[i];
906 static int nvenc_copy_frame(NV_ENC_LOCK_INPUT_BUFFER *in, const AVFrame *frame)
908 uint8_t *buf = in->bufferDataPtr;
909 int off = frame->height * in->pitch;
911 switch (frame->format) {
912 case AV_PIX_FMT_YUV420P:
913 av_image_copy_plane(buf, in->pitch,
914 frame->data[0], frame->linesize[0],
915 frame->width, frame->height);
918 av_image_copy_plane(buf, in->pitch >> 1,
919 frame->data[2], frame->linesize[2],
920 frame->width >> 1, frame->height >> 1);
924 av_image_copy_plane(buf, in->pitch >> 1,
925 frame->data[1], frame->linesize[1],
926 frame->width >> 1, frame->height >> 1);
928 case AV_PIX_FMT_NV12:
929 av_image_copy_plane(buf, in->pitch,
930 frame->data[0], frame->linesize[0],
931 frame->width, frame->height);
934 av_image_copy_plane(buf, in->pitch,
935 frame->data[1], frame->linesize[1],
936 frame->width, frame->height >> 1);
938 case AV_PIX_FMT_YUV444P:
939 av_image_copy_plane(buf, in->pitch,
940 frame->data[0], frame->linesize[0],
941 frame->width, frame->height);
944 av_image_copy_plane(buf, in->pitch,
945 frame->data[1], frame->linesize[1],
946 frame->width, frame->height);
949 av_image_copy_plane(buf, in->pitch,
950 frame->data[2], frame->linesize[2],
951 frame->width, frame->height);
960 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
961 NVENCFrame *nvenc_frame)
963 NVENCContext *ctx = avctx->priv_data;
964 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
965 NV_ENC_LOCK_INPUT_BUFFER params = { 0 };
968 params.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
969 params.inputBuffer = nvenc_frame->in;
972 ret = nv->nvEncLockInputBuffer(ctx->nvenc_ctx, ¶ms);
973 if (ret != NV_ENC_SUCCESS)
974 return nvenc_print_error(avctx, ret, "Cannot lock the buffer");
976 ret = nvenc_copy_frame(¶ms, frame);
980 ret = nv->nvEncUnlockInputBuffer(ctx->nvenc_ctx, nvenc_frame->in);
981 if (ret != NV_ENC_SUCCESS)
982 return nvenc_print_error(avctx, ret, "Cannot unlock the buffer");
987 nv->nvEncUnlockInputBuffer(ctx->nvenc_ctx, nvenc_frame->in);
992 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
993 NV_ENC_PIC_PARAMS *params)
995 NVENCContext *ctx = avctx->priv_data;
997 switch (avctx->codec->id) {
998 case AV_CODEC_ID_H264:
999 params->codecPicParams.h264PicParams.sliceMode =
1000 ctx->config.encodeCodecConfig.h264Config.sliceMode;
1001 params->codecPicParams.h264PicParams.sliceModeData =
1002 ctx->config.encodeCodecConfig.h264Config.sliceModeData;
1004 case AV_CODEC_ID_HEVC:
1005 params->codecPicParams.hevcPicParams.sliceMode =
1006 ctx->config.encodeCodecConfig.hevcConfig.sliceMode;
1007 params->codecPicParams.hevcPicParams.sliceModeData =
1008 ctx->config.encodeCodecConfig.hevcConfig.sliceModeData;
1013 static inline int nvenc_enqueue_timestamp(AVFifoBuffer *f, int64_t pts)
1015 return av_fifo_generic_write(f, &pts, sizeof(pts), NULL);
1018 static inline int nvenc_dequeue_timestamp(AVFifoBuffer *f, int64_t *pts)
1020 return av_fifo_generic_read(f, pts, sizeof(*pts), NULL);
1023 static int nvenc_set_timestamp(AVCodecContext *avctx,
1024 NV_ENC_LOCK_BITSTREAM *params,
1027 NVENCContext *ctx = avctx->priv_data;
1029 pkt->pts = params->outputTimeStamp;
1030 pkt->duration = params->outputDuration;
1032 /* generate the first dts by linearly extrapolating the
1033 * first two pts values to the past */
1034 if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
1035 ctx->initial_pts[1] != AV_NOPTS_VALUE) {
1036 int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
1039 if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
1040 (ts0 > 0 && ts1 < INT64_MIN + ts0))
1041 return AVERROR(ERANGE);
1044 if ((delta < 0 && ts0 > INT64_MAX + delta) ||
1045 (delta > 0 && ts0 < INT64_MIN + delta))
1046 return AVERROR(ERANGE);
1047 pkt->dts = ts0 - delta;
1049 ctx->first_packet_output = 1;
1052 return nvenc_dequeue_timestamp(ctx->timestamps, &pkt->dts);
1055 static int nvenc_get_output(AVCodecContext *avctx, AVPacket *pkt)
1057 NVENCContext *ctx = avctx->priv_data;
1058 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1059 NV_ENC_LOCK_BITSTREAM params = { 0 };
1063 ret = av_fifo_generic_read(ctx->ready, &frame, sizeof(frame), NULL);
1067 params.version = NV_ENC_LOCK_BITSTREAM_VER;
1068 params.outputBitstream = frame->out;
1070 ret = nv->nvEncLockBitstream(ctx->nvenc_ctx, ¶ms);
1072 return nvenc_print_error(avctx, ret, "Cannot lock the bitstream");
1074 ret = ff_alloc_packet(pkt, params.bitstreamSizeInBytes);
1078 memcpy(pkt->data, params.bitstreamBufferPtr, pkt->size);
1080 ret = nv->nvEncUnlockBitstream(ctx->nvenc_ctx, frame->out);
1082 return nvenc_print_error(avctx, ret, "Cannot unlock the bitstream");
1086 ret = nvenc_set_timestamp(avctx, ¶ms, pkt);
1090 switch (params.pictureType) {
1091 case NV_ENC_PIC_TYPE_IDR:
1092 pkt->flags |= AV_PKT_FLAG_KEY;
1093 #if FF_API_CODED_FRAME
1094 FF_DISABLE_DEPRECATION_WARNINGS
1095 case NV_ENC_PIC_TYPE_INTRA_REFRESH:
1096 case NV_ENC_PIC_TYPE_I:
1097 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
1099 case NV_ENC_PIC_TYPE_P:
1100 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
1102 case NV_ENC_PIC_TYPE_B:
1103 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;
1105 case NV_ENC_PIC_TYPE_BI:
1106 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_BI;
1108 FF_ENABLE_DEPRECATION_WARNINGS
1115 static int output_ready(AVCodecContext *avctx, int flush)
1117 NVENCContext *ctx = avctx->priv_data;
1119 /* when B-frames are enabled, we wait for two initial timestamps to
1120 * calculate the first dts */
1121 if (!flush && avctx->max_b_frames > 0 &&
1122 (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
1124 return av_fifo_size(ctx->ready) > 0;
1127 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1128 const AVFrame *frame, int *got_packet)
1130 NVENCContext *ctx = avctx->priv_data;
1131 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1132 NV_ENC_PIC_PARAMS params = { 0 };
1133 NVENCFrame *nvenc_frame = NULL;
1136 params.version = NV_ENC_PIC_PARAMS_VER;
1139 nvenc_frame = get_free_frame(ctx);
1141 av_log(avctx, AV_LOG_ERROR, "No free surfaces\n");
1145 ret = nvenc_upload_frame(avctx, frame, nvenc_frame);
1149 params.inputBuffer = nvenc_frame->in;
1150 params.bufferFmt = nvenc_frame->format;
1151 params.inputWidth = frame->width;
1152 params.inputHeight = frame->height;
1153 params.outputBitstream = nvenc_frame->out;
1154 params.inputTimeStamp = frame->pts;
1156 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1157 if (frame->top_field_first)
1158 params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
1160 params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
1162 params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1165 nvenc_codec_specific_pic_params(avctx, ¶ms);
1167 ret = nvenc_enqueue_timestamp(ctx->timestamps, frame->pts);
1171 if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
1172 ctx->initial_pts[0] = frame->pts;
1173 else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
1174 ctx->initial_pts[1] = frame->pts;
1176 params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1179 enc_ret = nv->nvEncEncodePicture(ctx->nvenc_ctx, ¶ms);
1180 if (enc_ret != NV_ENC_SUCCESS &&
1181 enc_ret != NV_ENC_ERR_NEED_MORE_INPUT)
1182 return nvenc_print_error(avctx, enc_ret, "Error encoding the frame");
1185 ret = av_fifo_generic_write(ctx->pending, &nvenc_frame, sizeof(nvenc_frame), NULL);
1190 /* all the pending buffers are now ready for output */
1191 if (enc_ret == NV_ENC_SUCCESS) {
1192 while (av_fifo_size(ctx->pending) > 0) {
1193 av_fifo_generic_read(ctx->pending, &nvenc_frame, sizeof(nvenc_frame), NULL);
1194 av_fifo_generic_write(ctx->ready, &nvenc_frame, sizeof(nvenc_frame), NULL);
1198 if (output_ready(avctx, !frame)) {
1199 ret = nvenc_get_output(avctx, pkt);