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/hwcontext.h"
51 #include "libavutil/hwcontext_cuda.h"
52 #include "libavutil/imgutils.h"
53 #include "libavutil/mem.h"
58 #define NVENC_CAP 0x30
59 #define BITSTREAM_BUFFER_SIZE 1024 * 1024
61 #define LOAD_LIBRARY(l, path) \
63 if (!((l) = dlopen(path, RTLD_LAZY))) { \
64 av_log(avctx, AV_LOG_ERROR, \
67 return AVERROR_UNKNOWN; \
71 #define LOAD_SYMBOL(fun, lib, symbol) \
73 if (!((fun) = dlsym(lib, symbol))) { \
74 av_log(avctx, AV_LOG_ERROR, \
77 return AVERROR_UNKNOWN; \
81 const enum AVPixelFormat ff_nvenc_pix_fmts[] = {
94 { NV_ENC_SUCCESS, 0, "success" },
95 { NV_ENC_ERR_NO_ENCODE_DEVICE, AVERROR(ENOENT), "no encode device" },
96 { NV_ENC_ERR_UNSUPPORTED_DEVICE, AVERROR(ENOSYS), "unsupported device" },
97 { NV_ENC_ERR_INVALID_ENCODERDEVICE, AVERROR(EINVAL), "invalid encoder device" },
98 { NV_ENC_ERR_INVALID_DEVICE, AVERROR(EINVAL), "invalid device" },
99 { NV_ENC_ERR_DEVICE_NOT_EXIST, AVERROR(EIO), "device does not exist" },
100 { NV_ENC_ERR_INVALID_PTR, AVERROR(EFAULT), "invalid ptr" },
101 { NV_ENC_ERR_INVALID_EVENT, AVERROR(EINVAL), "invalid event" },
102 { NV_ENC_ERR_INVALID_PARAM, AVERROR(EINVAL), "invalid param" },
103 { NV_ENC_ERR_INVALID_CALL, AVERROR(EINVAL), "invalid call" },
104 { NV_ENC_ERR_OUT_OF_MEMORY, AVERROR(ENOMEM), "out of memory" },
105 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED, AVERROR(EINVAL), "encoder not initialized" },
106 { NV_ENC_ERR_UNSUPPORTED_PARAM, AVERROR(ENOSYS), "unsupported param" },
107 { NV_ENC_ERR_LOCK_BUSY, AVERROR(EAGAIN), "lock busy" },
108 { NV_ENC_ERR_NOT_ENOUGH_BUFFER, AVERROR(ENOBUFS), "not enough buffer" },
109 { NV_ENC_ERR_INVALID_VERSION, AVERROR(EINVAL), "invalid version" },
110 { NV_ENC_ERR_MAP_FAILED, AVERROR(EIO), "map failed" },
111 { NV_ENC_ERR_NEED_MORE_INPUT, AVERROR(EAGAIN), "need more input" },
112 { NV_ENC_ERR_ENCODER_BUSY, AVERROR(EAGAIN), "encoder busy" },
113 { NV_ENC_ERR_EVENT_NOT_REGISTERD, AVERROR(EBADF), "event not registered" },
114 { NV_ENC_ERR_GENERIC, AVERROR_UNKNOWN, "generic error" },
115 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY, AVERROR(EINVAL), "incompatible client key" },
116 { NV_ENC_ERR_UNIMPLEMENTED, AVERROR(ENOSYS), "unimplemented" },
117 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO), "resource register failed" },
118 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED, AVERROR(EBADF), "resource not registered" },
119 { NV_ENC_ERR_RESOURCE_NOT_MAPPED, AVERROR(EBADF), "resource not mapped" },
122 static int nvenc_map_error(NVENCSTATUS err, const char **desc)
125 for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
126 if (nvenc_errors[i].nverr == err) {
128 *desc = nvenc_errors[i].desc;
129 return nvenc_errors[i].averr;
133 *desc = "unknown error";
134 return AVERROR_UNKNOWN;
137 static int nvenc_print_error(void *log_ctx, NVENCSTATUS err,
138 const char *error_string)
142 ret = nvenc_map_error(err, &desc);
143 av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
147 static av_cold int nvenc_load_libraries(AVCodecContext *avctx)
149 NVENCContext *ctx = avctx->priv_data;
150 NVENCLibraryContext *nvel = &ctx->nvel;
151 PNVENCODEAPICREATEINSTANCE nvenc_create_instance;
155 nvel->cu_init = cuInit;
156 nvel->cu_device_get_count = cuDeviceGetCount;
157 nvel->cu_device_get = cuDeviceGet;
158 nvel->cu_device_get_name = cuDeviceGetName;
159 nvel->cu_device_compute_capability = cuDeviceComputeCapability;
160 nvel->cu_ctx_create = cuCtxCreate_v2;
161 nvel->cu_ctx_pop_current = cuCtxPopCurrent_v2;
162 nvel->cu_ctx_destroy = cuCtxDestroy_v2;
164 LOAD_LIBRARY(nvel->cuda, CUDA_LIBNAME);
166 LOAD_SYMBOL(nvel->cu_init, nvel->cuda, "cuInit");
167 LOAD_SYMBOL(nvel->cu_device_get_count, nvel->cuda, "cuDeviceGetCount");
168 LOAD_SYMBOL(nvel->cu_device_get, nvel->cuda, "cuDeviceGet");
169 LOAD_SYMBOL(nvel->cu_device_get_name, nvel->cuda, "cuDeviceGetName");
170 LOAD_SYMBOL(nvel->cu_device_compute_capability, nvel->cuda,
171 "cuDeviceComputeCapability");
172 LOAD_SYMBOL(nvel->cu_ctx_create, nvel->cuda, "cuCtxCreate_v2");
173 LOAD_SYMBOL(nvel->cu_ctx_pop_current, nvel->cuda, "cuCtxPopCurrent_v2");
174 LOAD_SYMBOL(nvel->cu_ctx_destroy, nvel->cuda, "cuCtxDestroy_v2");
177 LOAD_LIBRARY(nvel->nvenc, NVENC_LIBNAME);
179 LOAD_SYMBOL(nvenc_create_instance, nvel->nvenc,
180 "NvEncodeAPICreateInstance");
182 nvel->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
184 err = nvenc_create_instance(&nvel->nvenc_funcs);
185 if (err != NV_ENC_SUCCESS)
186 return nvenc_print_error(avctx, err, "Cannot create the NVENC instance");
191 static int nvenc_open_session(AVCodecContext *avctx)
193 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
194 NVENCContext *ctx = avctx->priv_data;
195 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
198 params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
199 params.apiVersion = NVENCAPI_VERSION;
200 params.device = ctx->cu_context;
201 params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
203 ret = nv->nvEncOpenEncodeSessionEx(¶ms, &ctx->nvenc_ctx);
204 if (ret != NV_ENC_SUCCESS) {
205 ctx->nvenc_ctx = NULL;
206 return nvenc_print_error(avctx, ret, "Cannot open the NVENC Session");
212 static int nvenc_check_codec_support(AVCodecContext *avctx)
214 NVENCContext *ctx = avctx->priv_data;
215 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
216 int i, ret, count = 0;
219 ret = nv->nvEncGetEncodeGUIDCount(ctx->nvenc_ctx, &count);
221 if (ret != NV_ENC_SUCCESS || !count)
222 return AVERROR(ENOSYS);
224 guids = av_malloc(count * sizeof(GUID));
226 return AVERROR(ENOMEM);
228 ret = nv->nvEncGetEncodeGUIDs(ctx->nvenc_ctx, guids, count, &count);
229 if (ret != NV_ENC_SUCCESS) {
230 ret = AVERROR(ENOSYS);
234 ret = AVERROR(ENOSYS);
235 for (i = 0; i < count; i++) {
236 if (!memcmp(&guids[i], &ctx->params.encodeGUID, sizeof(*guids))) {
248 static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
250 NVENCContext *ctx = avctx->priv_data;
251 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
252 NV_ENC_CAPS_PARAM params = { 0 };
255 params.version = NV_ENC_CAPS_PARAM_VER;
256 params.capsToQuery = cap;
258 ret = nv->nvEncGetEncodeCaps(ctx->nvenc_ctx, ctx->params.encodeGUID, ¶ms, &val);
260 if (ret == NV_ENC_SUCCESS)
265 static int nvenc_check_capabilities(AVCodecContext *avctx)
267 NVENCContext *ctx = avctx->priv_data;
270 ret = nvenc_check_codec_support(avctx);
272 av_log(avctx, AV_LOG_VERBOSE, "Codec not supported\n");
276 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
277 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P && ret <= 0) {
278 av_log(avctx, AV_LOG_VERBOSE, "YUV444P not supported\n");
279 return AVERROR(ENOSYS);
282 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
283 if (ret < avctx->width) {
284 av_log(avctx, AV_LOG_VERBOSE, "Width %d exceeds %d\n",
286 return AVERROR(ENOSYS);
289 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
290 if (ret < avctx->height) {
291 av_log(avctx, AV_LOG_VERBOSE, "Height %d exceeds %d\n",
293 return AVERROR(ENOSYS);
296 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
297 if (ret < avctx->max_b_frames) {
298 av_log(avctx, AV_LOG_VERBOSE, "Max B-frames %d exceed %d\n",
299 avctx->max_b_frames, ret);
301 return AVERROR(ENOSYS);
307 static int nvenc_check_device(AVCodecContext *avctx, int idx)
309 NVENCContext *ctx = avctx->priv_data;
310 NVENCLibraryContext *nvel = &ctx->nvel;
311 char name[128] = { 0 };
312 int major, minor, ret;
315 int loglevel = AV_LOG_VERBOSE;
317 if (ctx->device == LIST_DEVICES)
318 loglevel = AV_LOG_INFO;
320 ret = nvel->cu_device_get(&cu_device, idx);
321 if (ret != CUDA_SUCCESS) {
322 av_log(avctx, AV_LOG_ERROR,
323 "Cannot access the CUDA device %d\n",
328 ret = nvel->cu_device_get_name(name, sizeof(name), cu_device);
329 if (ret != CUDA_SUCCESS)
332 ret = nvel->cu_device_compute_capability(&major, &minor, cu_device);
333 if (ret != CUDA_SUCCESS)
336 av_log(avctx, loglevel, "Device %d [%s] ", cu_device, name);
338 if (((major << 4) | minor) < NVENC_CAP)
341 ret = nvel->cu_ctx_create(&ctx->cu_context_internal, 0, cu_device);
342 if (ret != CUDA_SUCCESS)
345 ctx->cu_context = ctx->cu_context_internal;
347 ret = nvel->cu_ctx_pop_current(&dummy);
348 if (ret != CUDA_SUCCESS)
351 if ((ret = nvenc_open_session(avctx)) < 0)
354 if ((ret = nvenc_check_capabilities(avctx)) < 0)
357 av_log(avctx, loglevel, "supports NVENC\n");
359 if (ctx->device == cu_device || ctx->device == ANY_DEVICE)
363 nvel->nvenc_funcs.nvEncDestroyEncoder(ctx->nvenc_ctx);
364 ctx->nvenc_ctx = NULL;
367 nvel->cu_ctx_destroy(ctx->cu_context_internal);
368 ctx->cu_context_internal = NULL;
372 av_log(avctx, loglevel, "does not support NVENC (major %d minor %d)\n",
375 return AVERROR(ENOSYS);
378 static int nvenc_setup_device(AVCodecContext *avctx)
380 NVENCContext *ctx = avctx->priv_data;
381 NVENCLibraryContext *nvel = &ctx->nvel;
383 switch (avctx->codec->id) {
384 case AV_CODEC_ID_H264:
385 ctx->params.encodeGUID = NV_ENC_CODEC_H264_GUID;
387 case AV_CODEC_ID_HEVC:
388 ctx->params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
394 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
395 AVHWFramesContext *frames_ctx;
396 AVCUDADeviceContext *device_hwctx;
399 if (!avctx->hw_frames_ctx)
400 return AVERROR(EINVAL);
402 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
403 device_hwctx = frames_ctx->device_ctx->hwctx;
405 ctx->cu_context = device_hwctx->cuda_ctx;
407 ret = nvenc_open_session(avctx);
411 ret = nvenc_check_capabilities(avctx);
415 int i, nb_devices = 0;
417 if ((nvel->cu_init(0)) != CUDA_SUCCESS) {
418 av_log(avctx, AV_LOG_ERROR,
419 "Cannot init CUDA\n");
420 return AVERROR_UNKNOWN;
423 if ((nvel->cu_device_get_count(&nb_devices)) != CUDA_SUCCESS) {
424 av_log(avctx, AV_LOG_ERROR,
425 "Cannot enumerate the CUDA devices\n");
426 return AVERROR_UNKNOWN;
430 for (i = 0; i < nb_devices; ++i) {
431 if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
435 if (ctx->device == LIST_DEVICES)
438 return AVERROR(ENOSYS);
444 typedef struct GUIDTuple {
449 static int nvec_map_preset(NVENCContext *ctx)
451 GUIDTuple presets[] = {
452 { NV_ENC_PRESET_DEFAULT_GUID },
453 { NV_ENC_PRESET_HP_GUID },
454 { NV_ENC_PRESET_HQ_GUID },
455 { NV_ENC_PRESET_BD_GUID },
456 { NV_ENC_PRESET_LOW_LATENCY_DEFAULT_GUID, NVENC_LOWLATENCY },
457 { NV_ENC_PRESET_LOW_LATENCY_HP_GUID, NVENC_LOWLATENCY },
458 { NV_ENC_PRESET_LOW_LATENCY_HQ_GUID, NVENC_LOWLATENCY },
459 { NV_ENC_PRESET_LOSSLESS_DEFAULT_GUID, NVENC_LOSSLESS },
460 { NV_ENC_PRESET_LOSSLESS_HP_GUID, NVENC_LOSSLESS },
464 GUIDTuple *t = &presets[ctx->preset];
466 ctx->params.presetGUID = t->guid;
467 ctx->flags = t->flags;
469 return AVERROR(EINVAL);
472 static void set_constqp(AVCodecContext *avctx, NV_ENC_RC_PARAMS *rc)
474 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
475 rc->constQP.qpInterB = avctx->global_quality;
476 rc->constQP.qpInterP = avctx->global_quality;
477 rc->constQP.qpIntra = avctx->global_quality;
480 static void set_vbr(AVCodecContext *avctx, NV_ENC_RC_PARAMS *rc)
482 if (avctx->qmin >= 0) {
484 rc->minQP.qpInterB = avctx->qmin;
485 rc->minQP.qpInterP = avctx->qmin;
486 rc->minQP.qpIntra = avctx->qmin;
489 if (avctx->qmax >= 0) {
491 rc->maxQP.qpInterB = avctx->qmax;
492 rc->maxQP.qpInterP = avctx->qmax;
493 rc->maxQP.qpIntra = avctx->qmax;
497 static void nvenc_override_rate_control(AVCodecContext *avctx,
498 NV_ENC_RC_PARAMS *rc)
500 NVENCContext *ctx = avctx->priv_data;
503 case NV_ENC_PARAMS_RC_CONSTQP:
504 if (avctx->global_quality < 0) {
505 av_log(avctx, AV_LOG_WARNING,
506 "The constant quality rate-control requires "
507 "the 'global_quality' option set.\n");
510 set_constqp(avctx, rc);
512 case NV_ENC_PARAMS_RC_2_PASS_VBR:
513 case NV_ENC_PARAMS_RC_VBR:
514 if (avctx->qmin < 0 && avctx->qmax < 0) {
515 av_log(avctx, AV_LOG_WARNING,
516 "The variable bitrate rate-control requires "
517 "the 'qmin' and/or 'qmax' option set.\n");
520 case NV_ENC_PARAMS_RC_VBR_MINQP:
521 if (avctx->qmin < 0) {
522 av_log(avctx, AV_LOG_WARNING,
523 "The variable bitrate rate-control requires "
524 "the 'qmin' option set.\n");
529 case NV_ENC_PARAMS_RC_CBR:
531 case NV_ENC_PARAMS_RC_2_PASS_QUALITY:
532 case NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP:
533 if (!(ctx->flags & NVENC_LOWLATENCY)) {
534 av_log(avctx, AV_LOG_WARNING,
535 "The multipass rate-control requires "
536 "a low-latency preset.\n");
541 rc->rateControlMode = ctx->rc;
544 static void nvenc_setup_rate_control(AVCodecContext *avctx)
546 NVENCContext *ctx = avctx->priv_data;
547 NV_ENC_RC_PARAMS *rc = &ctx->config.rcParams;
549 if (avctx->bit_rate > 0)
550 rc->averageBitRate = avctx->bit_rate;
552 if (avctx->rc_max_rate > 0)
553 rc->maxBitRate = avctx->rc_max_rate;
556 nvenc_override_rate_control(avctx, rc);
557 } else if (avctx->global_quality > 0) {
558 set_constqp(avctx, rc);
559 } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
560 rc->rateControlMode = NV_ENC_PARAMS_RC_VBR;
564 if (avctx->rc_buffer_size > 0)
565 rc->vbvBufferSize = avctx->rc_buffer_size;
567 if (rc->averageBitRate > 0)
568 avctx->bit_rate = rc->averageBitRate;
571 static int nvenc_setup_h264_config(AVCodecContext *avctx)
573 NVENCContext *ctx = avctx->priv_data;
574 NV_ENC_CONFIG *cc = &ctx->config;
575 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
576 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
578 vui->colourDescriptionPresentFlag = 1;
579 vui->videoSignalTypePresentFlag = 1;
581 vui->colourMatrix = avctx->colorspace;
582 vui->colourPrimaries = avctx->color_primaries;
583 vui->transferCharacteristics = avctx->color_trc;
585 vui->videoFullRangeFlag = avctx->color_range == AVCOL_RANGE_JPEG;
587 h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
588 h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
590 h264->maxNumRefFrames = avctx->refs;
591 h264->idrPeriod = cc->gopLength;
594 avctx->profile = ctx->profile;
596 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P)
597 h264->chromaFormatIDC = 3;
599 h264->chromaFormatIDC = 1;
601 switch (ctx->profile) {
602 case NV_ENC_H264_PROFILE_BASELINE:
603 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
605 case NV_ENC_H264_PROFILE_MAIN:
606 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
608 case NV_ENC_H264_PROFILE_HIGH:
609 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
611 case NV_ENC_H264_PROFILE_HIGH_444:
612 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
614 case NV_ENC_H264_PROFILE_CONSTRAINED_HIGH:
615 cc->profileGUID = NV_ENC_H264_PROFILE_CONSTRAINED_HIGH_GUID;
619 h264->level = ctx->level;
624 static int nvenc_setup_hevc_config(AVCodecContext *avctx)
626 NVENCContext *ctx = avctx->priv_data;
627 NV_ENC_CONFIG *cc = &ctx->config;
628 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
630 hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
631 hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
633 hevc->maxNumRefFramesInDPB = avctx->refs;
634 hevc->idrPeriod = cc->gopLength;
636 /* No other profile is supported in the current SDK version 5 */
637 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
638 avctx->profile = FF_PROFILE_HEVC_MAIN;
641 hevc->level = ctx->level;
643 hevc->level = NV_ENC_LEVEL_AUTOSELECT;
647 hevc->tier = ctx->tier;
652 static int nvenc_setup_codec_config(AVCodecContext *avctx)
654 switch (avctx->codec->id) {
655 case AV_CODEC_ID_H264:
656 return nvenc_setup_h264_config(avctx);
657 case AV_CODEC_ID_HEVC:
658 return nvenc_setup_hevc_config(avctx);
663 static int nvenc_setup_encoder(AVCodecContext *avctx)
665 NVENCContext *ctx = avctx->priv_data;
666 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
667 NV_ENC_PRESET_CONFIG preset_cfg = { 0 };
668 AVCPBProperties *cpb_props;
671 ctx->params.version = NV_ENC_INITIALIZE_PARAMS_VER;
673 ctx->params.encodeHeight = avctx->height;
674 ctx->params.encodeWidth = avctx->width;
676 if (avctx->sample_aspect_ratio.num &&
677 avctx->sample_aspect_ratio.den &&
678 (avctx->sample_aspect_ratio.num != 1 ||
679 avctx->sample_aspect_ratio.den != 1)) {
680 av_reduce(&ctx->params.darWidth,
681 &ctx->params.darHeight,
682 avctx->width * avctx->sample_aspect_ratio.num,
683 avctx->height * avctx->sample_aspect_ratio.den,
686 ctx->params.darHeight = avctx->height;
687 ctx->params.darWidth = avctx->width;
690 ctx->params.frameRateNum = avctx->time_base.den;
691 ctx->params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
693 ctx->params.enableEncodeAsync = 0;
694 ctx->params.enablePTD = 1;
696 ctx->params.encodeConfig = &ctx->config;
698 nvec_map_preset(ctx);
700 preset_cfg.version = NV_ENC_PRESET_CONFIG_VER;
701 preset_cfg.presetCfg.version = NV_ENC_CONFIG_VER;
703 ret = nv->nvEncGetEncodePresetConfig(ctx->nvenc_ctx,
704 ctx->params.encodeGUID,
705 ctx->params.presetGUID,
707 if (ret != NV_ENC_SUCCESS)
708 return nvenc_print_error(avctx, ret, "Cannot get the preset configuration");
710 memcpy(&ctx->config, &preset_cfg.presetCfg, sizeof(ctx->config));
712 ctx->config.version = NV_ENC_CONFIG_VER;
714 if (avctx->gop_size > 0) {
715 if (avctx->max_b_frames > 0) {
719 * 3 two B-frames, and so on. */
720 ctx->config.frameIntervalP = avctx->max_b_frames + 1;
721 } else if (avctx->max_b_frames == 0) {
722 ctx->config.frameIntervalP = 1;
724 ctx->config.gopLength = avctx->gop_size;
725 } else if (avctx->gop_size == 0) {
726 ctx->config.frameIntervalP = 0;
727 ctx->config.gopLength = 1;
730 if (ctx->config.frameIntervalP > 1)
731 avctx->max_b_frames = ctx->config.frameIntervalP - 1;
733 ctx->initial_pts[0] = AV_NOPTS_VALUE;
734 ctx->initial_pts[1] = AV_NOPTS_VALUE;
736 nvenc_setup_rate_control(avctx);
738 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
739 ctx->config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
741 ctx->config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
744 if ((ret = nvenc_setup_codec_config(avctx)) < 0)
747 ret = nv->nvEncInitializeEncoder(ctx->nvenc_ctx, &ctx->params);
748 if (ret != NV_ENC_SUCCESS)
749 return nvenc_print_error(avctx, ret, "Cannot initialize the decoder");
751 cpb_props = ff_add_cpb_side_data(avctx);
753 return AVERROR(ENOMEM);
754 cpb_props->max_bitrate = avctx->rc_max_rate;
755 cpb_props->min_bitrate = avctx->rc_min_rate;
756 cpb_props->avg_bitrate = avctx->bit_rate;
757 cpb_props->buffer_size = avctx->rc_buffer_size;
762 static int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
764 NVENCContext *ctx = avctx->priv_data;
765 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
767 NV_ENC_CREATE_BITSTREAM_BUFFER out_buffer = { 0 };
769 switch (ctx->data_pix_fmt) {
770 case AV_PIX_FMT_YUV420P:
771 ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YV12_PL;
773 case AV_PIX_FMT_NV12:
774 ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_NV12_PL;
776 case AV_PIX_FMT_YUV444P:
777 ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YUV444_PL;
783 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
784 ctx->frames[idx].in_ref = av_frame_alloc();
785 if (!ctx->frames[idx].in_ref)
786 return AVERROR(ENOMEM);
788 NV_ENC_CREATE_INPUT_BUFFER in_buffer = { 0 };
790 in_buffer.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
792 in_buffer.width = avctx->width;
793 in_buffer.height = avctx->height;
795 in_buffer.bufferFmt = ctx->frames[idx].format;
796 in_buffer.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED;
798 ret = nv->nvEncCreateInputBuffer(ctx->nvenc_ctx, &in_buffer);
799 if (ret != NV_ENC_SUCCESS)
800 return nvenc_print_error(avctx, ret, "CreateInputBuffer failed");
802 ctx->frames[idx].in = in_buffer.inputBuffer;
805 out_buffer.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
806 /* 1MB is large enough to hold most output frames.
807 * NVENC increases this automatically if it is not enough. */
808 out_buffer.size = BITSTREAM_BUFFER_SIZE;
810 out_buffer.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED;
812 ret = nv->nvEncCreateBitstreamBuffer(ctx->nvenc_ctx, &out_buffer);
813 if (ret != NV_ENC_SUCCESS)
814 return nvenc_print_error(avctx, ret, "CreateBitstreamBuffer failed");
816 ctx->frames[idx].out = out_buffer.bitstreamBuffer;
821 static int nvenc_setup_surfaces(AVCodecContext *avctx)
823 NVENCContext *ctx = avctx->priv_data;
826 ctx->nb_surfaces = FFMAX(4 + avctx->max_b_frames,
829 ctx->frames = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->frames));
831 return AVERROR(ENOMEM);
833 ctx->timestamps = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
834 if (!ctx->timestamps)
835 return AVERROR(ENOMEM);
836 ctx->pending = av_fifo_alloc(ctx->nb_surfaces * sizeof(*ctx->frames));
838 return AVERROR(ENOMEM);
839 ctx->ready = av_fifo_alloc(ctx->nb_surfaces * sizeof(*ctx->frames));
841 return AVERROR(ENOMEM);
843 for (i = 0; i < ctx->nb_surfaces; i++) {
844 if ((ret = nvenc_alloc_surface(avctx, i)) < 0)
851 #define EXTRADATA_SIZE 512
853 static int nvenc_setup_extradata(AVCodecContext *avctx)
855 NVENCContext *ctx = avctx->priv_data;
856 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
857 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
860 avctx->extradata = av_mallocz(EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
861 if (!avctx->extradata)
862 return AVERROR(ENOMEM);
864 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
865 payload.spsppsBuffer = avctx->extradata;
866 payload.inBufferSize = EXTRADATA_SIZE;
867 payload.outSPSPPSPayloadSize = &avctx->extradata_size;
869 ret = nv->nvEncGetSequenceParams(ctx->nvenc_ctx, &payload);
870 if (ret != NV_ENC_SUCCESS)
871 return nvenc_print_error(avctx, ret, "Cannot get the extradata");
876 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
878 NVENCContext *ctx = avctx->priv_data;
879 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
882 /* the encoder has to be flushed before it can be closed */
883 if (ctx->nvenc_ctx) {
884 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
885 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
887 nv->nvEncEncodePicture(ctx->nvenc_ctx, ¶ms);
890 av_fifo_free(ctx->timestamps);
891 av_fifo_free(ctx->pending);
892 av_fifo_free(ctx->ready);
895 for (i = 0; i < ctx->nb_surfaces; ++i) {
896 if (avctx->pix_fmt != AV_PIX_FMT_CUDA) {
897 nv->nvEncDestroyInputBuffer(ctx->nvenc_ctx, ctx->frames[i].in);
898 } else if (ctx->frames[i].in) {
899 nv->nvEncUnmapInputResource(ctx->nvenc_ctx, ctx->frames[i].in_map.mappedResource);
902 av_frame_free(&ctx->frames[i].in_ref);
903 nv->nvEncDestroyBitstreamBuffer(ctx->nvenc_ctx, ctx->frames[i].out);
906 for (i = 0; i < ctx->nb_registered_frames; i++) {
907 if (ctx->registered_frames[i].regptr)
908 nv->nvEncUnregisterResource(ctx->nvenc_ctx, ctx->registered_frames[i].regptr);
910 ctx->nb_registered_frames = 0;
912 av_freep(&ctx->frames);
915 nv->nvEncDestroyEncoder(ctx->nvenc_ctx);
917 if (ctx->cu_context_internal)
918 ctx->nvel.cu_ctx_destroy(ctx->cu_context_internal);
921 dlclose(ctx->nvel.nvenc);
925 dlclose(ctx->nvel.cuda);
931 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
933 NVENCContext *ctx = avctx->priv_data;
936 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
937 AVHWFramesContext *frames_ctx;
938 if (!avctx->hw_frames_ctx) {
939 av_log(avctx, AV_LOG_ERROR,
940 "hw_frames_ctx must be set when using GPU frames as input\n");
941 return AVERROR(EINVAL);
943 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
944 ctx->data_pix_fmt = frames_ctx->sw_format;
946 ctx->data_pix_fmt = avctx->pix_fmt;
949 if ((ret = nvenc_load_libraries(avctx)) < 0)
952 if ((ret = nvenc_setup_device(avctx)) < 0)
955 if ((ret = nvenc_setup_encoder(avctx)) < 0)
958 if ((ret = nvenc_setup_surfaces(avctx)) < 0)
961 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
962 if ((ret = nvenc_setup_extradata(avctx)) < 0)
969 static NVENCFrame *get_free_frame(NVENCContext *ctx)
973 for (i = 0; i < ctx->nb_surfaces; i++) {
974 if (!ctx->frames[i].locked) {
975 ctx->frames[i].locked = 1;
976 return &ctx->frames[i];
983 static int nvenc_copy_frame(NV_ENC_LOCK_INPUT_BUFFER *in, const AVFrame *frame)
985 uint8_t *buf = in->bufferDataPtr;
986 int off = frame->height * in->pitch;
988 switch (frame->format) {
989 case AV_PIX_FMT_YUV420P:
990 av_image_copy_plane(buf, in->pitch,
991 frame->data[0], frame->linesize[0],
992 frame->width, frame->height);
995 av_image_copy_plane(buf, in->pitch >> 1,
996 frame->data[2], frame->linesize[2],
997 frame->width >> 1, frame->height >> 1);
1001 av_image_copy_plane(buf, in->pitch >> 1,
1002 frame->data[1], frame->linesize[1],
1003 frame->width >> 1, frame->height >> 1);
1005 case AV_PIX_FMT_NV12:
1006 av_image_copy_plane(buf, in->pitch,
1007 frame->data[0], frame->linesize[0],
1008 frame->width, frame->height);
1011 av_image_copy_plane(buf, in->pitch,
1012 frame->data[1], frame->linesize[1],
1013 frame->width, frame->height >> 1);
1015 case AV_PIX_FMT_YUV444P:
1016 av_image_copy_plane(buf, in->pitch,
1017 frame->data[0], frame->linesize[0],
1018 frame->width, frame->height);
1021 av_image_copy_plane(buf, in->pitch,
1022 frame->data[1], frame->linesize[1],
1023 frame->width, frame->height);
1026 av_image_copy_plane(buf, in->pitch,
1027 frame->data[2], frame->linesize[2],
1028 frame->width, frame->height);
1037 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1039 NVENCContext *ctx = avctx->priv_data;
1040 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1043 if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1044 for (i = 0; i < ctx->nb_registered_frames; i++) {
1045 if (!ctx->registered_frames[i].mapped) {
1046 if (ctx->registered_frames[i].regptr) {
1047 nv->nvEncUnregisterResource(ctx->nvenc_ctx,
1048 ctx->registered_frames[i].regptr);
1049 ctx->registered_frames[i].regptr = NULL;
1055 return ctx->nb_registered_frames++;
1058 av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1059 return AVERROR(ENOMEM);
1062 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1064 NVENCContext *ctx = avctx->priv_data;
1065 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1066 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1067 NV_ENC_REGISTER_RESOURCE reg;
1070 for (i = 0; i < ctx->nb_registered_frames; i++) {
1071 if (ctx->registered_frames[i].ptr == (CUdeviceptr)frame->data[0])
1075 idx = nvenc_find_free_reg_resource(avctx);
1079 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1080 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1081 reg.width = frames_ctx->width;
1082 reg.height = frames_ctx->height;
1083 reg.bufferFormat = ctx->frames[0].format;
1084 reg.pitch = frame->linesize[0];
1085 reg.resourceToRegister = frame->data[0];
1087 ret = nv->nvEncRegisterResource(ctx->nvenc_ctx, ®);
1088 if (ret != NV_ENC_SUCCESS) {
1089 nvenc_print_error(avctx, ret, "Error registering an input resource");
1090 return AVERROR_UNKNOWN;
1093 ctx->registered_frames[idx].ptr = (CUdeviceptr)frame->data[0];
1094 ctx->registered_frames[idx].regptr = reg.registeredResource;
1098 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1099 NVENCFrame *nvenc_frame)
1101 NVENCContext *ctx = avctx->priv_data;
1102 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1105 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1108 ret = nvenc_register_frame(avctx, frame);
1110 av_log(avctx, AV_LOG_ERROR, "Could not register an input CUDA frame\n");
1115 ret = av_frame_ref(nvenc_frame->in_ref, frame);
1119 nvenc_frame->in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1120 nvenc_frame->in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1122 ret = nv->nvEncMapInputResource(ctx->nvenc_ctx, &nvenc_frame->in_map);
1123 if (ret != NV_ENC_SUCCESS) {
1124 av_frame_unref(nvenc_frame->in_ref);
1125 return nvenc_print_error(avctx, ret, "Error mapping an input resource");
1128 ctx->registered_frames[reg_idx].mapped = 1;
1129 nvenc_frame->reg_idx = reg_idx;
1130 nvenc_frame->in = nvenc_frame->in_map.mappedResource;
1132 NV_ENC_LOCK_INPUT_BUFFER params = { 0 };
1134 params.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1135 params.inputBuffer = nvenc_frame->in;
1137 ret = nv->nvEncLockInputBuffer(ctx->nvenc_ctx, ¶ms);
1138 if (ret != NV_ENC_SUCCESS)
1139 return nvenc_print_error(avctx, ret, "Cannot lock the buffer");
1141 ret = nvenc_copy_frame(¶ms, frame);
1143 nv->nvEncUnlockInputBuffer(ctx->nvenc_ctx, nvenc_frame->in);
1147 ret = nv->nvEncUnlockInputBuffer(ctx->nvenc_ctx, nvenc_frame->in);
1148 if (ret != NV_ENC_SUCCESS)
1149 return nvenc_print_error(avctx, ret, "Cannot unlock the buffer");
1155 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1156 NV_ENC_PIC_PARAMS *params)
1158 NVENCContext *ctx = avctx->priv_data;
1160 switch (avctx->codec->id) {
1161 case AV_CODEC_ID_H264:
1162 params->codecPicParams.h264PicParams.sliceMode =
1163 ctx->config.encodeCodecConfig.h264Config.sliceMode;
1164 params->codecPicParams.h264PicParams.sliceModeData =
1165 ctx->config.encodeCodecConfig.h264Config.sliceModeData;
1167 case AV_CODEC_ID_HEVC:
1168 params->codecPicParams.hevcPicParams.sliceMode =
1169 ctx->config.encodeCodecConfig.hevcConfig.sliceMode;
1170 params->codecPicParams.hevcPicParams.sliceModeData =
1171 ctx->config.encodeCodecConfig.hevcConfig.sliceModeData;
1176 static inline int nvenc_enqueue_timestamp(AVFifoBuffer *f, int64_t pts)
1178 return av_fifo_generic_write(f, &pts, sizeof(pts), NULL);
1181 static inline int nvenc_dequeue_timestamp(AVFifoBuffer *f, int64_t *pts)
1183 return av_fifo_generic_read(f, pts, sizeof(*pts), NULL);
1186 static int nvenc_set_timestamp(AVCodecContext *avctx,
1187 NV_ENC_LOCK_BITSTREAM *params,
1190 NVENCContext *ctx = avctx->priv_data;
1192 pkt->pts = params->outputTimeStamp;
1193 pkt->duration = params->outputDuration;
1195 /* generate the first dts by linearly extrapolating the
1196 * first two pts values to the past */
1197 if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
1198 ctx->initial_pts[1] != AV_NOPTS_VALUE) {
1199 int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
1202 if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
1203 (ts0 > 0 && ts1 < INT64_MIN + ts0))
1204 return AVERROR(ERANGE);
1207 if ((delta < 0 && ts0 > INT64_MAX + delta) ||
1208 (delta > 0 && ts0 < INT64_MIN + delta))
1209 return AVERROR(ERANGE);
1210 pkt->dts = ts0 - delta;
1212 ctx->first_packet_output = 1;
1215 return nvenc_dequeue_timestamp(ctx->timestamps, &pkt->dts);
1218 static int nvenc_get_output(AVCodecContext *avctx, AVPacket *pkt)
1220 NVENCContext *ctx = avctx->priv_data;
1221 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1222 NV_ENC_LOCK_BITSTREAM params = { 0 };
1226 ret = av_fifo_generic_read(ctx->ready, &frame, sizeof(frame), NULL);
1230 params.version = NV_ENC_LOCK_BITSTREAM_VER;
1231 params.outputBitstream = frame->out;
1233 ret = nv->nvEncLockBitstream(ctx->nvenc_ctx, ¶ms);
1235 return nvenc_print_error(avctx, ret, "Cannot lock the bitstream");
1237 ret = ff_alloc_packet(pkt, params.bitstreamSizeInBytes);
1241 memcpy(pkt->data, params.bitstreamBufferPtr, pkt->size);
1243 ret = nv->nvEncUnlockBitstream(ctx->nvenc_ctx, frame->out);
1245 return nvenc_print_error(avctx, ret, "Cannot unlock the bitstream");
1247 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1248 nv->nvEncUnmapInputResource(ctx->nvenc_ctx, frame->in_map.mappedResource);
1249 av_frame_unref(frame->in_ref);
1250 ctx->registered_frames[frame->reg_idx].mapped = 0;
1257 ret = nvenc_set_timestamp(avctx, ¶ms, pkt);
1261 switch (params.pictureType) {
1262 case NV_ENC_PIC_TYPE_IDR:
1263 pkt->flags |= AV_PKT_FLAG_KEY;
1264 #if FF_API_CODED_FRAME
1265 FF_DISABLE_DEPRECATION_WARNINGS
1266 case NV_ENC_PIC_TYPE_INTRA_REFRESH:
1267 case NV_ENC_PIC_TYPE_I:
1268 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
1270 case NV_ENC_PIC_TYPE_P:
1271 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
1273 case NV_ENC_PIC_TYPE_B:
1274 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;
1276 case NV_ENC_PIC_TYPE_BI:
1277 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_BI;
1279 FF_ENABLE_DEPRECATION_WARNINGS
1286 static int output_ready(AVCodecContext *avctx, int flush)
1288 NVENCContext *ctx = avctx->priv_data;
1290 /* when B-frames are enabled, we wait for two initial timestamps to
1291 * calculate the first dts */
1292 if (!flush && avctx->max_b_frames > 0 &&
1293 (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
1295 return av_fifo_size(ctx->ready) > 0;
1298 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1299 const AVFrame *frame, int *got_packet)
1301 NVENCContext *ctx = avctx->priv_data;
1302 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1303 NV_ENC_PIC_PARAMS params = { 0 };
1304 NVENCFrame *nvenc_frame = NULL;
1307 params.version = NV_ENC_PIC_PARAMS_VER;
1310 nvenc_frame = get_free_frame(ctx);
1312 av_log(avctx, AV_LOG_ERROR, "No free surfaces\n");
1316 ret = nvenc_upload_frame(avctx, frame, nvenc_frame);
1320 params.inputBuffer = nvenc_frame->in;
1321 params.bufferFmt = nvenc_frame->format;
1322 params.inputWidth = frame->width;
1323 params.inputHeight = frame->height;
1324 params.outputBitstream = nvenc_frame->out;
1325 params.inputTimeStamp = frame->pts;
1327 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1328 if (frame->top_field_first)
1329 params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
1331 params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
1333 params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1336 nvenc_codec_specific_pic_params(avctx, ¶ms);
1338 ret = nvenc_enqueue_timestamp(ctx->timestamps, frame->pts);
1342 if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
1343 ctx->initial_pts[0] = frame->pts;
1344 else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
1345 ctx->initial_pts[1] = frame->pts;
1347 params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1350 enc_ret = nv->nvEncEncodePicture(ctx->nvenc_ctx, ¶ms);
1351 if (enc_ret != NV_ENC_SUCCESS &&
1352 enc_ret != NV_ENC_ERR_NEED_MORE_INPUT)
1353 return nvenc_print_error(avctx, enc_ret, "Error encoding the frame");
1356 ret = av_fifo_generic_write(ctx->pending, &nvenc_frame, sizeof(nvenc_frame), NULL);
1361 /* all the pending buffers are now ready for output */
1362 if (enc_ret == NV_ENC_SUCCESS) {
1363 while (av_fifo_size(ctx->pending) > 0) {
1364 av_fifo_generic_read(ctx->pending, &nvenc_frame, sizeof(nvenc_frame), NULL);
1365 av_fifo_generic_write(ctx->ready, &nvenc_frame, sizeof(nvenc_frame), NULL);
1369 if (output_ready(avctx, !frame)) {
1370 ret = nvenc_get_output(avctx, pkt);