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;
152 nvel->cu_init = cuInit;
153 nvel->cu_device_get_count = cuDeviceGetCount;
154 nvel->cu_device_get = cuDeviceGet;
155 nvel->cu_device_get_name = cuDeviceGetName;
156 nvel->cu_device_compute_capability = cuDeviceComputeCapability;
157 nvel->cu_ctx_create = cuCtxCreate_v2;
158 nvel->cu_ctx_pop_current = cuCtxPopCurrent_v2;
159 nvel->cu_ctx_destroy = cuCtxDestroy_v2;
161 LOAD_LIBRARY(nvel->cuda, CUDA_LIBNAME);
163 LOAD_SYMBOL(nvel->cu_init, nvel->cuda, "cuInit");
164 LOAD_SYMBOL(nvel->cu_device_get_count, nvel->cuda, "cuDeviceGetCount");
165 LOAD_SYMBOL(nvel->cu_device_get, nvel->cuda, "cuDeviceGet");
166 LOAD_SYMBOL(nvel->cu_device_get_name, nvel->cuda, "cuDeviceGetName");
167 LOAD_SYMBOL(nvel->cu_device_compute_capability, nvel->cuda,
168 "cuDeviceComputeCapability");
169 LOAD_SYMBOL(nvel->cu_ctx_create, nvel->cuda, "cuCtxCreate_v2");
170 LOAD_SYMBOL(nvel->cu_ctx_pop_current, nvel->cuda, "cuCtxPopCurrent_v2");
171 LOAD_SYMBOL(nvel->cu_ctx_destroy, nvel->cuda, "cuCtxDestroy_v2");
174 LOAD_LIBRARY(nvel->nvenc, NVENC_LIBNAME);
176 LOAD_SYMBOL(nvenc_create_instance, nvel->nvenc,
177 "NvEncodeAPICreateInstance");
179 nvel->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
181 err = nvenc_create_instance(&nvel->nvenc_funcs);
182 if (err != NV_ENC_SUCCESS)
183 return nvenc_print_error(avctx, err, "Cannot create the NVENC instance");
188 static int nvenc_open_session(AVCodecContext *avctx)
190 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
191 NVENCContext *ctx = avctx->priv_data;
192 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
195 params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
196 params.apiVersion = NVENCAPI_VERSION;
197 params.device = ctx->cu_context;
198 params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
200 ret = nv->nvEncOpenEncodeSessionEx(¶ms, &ctx->nvenc_ctx);
201 if (ret != NV_ENC_SUCCESS) {
202 ctx->nvenc_ctx = NULL;
203 return nvenc_print_error(avctx, ret, "Cannot open the NVENC Session");
209 static int nvenc_check_codec_support(AVCodecContext *avctx)
211 NVENCContext *ctx = avctx->priv_data;
212 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
213 int i, ret, count = 0;
216 ret = nv->nvEncGetEncodeGUIDCount(ctx->nvenc_ctx, &count);
218 if (ret != NV_ENC_SUCCESS || !count)
219 return AVERROR(ENOSYS);
221 guids = av_malloc(count * sizeof(GUID));
223 return AVERROR(ENOMEM);
225 ret = nv->nvEncGetEncodeGUIDs(ctx->nvenc_ctx, guids, count, &count);
226 if (ret != NV_ENC_SUCCESS) {
227 ret = AVERROR(ENOSYS);
231 ret = AVERROR(ENOSYS);
232 for (i = 0; i < count; i++) {
233 if (!memcmp(&guids[i], &ctx->params.encodeGUID, sizeof(*guids))) {
245 static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
247 NVENCContext *ctx = avctx->priv_data;
248 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
249 NV_ENC_CAPS_PARAM params = { 0 };
252 params.version = NV_ENC_CAPS_PARAM_VER;
253 params.capsToQuery = cap;
255 ret = nv->nvEncGetEncodeCaps(ctx->nvenc_ctx, ctx->params.encodeGUID, ¶ms, &val);
257 if (ret == NV_ENC_SUCCESS)
262 static int nvenc_check_capabilities(AVCodecContext *avctx)
266 ret = nvenc_check_codec_support(avctx);
268 av_log(avctx, AV_LOG_VERBOSE, "Codec not supported\n");
272 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
273 if (avctx->pix_fmt == AV_PIX_FMT_YUV444P && ret <= 0) {
274 av_log(avctx, AV_LOG_VERBOSE, "YUV444P not supported\n");
275 return AVERROR(ENOSYS);
278 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
279 if (ret < avctx->width) {
280 av_log(avctx, AV_LOG_VERBOSE, "Width %d exceeds %d\n",
282 return AVERROR(ENOSYS);
285 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
286 if (ret < avctx->height) {
287 av_log(avctx, AV_LOG_VERBOSE, "Height %d exceeds %d\n",
289 return AVERROR(ENOSYS);
292 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
293 if (ret < avctx->max_b_frames) {
294 av_log(avctx, AV_LOG_VERBOSE, "Max b-frames %d exceed %d\n",
295 avctx->max_b_frames, ret);
297 return AVERROR(ENOSYS);
303 static int nvenc_check_device(AVCodecContext *avctx, int idx)
305 NVENCContext *ctx = avctx->priv_data;
306 NVENCLibraryContext *nvel = &ctx->nvel;
307 char name[128] = { 0 };
308 int major, minor, ret;
311 int loglevel = AV_LOG_VERBOSE;
313 if (ctx->device == LIST_DEVICES)
314 loglevel = AV_LOG_INFO;
316 ret = nvel->cu_device_get(&cu_device, idx);
317 if (ret != CUDA_SUCCESS) {
318 av_log(avctx, AV_LOG_ERROR,
319 "Cannot access the CUDA device %d\n",
324 ret = nvel->cu_device_get_name(name, sizeof(name), cu_device);
325 if (ret != CUDA_SUCCESS)
328 ret = nvel->cu_device_compute_capability(&major, &minor, cu_device);
329 if (ret != CUDA_SUCCESS)
332 av_log(avctx, loglevel, "Device %d [%s] ", cu_device, name);
334 if (((major << 4) | minor) < NVENC_CAP)
337 ret = nvel->cu_ctx_create(&ctx->cu_context, 0, cu_device);
338 if (ret != CUDA_SUCCESS)
341 ret = nvel->cu_ctx_pop_current(&dummy);
342 if (ret != CUDA_SUCCESS)
345 if ((ret = nvenc_open_session(avctx)) < 0)
348 if ((ret = nvenc_check_capabilities(avctx)) < 0)
351 av_log(avctx, loglevel, "supports NVENC\n");
353 if (ctx->device == cu_device || ctx->device == ANY_DEVICE)
357 nvel->nvenc_funcs.nvEncDestroyEncoder(ctx->nvenc_ctx);
358 ctx->nvenc_ctx = NULL;
361 nvel->cu_ctx_destroy(ctx->cu_context);
362 ctx->cu_context = NULL;
366 av_log(avctx, loglevel, "does not support NVENC (major %d minor %d)\n",
369 return AVERROR(ENOSYS);
372 static int nvenc_setup_device(AVCodecContext *avctx)
374 NVENCContext *ctx = avctx->priv_data;
375 NVENCLibraryContext *nvel = &ctx->nvel;
376 int i, nb_devices = 0;
378 if ((nvel->cu_init(0)) != CUDA_SUCCESS) {
379 av_log(avctx, AV_LOG_ERROR,
380 "Cannot init CUDA\n");
381 return AVERROR_UNKNOWN;
384 if ((nvel->cu_device_get_count(&nb_devices)) != CUDA_SUCCESS) {
385 av_log(avctx, AV_LOG_ERROR,
386 "Cannot enumerate the CUDA devices\n");
387 return AVERROR_UNKNOWN;
390 switch (avctx->codec->id) {
391 case AV_CODEC_ID_H264:
392 ctx->params.encodeGUID = NV_ENC_CODEC_H264_GUID;
394 case AV_CODEC_ID_HEVC:
395 ctx->params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
401 for (i = 0; i < nb_devices; ++i) {
402 if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
406 if (ctx->device == LIST_DEVICES)
409 return AVERROR(ENOSYS);
412 typedef struct GUIDTuple {
417 static int nvec_map_preset(NVENCContext *ctx)
419 GUIDTuple presets[] = {
420 { NV_ENC_PRESET_DEFAULT_GUID },
421 { NV_ENC_PRESET_HP_GUID },
422 { NV_ENC_PRESET_HQ_GUID },
423 { NV_ENC_PRESET_BD_GUID },
424 { NV_ENC_PRESET_LOW_LATENCY_DEFAULT_GUID, NVENC_LOWLATENCY },
425 { NV_ENC_PRESET_LOW_LATENCY_HP_GUID, NVENC_LOWLATENCY },
426 { NV_ENC_PRESET_LOW_LATENCY_HQ_GUID, NVENC_LOWLATENCY },
427 { NV_ENC_PRESET_LOSSLESS_DEFAULT_GUID, NVENC_LOSSLESS },
428 { NV_ENC_PRESET_LOSSLESS_HP_GUID, NVENC_LOSSLESS },
432 GUIDTuple *t = &presets[ctx->preset];
434 ctx->params.presetGUID = t->guid;
435 ctx->flags = t->flags;
437 return AVERROR(EINVAL);
440 static void set_constqp(AVCodecContext *avctx, NV_ENC_RC_PARAMS *rc)
442 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
443 rc->constQP.qpInterB = avctx->global_quality;
444 rc->constQP.qpInterP = avctx->global_quality;
445 rc->constQP.qpIntra = avctx->global_quality;
448 static void set_vbr(AVCodecContext *avctx, NV_ENC_RC_PARAMS *rc)
450 if (avctx->qmin >= 0) {
452 rc->minQP.qpInterB = avctx->qmin;
453 rc->minQP.qpInterP = avctx->qmin;
454 rc->minQP.qpIntra = avctx->qmin;
457 if (avctx->qmax >= 0) {
459 rc->maxQP.qpInterB = avctx->qmax;
460 rc->maxQP.qpInterP = avctx->qmax;
461 rc->maxQP.qpIntra = avctx->qmax;
465 static void nvenc_override_rate_control(AVCodecContext *avctx,
466 NV_ENC_RC_PARAMS *rc)
468 NVENCContext *ctx = avctx->priv_data;
471 case NV_ENC_PARAMS_RC_CONSTQP:
472 if (avctx->global_quality < 0) {
473 av_log(avctx, AV_LOG_WARNING,
474 "The constant quality rate-control requires "
475 "the 'global_quality' option set.\n");
478 set_constqp(avctx, rc);
480 case NV_ENC_PARAMS_RC_2_PASS_VBR:
481 case NV_ENC_PARAMS_RC_VBR:
482 if (avctx->qmin < 0 && avctx->qmax < 0) {
483 av_log(avctx, AV_LOG_WARNING,
484 "The variable bitrate rate-control requires "
485 "the 'qmin' and/or 'qmax' option set.\n");
488 case NV_ENC_PARAMS_RC_VBR_MINQP:
489 if (avctx->qmin < 0) {
490 av_log(avctx, AV_LOG_WARNING,
491 "The variable bitrate rate-control requires "
492 "the 'qmin' option set.\n");
497 case NV_ENC_PARAMS_RC_CBR:
499 case NV_ENC_PARAMS_RC_2_PASS_QUALITY:
500 case NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP:
501 if (!(ctx->flags & NVENC_LOWLATENCY)) {
502 av_log(avctx, AV_LOG_WARNING,
503 "The multipass rate-control requires "
504 "a low-latency preset.\n");
509 rc->rateControlMode = ctx->rc;
512 static void nvenc_setup_rate_control(AVCodecContext *avctx)
514 NVENCContext *ctx = avctx->priv_data;
515 NV_ENC_RC_PARAMS *rc = &ctx->config.rcParams;
517 if (avctx->bit_rate > 0)
518 rc->averageBitRate = avctx->bit_rate;
520 if (avctx->rc_max_rate > 0)
521 rc->maxBitRate = avctx->rc_max_rate;
524 nvenc_override_rate_control(avctx, rc);
525 } else if (avctx->global_quality > 0) {
526 set_constqp(avctx, rc);
527 } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
528 rc->rateControlMode = NV_ENC_PARAMS_RC_VBR;
532 if (avctx->rc_buffer_size > 0)
533 rc->vbvBufferSize = avctx->rc_buffer_size;
535 if (rc->averageBitRate > 0)
536 avctx->bit_rate = rc->averageBitRate;
539 static int nvenc_setup_h264_config(AVCodecContext *avctx)
541 NVENCContext *ctx = avctx->priv_data;
542 NV_ENC_CONFIG *cc = &ctx->config;
543 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
544 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
546 vui->colourDescriptionPresentFlag = 1;
547 vui->videoSignalTypePresentFlag = 1;
549 vui->colourMatrix = avctx->colorspace;
550 vui->colourPrimaries = avctx->color_primaries;
551 vui->transferCharacteristics = avctx->color_trc;
553 vui->videoFullRangeFlag = avctx->color_range == AVCOL_RANGE_JPEG;
555 h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
556 h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
558 h264->maxNumRefFrames = avctx->refs;
559 h264->idrPeriod = cc->gopLength;
562 avctx->profile = ctx->profile;
564 if (avctx->pix_fmt == AV_PIX_FMT_YUV444P)
565 h264->chromaFormatIDC = 3;
567 h264->chromaFormatIDC = 1;
569 switch (ctx->profile) {
570 case NV_ENC_H264_PROFILE_BASELINE:
571 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
573 case NV_ENC_H264_PROFILE_MAIN:
574 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
576 case NV_ENC_H264_PROFILE_HIGH:
577 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
579 case NV_ENC_H264_PROFILE_HIGH_444:
580 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
582 case NV_ENC_H264_PROFILE_CONSTRAINED_HIGH:
583 cc->profileGUID = NV_ENC_H264_PROFILE_CONSTRAINED_HIGH_GUID;
587 h264->level = ctx->level;
592 static int nvenc_setup_hevc_config(AVCodecContext *avctx)
594 NVENCContext *ctx = avctx->priv_data;
595 NV_ENC_CONFIG *cc = &ctx->config;
596 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
598 hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
599 hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
601 hevc->maxNumRefFramesInDPB = avctx->refs;
602 hevc->idrPeriod = cc->gopLength;
604 /* No other profile is supported in the current SDK version 5 */
605 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
606 avctx->profile = FF_PROFILE_HEVC_MAIN;
609 hevc->level = ctx->level;
611 hevc->level = NV_ENC_LEVEL_AUTOSELECT;
615 hevc->tier = ctx->tier;
620 static int nvenc_setup_codec_config(AVCodecContext *avctx)
622 switch (avctx->codec->id) {
623 case AV_CODEC_ID_H264:
624 return nvenc_setup_h264_config(avctx);
625 case AV_CODEC_ID_HEVC:
626 return nvenc_setup_hevc_config(avctx);
631 static int nvenc_setup_encoder(AVCodecContext *avctx)
633 NVENCContext *ctx = avctx->priv_data;
634 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
635 NV_ENC_PRESET_CONFIG preset_cfg = { 0 };
636 AVCPBProperties *cpb_props;
639 ctx->params.version = NV_ENC_INITIALIZE_PARAMS_VER;
641 ctx->params.encodeHeight = avctx->height;
642 ctx->params.encodeWidth = avctx->width;
644 if (avctx->sample_aspect_ratio.num &&
645 avctx->sample_aspect_ratio.den &&
646 (avctx->sample_aspect_ratio.num != 1 ||
647 avctx->sample_aspect_ratio.den != 1)) {
648 av_reduce(&ctx->params.darWidth,
649 &ctx->params.darHeight,
650 avctx->width * avctx->sample_aspect_ratio.num,
651 avctx->height * avctx->sample_aspect_ratio.den,
654 ctx->params.darHeight = avctx->height;
655 ctx->params.darWidth = avctx->width;
658 ctx->params.frameRateNum = avctx->time_base.den;
659 ctx->params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
661 ctx->params.enableEncodeAsync = 0;
662 ctx->params.enablePTD = 1;
664 ctx->params.encodeConfig = &ctx->config;
666 nvec_map_preset(ctx);
668 preset_cfg.version = NV_ENC_PRESET_CONFIG_VER;
669 preset_cfg.presetCfg.version = NV_ENC_CONFIG_VER;
671 ret = nv->nvEncGetEncodePresetConfig(ctx->nvenc_ctx,
672 ctx->params.encodeGUID,
673 ctx->params.presetGUID,
675 if (ret != NV_ENC_SUCCESS)
676 return nvenc_print_error(avctx, ret, "Cannot get the preset configuration");
678 memcpy(&ctx->config, &preset_cfg.presetCfg, sizeof(ctx->config));
680 ctx->config.version = NV_ENC_CONFIG_VER;
682 if (avctx->gop_size > 0) {
683 if (avctx->max_b_frames > 0) {
687 * 3 two B frames, and so on. */
688 ctx->config.frameIntervalP = avctx->max_b_frames + 1;
689 } else if (avctx->max_b_frames == 0) {
690 ctx->config.frameIntervalP = 1;
692 ctx->config.gopLength = avctx->gop_size;
693 } else if (avctx->gop_size == 0) {
694 ctx->config.frameIntervalP = 0;
695 ctx->config.gopLength = 1;
698 if (ctx->config.frameIntervalP > 1)
699 avctx->max_b_frames = ctx->config.frameIntervalP - 1;
701 ctx->initial_pts[0] = AV_NOPTS_VALUE;
702 ctx->initial_pts[1] = AV_NOPTS_VALUE;
704 nvenc_setup_rate_control(avctx);
706 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
707 ctx->config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
709 ctx->config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
712 if ((ret = nvenc_setup_codec_config(avctx)) < 0)
715 ret = nv->nvEncInitializeEncoder(ctx->nvenc_ctx, &ctx->params);
716 if (ret != NV_ENC_SUCCESS)
717 return nvenc_print_error(avctx, ret, "Cannot initialize the decoder");
719 cpb_props = ff_add_cpb_side_data(avctx);
721 return AVERROR(ENOMEM);
722 cpb_props->max_bitrate = avctx->rc_max_rate;
723 cpb_props->min_bitrate = avctx->rc_min_rate;
724 cpb_props->avg_bitrate = avctx->bit_rate;
725 cpb_props->buffer_size = avctx->rc_buffer_size;
730 static int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
732 NVENCContext *ctx = avctx->priv_data;
733 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
735 NV_ENC_CREATE_INPUT_BUFFER in_buffer = { 0 };
736 NV_ENC_CREATE_BITSTREAM_BUFFER out_buffer = { 0 };
738 in_buffer.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
739 out_buffer.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
741 in_buffer.width = avctx->width;
742 in_buffer.height = avctx->height;
744 in_buffer.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED;
746 switch (avctx->pix_fmt) {
747 case AV_PIX_FMT_YUV420P:
748 in_buffer.bufferFmt = NV_ENC_BUFFER_FORMAT_YV12_PL;
750 case AV_PIX_FMT_NV12:
751 in_buffer.bufferFmt = NV_ENC_BUFFER_FORMAT_NV12_PL;
753 case AV_PIX_FMT_YUV444P:
754 in_buffer.bufferFmt = NV_ENC_BUFFER_FORMAT_YUV444_PL;
760 ret = nv->nvEncCreateInputBuffer(ctx->nvenc_ctx, &in_buffer);
761 if (ret != NV_ENC_SUCCESS)
762 return nvenc_print_error(avctx, ret, "CreateInputBuffer failed");
764 ctx->frames[idx].in = in_buffer.inputBuffer;
765 ctx->frames[idx].format = in_buffer.bufferFmt;
767 /* 1MB is large enough to hold most output frames.
768 * NVENC increases this automaticaly if it's not enough. */
769 out_buffer.size = BITSTREAM_BUFFER_SIZE;
771 out_buffer.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED;
773 ret = nv->nvEncCreateBitstreamBuffer(ctx->nvenc_ctx, &out_buffer);
774 if (ret != NV_ENC_SUCCESS)
775 return nvenc_print_error(avctx, ret, "CreateBitstreamBuffer failed");
777 ctx->frames[idx].out = out_buffer.bitstreamBuffer;
782 static int nvenc_setup_surfaces(AVCodecContext *avctx)
784 NVENCContext *ctx = avctx->priv_data;
787 ctx->nb_surfaces = FFMAX(4 + avctx->max_b_frames,
790 ctx->frames = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->frames));
792 return AVERROR(ENOMEM);
794 ctx->timestamps = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
795 if (!ctx->timestamps)
796 return AVERROR(ENOMEM);
797 ctx->pending = av_fifo_alloc(ctx->nb_surfaces * sizeof(*ctx->frames));
799 return AVERROR(ENOMEM);
800 ctx->ready = av_fifo_alloc(ctx->nb_surfaces * sizeof(*ctx->frames));
802 return AVERROR(ENOMEM);
804 for (i = 0; i < ctx->nb_surfaces; i++) {
805 if ((ret = nvenc_alloc_surface(avctx, i)) < 0)
812 #define EXTRADATA_SIZE 512
814 static int nvenc_setup_extradata(AVCodecContext *avctx)
816 NVENCContext *ctx = avctx->priv_data;
817 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
818 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
821 avctx->extradata = av_mallocz(EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
822 if (!avctx->extradata)
823 return AVERROR(ENOMEM);
825 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
826 payload.spsppsBuffer = avctx->extradata;
827 payload.inBufferSize = EXTRADATA_SIZE;
828 payload.outSPSPPSPayloadSize = &avctx->extradata_size;
830 ret = nv->nvEncGetSequenceParams(ctx->nvenc_ctx, &payload);
831 if (ret != NV_ENC_SUCCESS)
832 return nvenc_print_error(avctx, ret, "Cannot get the extradata");
837 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
839 NVENCContext *ctx = avctx->priv_data;
840 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
843 /* the encoder has to be flushed before it can be closed */
844 if (ctx->nvenc_ctx) {
845 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
846 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
848 nv->nvEncEncodePicture(ctx->nvenc_ctx, ¶ms);
851 av_fifo_free(ctx->timestamps);
852 av_fifo_free(ctx->pending);
853 av_fifo_free(ctx->ready);
856 for (i = 0; i < ctx->nb_surfaces; ++i) {
857 nv->nvEncDestroyInputBuffer(ctx->nvenc_ctx, ctx->frames[i].in);
858 nv->nvEncDestroyBitstreamBuffer(ctx->nvenc_ctx, ctx->frames[i].out);
862 av_freep(&ctx->frames);
865 nv->nvEncDestroyEncoder(ctx->nvenc_ctx);
868 ctx->nvel.cu_ctx_destroy(ctx->cu_context);
871 dlclose(ctx->nvel.nvenc);
875 dlclose(ctx->nvel.cuda);
881 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
885 if ((ret = nvenc_load_libraries(avctx)) < 0)
888 if ((ret = nvenc_setup_device(avctx)) < 0)
891 if ((ret = nvenc_setup_encoder(avctx)) < 0)
894 if ((ret = nvenc_setup_surfaces(avctx)) < 0)
897 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
898 if ((ret = nvenc_setup_extradata(avctx)) < 0)
905 static NVENCFrame *get_free_frame(NVENCContext *ctx)
909 for (i = 0; i < ctx->nb_surfaces; i++) {
910 if (!ctx->frames[i].locked) {
911 ctx->frames[i].locked = 1;
912 return &ctx->frames[i];
919 static int nvenc_copy_frame(NV_ENC_LOCK_INPUT_BUFFER *in, const AVFrame *frame)
921 uint8_t *buf = in->bufferDataPtr;
922 int off = frame->height * in->pitch;
924 switch (frame->format) {
925 case AV_PIX_FMT_YUV420P:
926 av_image_copy_plane(buf, in->pitch,
927 frame->data[0], frame->linesize[0],
928 frame->width, frame->height);
931 av_image_copy_plane(buf, in->pitch >> 1,
932 frame->data[2], frame->linesize[2],
933 frame->width >> 1, frame->height >> 1);
937 av_image_copy_plane(buf, in->pitch >> 1,
938 frame->data[1], frame->linesize[1],
939 frame->width >> 1, frame->height >> 1);
941 case AV_PIX_FMT_NV12:
942 av_image_copy_plane(buf, in->pitch,
943 frame->data[0], frame->linesize[0],
944 frame->width, frame->height);
947 av_image_copy_plane(buf, in->pitch,
948 frame->data[1], frame->linesize[1],
949 frame->width, frame->height >> 1);
951 case AV_PIX_FMT_YUV444P:
952 av_image_copy_plane(buf, in->pitch,
953 frame->data[0], frame->linesize[0],
954 frame->width, frame->height);
957 av_image_copy_plane(buf, in->pitch,
958 frame->data[1], frame->linesize[1],
959 frame->width, frame->height);
962 av_image_copy_plane(buf, in->pitch,
963 frame->data[2], frame->linesize[2],
964 frame->width, frame->height);
973 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
974 NVENCFrame *nvenc_frame)
976 NVENCContext *ctx = avctx->priv_data;
977 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
978 NV_ENC_LOCK_INPUT_BUFFER params = { 0 };
981 params.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
982 params.inputBuffer = nvenc_frame->in;
985 ret = nv->nvEncLockInputBuffer(ctx->nvenc_ctx, ¶ms);
986 if (ret != NV_ENC_SUCCESS)
987 return nvenc_print_error(avctx, ret, "Cannot lock the buffer");
989 ret = nvenc_copy_frame(¶ms, frame);
993 ret = nv->nvEncUnlockInputBuffer(ctx->nvenc_ctx, nvenc_frame->in);
994 if (ret != NV_ENC_SUCCESS)
995 return nvenc_print_error(avctx, ret, "Cannot unlock the buffer");
1000 nv->nvEncUnlockInputBuffer(ctx->nvenc_ctx, nvenc_frame->in);
1005 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1006 NV_ENC_PIC_PARAMS *params)
1008 NVENCContext *ctx = avctx->priv_data;
1010 switch (avctx->codec->id) {
1011 case AV_CODEC_ID_H264:
1012 params->codecPicParams.h264PicParams.sliceMode =
1013 ctx->config.encodeCodecConfig.h264Config.sliceMode;
1014 params->codecPicParams.h264PicParams.sliceModeData =
1015 ctx->config.encodeCodecConfig.h264Config.sliceModeData;
1017 case AV_CODEC_ID_HEVC:
1018 params->codecPicParams.hevcPicParams.sliceMode =
1019 ctx->config.encodeCodecConfig.hevcConfig.sliceMode;
1020 params->codecPicParams.hevcPicParams.sliceModeData =
1021 ctx->config.encodeCodecConfig.hevcConfig.sliceModeData;
1026 static inline int nvenc_enqueue_timestamp(AVFifoBuffer *f, int64_t pts)
1028 return av_fifo_generic_write(f, &pts, sizeof(pts), NULL);
1031 static inline int nvenc_dequeue_timestamp(AVFifoBuffer *f, int64_t *pts)
1033 return av_fifo_generic_read(f, pts, sizeof(*pts), NULL);
1036 static int nvenc_set_timestamp(AVCodecContext *avctx,
1037 NV_ENC_LOCK_BITSTREAM *params,
1040 NVENCContext *ctx = avctx->priv_data;
1042 pkt->pts = params->outputTimeStamp;
1043 pkt->duration = params->outputDuration;
1045 /* generate the first dts by linearly extrapolating the
1046 * first two pts values to the past */
1047 if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
1048 ctx->initial_pts[1] != AV_NOPTS_VALUE) {
1049 int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
1052 if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
1053 (ts0 > 0 && ts1 < INT64_MIN + ts0))
1054 return AVERROR(ERANGE);
1057 if ((delta < 0 && ts0 > INT64_MAX + delta) ||
1058 (delta > 0 && ts0 < INT64_MIN + delta))
1059 return AVERROR(ERANGE);
1060 pkt->dts = ts0 - delta;
1062 ctx->first_packet_output = 1;
1065 return nvenc_dequeue_timestamp(ctx->timestamps, &pkt->dts);
1068 static int nvenc_get_output(AVCodecContext *avctx, AVPacket *pkt)
1070 NVENCContext *ctx = avctx->priv_data;
1071 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1072 NV_ENC_LOCK_BITSTREAM params = { 0 };
1076 ret = av_fifo_generic_read(ctx->ready, &frame, sizeof(frame), NULL);
1080 params.version = NV_ENC_LOCK_BITSTREAM_VER;
1081 params.outputBitstream = frame->out;
1083 ret = nv->nvEncLockBitstream(ctx->nvenc_ctx, ¶ms);
1085 return nvenc_print_error(avctx, ret, "Cannot lock the bitstream");
1087 ret = ff_alloc_packet(pkt, params.bitstreamSizeInBytes);
1091 memcpy(pkt->data, params.bitstreamBufferPtr, pkt->size);
1093 ret = nv->nvEncUnlockBitstream(ctx->nvenc_ctx, frame->out);
1095 return nvenc_print_error(avctx, ret, "Cannot unlock the bitstream");
1099 ret = nvenc_set_timestamp(avctx, ¶ms, pkt);
1103 switch (params.pictureType) {
1104 case NV_ENC_PIC_TYPE_IDR:
1105 pkt->flags |= AV_PKT_FLAG_KEY;
1106 #if FF_API_CODED_FRAME
1107 FF_DISABLE_DEPRECATION_WARNINGS
1108 case NV_ENC_PIC_TYPE_INTRA_REFRESH:
1109 case NV_ENC_PIC_TYPE_I:
1110 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
1112 case NV_ENC_PIC_TYPE_P:
1113 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
1115 case NV_ENC_PIC_TYPE_B:
1116 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;
1118 case NV_ENC_PIC_TYPE_BI:
1119 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_BI;
1121 FF_ENABLE_DEPRECATION_WARNINGS
1128 static int output_ready(AVCodecContext *avctx, int flush)
1130 NVENCContext *ctx = avctx->priv_data;
1132 /* when B-frames are enabled, we wait for two initial timestamps to
1133 * calculate the first dts */
1134 if (!flush && avctx->max_b_frames > 0 &&
1135 (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
1137 return av_fifo_size(ctx->ready) > 0;
1140 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1141 const AVFrame *frame, int *got_packet)
1143 NVENCContext *ctx = avctx->priv_data;
1144 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1145 NV_ENC_PIC_PARAMS params = { 0 };
1146 NVENCFrame *nvenc_frame = NULL;
1149 params.version = NV_ENC_PIC_PARAMS_VER;
1152 nvenc_frame = get_free_frame(ctx);
1154 av_log(avctx, AV_LOG_ERROR, "No free surfaces\n");
1158 ret = nvenc_upload_frame(avctx, frame, nvenc_frame);
1162 params.inputBuffer = nvenc_frame->in;
1163 params.bufferFmt = nvenc_frame->format;
1164 params.inputWidth = frame->width;
1165 params.inputHeight = frame->height;
1166 params.outputBitstream = nvenc_frame->out;
1167 params.inputTimeStamp = frame->pts;
1169 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1170 if (frame->top_field_first)
1171 params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
1173 params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
1175 params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1178 nvenc_codec_specific_pic_params(avctx, ¶ms);
1180 ret = nvenc_enqueue_timestamp(ctx->timestamps, frame->pts);
1184 if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
1185 ctx->initial_pts[0] = frame->pts;
1186 else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
1187 ctx->initial_pts[1] = frame->pts;
1189 params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1192 enc_ret = nv->nvEncEncodePicture(ctx->nvenc_ctx, ¶ms);
1193 if (enc_ret != NV_ENC_SUCCESS &&
1194 enc_ret != NV_ENC_ERR_NEED_MORE_INPUT)
1195 return nvenc_print_error(avctx, enc_ret, "Error encoding the frame");
1198 ret = av_fifo_generic_write(ctx->pending, &nvenc_frame, sizeof(nvenc_frame), NULL);
1203 /* all the pending buffers are now ready for output */
1204 if (enc_ret == NV_ENC_SUCCESS) {
1205 while (av_fifo_size(ctx->pending) > 0) {
1206 av_fifo_generic_read(ctx->pending, &nvenc_frame, sizeof(nvenc_frame), NULL);
1207 av_fifo_generic_write(ctx->ready, &nvenc_frame, sizeof(nvenc_frame), NULL);
1211 if (output_ready(avctx, !frame)) {
1212 ret = nvenc_get_output(avctx, pkt);