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
60 #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR || \
61 rc == NV_ENC_PARAMS_RC_2_PASS_QUALITY || \
62 rc == NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP)
64 #define LOAD_LIBRARY(l, path) \
66 if (!((l) = dlopen(path, RTLD_LAZY))) { \
67 av_log(avctx, AV_LOG_ERROR, \
70 return AVERROR_UNKNOWN; \
74 #define LOAD_SYMBOL(fun, lib, symbol) \
76 if (!((fun) = dlsym(lib, symbol))) { \
77 av_log(avctx, AV_LOG_ERROR, \
80 return AVERROR_UNKNOWN; \
84 const enum AVPixelFormat ff_nvenc_pix_fmts[] = {
97 { NV_ENC_SUCCESS, 0, "success" },
98 { NV_ENC_ERR_NO_ENCODE_DEVICE, AVERROR(ENOENT), "no encode device" },
99 { NV_ENC_ERR_UNSUPPORTED_DEVICE, AVERROR(ENOSYS), "unsupported device" },
100 { NV_ENC_ERR_INVALID_ENCODERDEVICE, AVERROR(EINVAL), "invalid encoder device" },
101 { NV_ENC_ERR_INVALID_DEVICE, AVERROR(EINVAL), "invalid device" },
102 { NV_ENC_ERR_DEVICE_NOT_EXIST, AVERROR(EIO), "device does not exist" },
103 { NV_ENC_ERR_INVALID_PTR, AVERROR(EFAULT), "invalid ptr" },
104 { NV_ENC_ERR_INVALID_EVENT, AVERROR(EINVAL), "invalid event" },
105 { NV_ENC_ERR_INVALID_PARAM, AVERROR(EINVAL), "invalid param" },
106 { NV_ENC_ERR_INVALID_CALL, AVERROR(EINVAL), "invalid call" },
107 { NV_ENC_ERR_OUT_OF_MEMORY, AVERROR(ENOMEM), "out of memory" },
108 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED, AVERROR(EINVAL), "encoder not initialized" },
109 { NV_ENC_ERR_UNSUPPORTED_PARAM, AVERROR(ENOSYS), "unsupported param" },
110 { NV_ENC_ERR_LOCK_BUSY, AVERROR(EAGAIN), "lock busy" },
111 { NV_ENC_ERR_NOT_ENOUGH_BUFFER, AVERROR(ENOBUFS), "not enough buffer" },
112 { NV_ENC_ERR_INVALID_VERSION, AVERROR(EINVAL), "invalid version" },
113 { NV_ENC_ERR_MAP_FAILED, AVERROR(EIO), "map failed" },
114 { NV_ENC_ERR_NEED_MORE_INPUT, AVERROR(EAGAIN), "need more input" },
115 { NV_ENC_ERR_ENCODER_BUSY, AVERROR(EAGAIN), "encoder busy" },
116 { NV_ENC_ERR_EVENT_NOT_REGISTERD, AVERROR(EBADF), "event not registered" },
117 { NV_ENC_ERR_GENERIC, AVERROR_UNKNOWN, "generic error" },
118 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY, AVERROR(EINVAL), "incompatible client key" },
119 { NV_ENC_ERR_UNIMPLEMENTED, AVERROR(ENOSYS), "unimplemented" },
120 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO), "resource register failed" },
121 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED, AVERROR(EBADF), "resource not registered" },
122 { NV_ENC_ERR_RESOURCE_NOT_MAPPED, AVERROR(EBADF), "resource not mapped" },
125 static int nvenc_map_error(NVENCSTATUS err, const char **desc)
128 for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
129 if (nvenc_errors[i].nverr == err) {
131 *desc = nvenc_errors[i].desc;
132 return nvenc_errors[i].averr;
136 *desc = "unknown error";
137 return AVERROR_UNKNOWN;
140 static int nvenc_print_error(void *log_ctx, NVENCSTATUS err,
141 const char *error_string)
145 ret = nvenc_map_error(err, &desc);
146 av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
150 static av_cold int nvenc_load_libraries(AVCodecContext *avctx)
152 NVENCContext *ctx = avctx->priv_data;
153 NVENCLibraryContext *nvel = &ctx->nvel;
154 PNVENCODEAPICREATEINSTANCE nvenc_create_instance;
158 nvel->cu_init = cuInit;
159 nvel->cu_device_get_count = cuDeviceGetCount;
160 nvel->cu_device_get = cuDeviceGet;
161 nvel->cu_device_get_name = cuDeviceGetName;
162 nvel->cu_device_compute_capability = cuDeviceComputeCapability;
163 nvel->cu_ctx_create = cuCtxCreate_v2;
164 nvel->cu_ctx_pop_current = cuCtxPopCurrent_v2;
165 nvel->cu_ctx_destroy = cuCtxDestroy_v2;
167 LOAD_LIBRARY(nvel->cuda, CUDA_LIBNAME);
169 LOAD_SYMBOL(nvel->cu_init, nvel->cuda, "cuInit");
170 LOAD_SYMBOL(nvel->cu_device_get_count, nvel->cuda, "cuDeviceGetCount");
171 LOAD_SYMBOL(nvel->cu_device_get, nvel->cuda, "cuDeviceGet");
172 LOAD_SYMBOL(nvel->cu_device_get_name, nvel->cuda, "cuDeviceGetName");
173 LOAD_SYMBOL(nvel->cu_device_compute_capability, nvel->cuda,
174 "cuDeviceComputeCapability");
175 LOAD_SYMBOL(nvel->cu_ctx_create, nvel->cuda, "cuCtxCreate_v2");
176 LOAD_SYMBOL(nvel->cu_ctx_pop_current, nvel->cuda, "cuCtxPopCurrent_v2");
177 LOAD_SYMBOL(nvel->cu_ctx_destroy, nvel->cuda, "cuCtxDestroy_v2");
180 LOAD_LIBRARY(nvel->nvenc, NVENC_LIBNAME);
182 LOAD_SYMBOL(nvenc_create_instance, nvel->nvenc,
183 "NvEncodeAPICreateInstance");
185 nvel->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
187 err = nvenc_create_instance(&nvel->nvenc_funcs);
188 if (err != NV_ENC_SUCCESS)
189 return nvenc_print_error(avctx, err, "Cannot create the NVENC instance");
194 static int nvenc_open_session(AVCodecContext *avctx)
196 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
197 NVENCContext *ctx = avctx->priv_data;
198 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
201 params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
202 params.apiVersion = NVENCAPI_VERSION;
203 params.device = ctx->cu_context;
204 params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
206 ret = nv->nvEncOpenEncodeSessionEx(¶ms, &ctx->nvenc_ctx);
207 if (ret != NV_ENC_SUCCESS) {
208 ctx->nvenc_ctx = NULL;
209 return nvenc_print_error(avctx, ret, "Cannot open the NVENC Session");
215 static int nvenc_check_codec_support(AVCodecContext *avctx)
217 NVENCContext *ctx = avctx->priv_data;
218 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
219 int i, ret, count = 0;
222 ret = nv->nvEncGetEncodeGUIDCount(ctx->nvenc_ctx, &count);
224 if (ret != NV_ENC_SUCCESS || !count)
225 return AVERROR(ENOSYS);
227 guids = av_malloc(count * sizeof(GUID));
229 return AVERROR(ENOMEM);
231 ret = nv->nvEncGetEncodeGUIDs(ctx->nvenc_ctx, guids, count, &count);
232 if (ret != NV_ENC_SUCCESS) {
233 ret = AVERROR(ENOSYS);
237 ret = AVERROR(ENOSYS);
238 for (i = 0; i < count; i++) {
239 if (!memcmp(&guids[i], &ctx->params.encodeGUID, sizeof(*guids))) {
251 static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
253 NVENCContext *ctx = avctx->priv_data;
254 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
255 NV_ENC_CAPS_PARAM params = { 0 };
258 params.version = NV_ENC_CAPS_PARAM_VER;
259 params.capsToQuery = cap;
261 ret = nv->nvEncGetEncodeCaps(ctx->nvenc_ctx, ctx->params.encodeGUID, ¶ms, &val);
263 if (ret == NV_ENC_SUCCESS)
268 static int nvenc_check_capabilities(AVCodecContext *avctx)
270 NVENCContext *ctx = avctx->priv_data;
273 ret = nvenc_check_codec_support(avctx);
275 av_log(avctx, AV_LOG_VERBOSE, "Codec not supported\n");
279 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
280 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P && ret <= 0) {
281 av_log(avctx, AV_LOG_VERBOSE, "YUV444P not supported\n");
282 return AVERROR(ENOSYS);
285 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
286 if (ret < avctx->width) {
287 av_log(avctx, AV_LOG_VERBOSE, "Width %d exceeds %d\n",
289 return AVERROR(ENOSYS);
292 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
293 if (ret < avctx->height) {
294 av_log(avctx, AV_LOG_VERBOSE, "Height %d exceeds %d\n",
296 return AVERROR(ENOSYS);
299 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
300 if (ret < avctx->max_b_frames) {
301 av_log(avctx, AV_LOG_VERBOSE, "Max B-frames %d exceed %d\n",
302 avctx->max_b_frames, ret);
304 return AVERROR(ENOSYS);
310 static int nvenc_check_device(AVCodecContext *avctx, int idx)
312 NVENCContext *ctx = avctx->priv_data;
313 NVENCLibraryContext *nvel = &ctx->nvel;
314 char name[128] = { 0 };
315 int major, minor, ret;
318 int loglevel = AV_LOG_VERBOSE;
320 if (ctx->device == LIST_DEVICES)
321 loglevel = AV_LOG_INFO;
323 ret = nvel->cu_device_get(&cu_device, idx);
324 if (ret != CUDA_SUCCESS) {
325 av_log(avctx, AV_LOG_ERROR,
326 "Cannot access the CUDA device %d\n",
331 ret = nvel->cu_device_get_name(name, sizeof(name), cu_device);
332 if (ret != CUDA_SUCCESS)
335 ret = nvel->cu_device_compute_capability(&major, &minor, cu_device);
336 if (ret != CUDA_SUCCESS)
339 av_log(avctx, loglevel, "Device %d [%s] ", cu_device, name);
341 if (((major << 4) | minor) < NVENC_CAP)
344 ret = nvel->cu_ctx_create(&ctx->cu_context_internal, 0, cu_device);
345 if (ret != CUDA_SUCCESS)
348 ctx->cu_context = ctx->cu_context_internal;
350 ret = nvel->cu_ctx_pop_current(&dummy);
351 if (ret != CUDA_SUCCESS)
354 if ((ret = nvenc_open_session(avctx)) < 0)
357 if ((ret = nvenc_check_capabilities(avctx)) < 0)
360 av_log(avctx, loglevel, "supports NVENC\n");
362 if (ctx->device == cu_device || ctx->device == ANY_DEVICE)
366 nvel->nvenc_funcs.nvEncDestroyEncoder(ctx->nvenc_ctx);
367 ctx->nvenc_ctx = NULL;
370 nvel->cu_ctx_destroy(ctx->cu_context_internal);
371 ctx->cu_context_internal = NULL;
375 av_log(avctx, loglevel, "does not support NVENC (major %d minor %d)\n",
378 return AVERROR(ENOSYS);
381 static int nvenc_setup_device(AVCodecContext *avctx)
383 NVENCContext *ctx = avctx->priv_data;
384 NVENCLibraryContext *nvel = &ctx->nvel;
386 switch (avctx->codec->id) {
387 case AV_CODEC_ID_H264:
388 ctx->params.encodeGUID = NV_ENC_CODEC_H264_GUID;
390 case AV_CODEC_ID_HEVC:
391 ctx->params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
397 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
398 AVHWFramesContext *frames_ctx;
399 AVCUDADeviceContext *device_hwctx;
402 if (!avctx->hw_frames_ctx)
403 return AVERROR(EINVAL);
405 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
406 device_hwctx = frames_ctx->device_ctx->hwctx;
408 ctx->cu_context = device_hwctx->cuda_ctx;
410 ret = nvenc_open_session(avctx);
414 ret = nvenc_check_capabilities(avctx);
418 int i, nb_devices = 0;
420 if ((nvel->cu_init(0)) != CUDA_SUCCESS) {
421 av_log(avctx, AV_LOG_ERROR,
422 "Cannot init CUDA\n");
423 return AVERROR_UNKNOWN;
426 if ((nvel->cu_device_get_count(&nb_devices)) != CUDA_SUCCESS) {
427 av_log(avctx, AV_LOG_ERROR,
428 "Cannot enumerate the CUDA devices\n");
429 return AVERROR_UNKNOWN;
433 for (i = 0; i < nb_devices; ++i) {
434 if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
438 if (ctx->device == LIST_DEVICES)
441 return AVERROR(ENOSYS);
447 typedef struct GUIDTuple {
452 static int nvec_map_preset(NVENCContext *ctx)
454 GUIDTuple presets[] = {
455 { NV_ENC_PRESET_DEFAULT_GUID },
456 { NV_ENC_PRESET_HP_GUID },
457 { NV_ENC_PRESET_HQ_GUID },
458 { NV_ENC_PRESET_BD_GUID },
459 { NV_ENC_PRESET_LOW_LATENCY_DEFAULT_GUID, NVENC_LOWLATENCY },
460 { NV_ENC_PRESET_LOW_LATENCY_HP_GUID, NVENC_LOWLATENCY },
461 { NV_ENC_PRESET_LOW_LATENCY_HQ_GUID, NVENC_LOWLATENCY },
462 { NV_ENC_PRESET_LOSSLESS_DEFAULT_GUID, NVENC_LOSSLESS },
463 { NV_ENC_PRESET_LOSSLESS_HP_GUID, NVENC_LOSSLESS },
467 GUIDTuple *t = &presets[ctx->preset];
469 ctx->params.presetGUID = t->guid;
470 ctx->flags = t->flags;
472 return AVERROR(EINVAL);
475 static void set_constqp(AVCodecContext *avctx, NV_ENC_RC_PARAMS *rc)
477 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
478 rc->constQP.qpInterB = avctx->global_quality;
479 rc->constQP.qpInterP = avctx->global_quality;
480 rc->constQP.qpIntra = avctx->global_quality;
483 static void set_vbr(AVCodecContext *avctx, NV_ENC_RC_PARAMS *rc)
485 if (avctx->qmin >= 0) {
487 rc->minQP.qpInterB = avctx->qmin;
488 rc->minQP.qpInterP = avctx->qmin;
489 rc->minQP.qpIntra = avctx->qmin;
492 if (avctx->qmax >= 0) {
494 rc->maxQP.qpInterB = avctx->qmax;
495 rc->maxQP.qpInterP = avctx->qmax;
496 rc->maxQP.qpIntra = avctx->qmax;
500 static void set_lossless(AVCodecContext *avctx, NV_ENC_RC_PARAMS *rc)
502 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
503 rc->constQP.qpInterB = 0;
504 rc->constQP.qpInterP = 0;
505 rc->constQP.qpIntra = 0;
508 static void nvenc_override_rate_control(AVCodecContext *avctx,
509 NV_ENC_RC_PARAMS *rc)
511 NVENCContext *ctx = avctx->priv_data;
514 case NV_ENC_PARAMS_RC_CONSTQP:
515 if (avctx->global_quality < 0) {
516 av_log(avctx, AV_LOG_WARNING,
517 "The constant quality rate-control requires "
518 "the 'global_quality' option set.\n");
521 set_constqp(avctx, rc);
523 case NV_ENC_PARAMS_RC_2_PASS_VBR:
524 case NV_ENC_PARAMS_RC_VBR:
525 if (avctx->qmin < 0 && avctx->qmax < 0) {
526 av_log(avctx, AV_LOG_WARNING,
527 "The variable bitrate rate-control requires "
528 "the 'qmin' and/or 'qmax' option set.\n");
531 case NV_ENC_PARAMS_RC_VBR_MINQP:
532 if (avctx->qmin < 0) {
533 av_log(avctx, AV_LOG_WARNING,
534 "The variable bitrate rate-control requires "
535 "the 'qmin' option set.\n");
540 case NV_ENC_PARAMS_RC_CBR:
542 case NV_ENC_PARAMS_RC_2_PASS_QUALITY:
543 case NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP:
544 if (!(ctx->flags & NVENC_LOWLATENCY)) {
545 av_log(avctx, AV_LOG_WARNING,
546 "The multipass rate-control requires "
547 "a low-latency preset.\n");
552 rc->rateControlMode = ctx->rc;
555 static void nvenc_setup_rate_control(AVCodecContext *avctx)
557 NVENCContext *ctx = avctx->priv_data;
558 NV_ENC_RC_PARAMS *rc = &ctx->config.rcParams;
560 if (avctx->bit_rate > 0)
561 rc->averageBitRate = avctx->bit_rate;
563 if (avctx->rc_max_rate > 0)
564 rc->maxBitRate = avctx->rc_max_rate;
567 nvenc_override_rate_control(avctx, rc);
568 } else if (ctx->flags & NVENC_LOSSLESS) {
569 set_lossless(avctx, rc);
570 } else if (avctx->global_quality > 0) {
571 set_constqp(avctx, rc);
572 } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
573 rc->rateControlMode = NV_ENC_PARAMS_RC_VBR;
577 if (avctx->rc_buffer_size > 0)
578 rc->vbvBufferSize = avctx->rc_buffer_size;
580 if (rc->averageBitRate > 0)
581 avctx->bit_rate = rc->averageBitRate;
584 static int nvenc_setup_h264_config(AVCodecContext *avctx)
586 NVENCContext *ctx = avctx->priv_data;
587 NV_ENC_CONFIG *cc = &ctx->config;
588 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
589 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
591 vui->colourDescriptionPresentFlag = avctx->colorspace != AVCOL_SPC_UNSPECIFIED ||
592 avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
593 avctx->color_trc != AVCOL_TRC_UNSPECIFIED;
595 vui->colourMatrix = avctx->colorspace;
596 vui->colourPrimaries = avctx->color_primaries;
597 vui->transferCharacteristics = avctx->color_trc;
599 vui->videoFullRangeFlag = avctx->color_range == AVCOL_RANGE_JPEG;
601 vui->videoSignalTypePresentFlag = vui->colourDescriptionPresentFlag ||
602 vui->videoFullRangeFlag;
604 h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
605 h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
608 h264->maxNumRefFrames = avctx->refs;
609 h264->idrPeriod = cc->gopLength;
611 if (ctx->flags & NVENC_LOSSLESS)
612 h264->qpPrimeYZeroTransformBypassFlag = 1;
614 if (IS_CBR(cc->rcParams.rateControlMode)) {
615 h264->outputBufferingPeriodSEI = 1;
616 h264->outputPictureTimingSEI = 1;
620 avctx->profile = ctx->profile;
622 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P)
623 h264->chromaFormatIDC = 3;
625 h264->chromaFormatIDC = 1;
627 switch (ctx->profile) {
628 case NV_ENC_H264_PROFILE_BASELINE:
629 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
631 case NV_ENC_H264_PROFILE_MAIN:
632 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
634 case NV_ENC_H264_PROFILE_HIGH:
635 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
637 case NV_ENC_H264_PROFILE_HIGH_444:
638 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
640 case NV_ENC_H264_PROFILE_CONSTRAINED_HIGH:
641 cc->profileGUID = NV_ENC_H264_PROFILE_CONSTRAINED_HIGH_GUID;
645 h264->level = ctx->level;
650 static int nvenc_setup_hevc_config(AVCodecContext *avctx)
652 NVENCContext *ctx = avctx->priv_data;
653 NV_ENC_CONFIG *cc = &ctx->config;
654 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
656 hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
657 hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
660 hevc->maxNumRefFramesInDPB = avctx->refs;
661 hevc->idrPeriod = cc->gopLength;
663 if (IS_CBR(cc->rcParams.rateControlMode)) {
664 hevc->outputBufferingPeriodSEI = 1;
665 hevc->outputPictureTimingSEI = 1;
668 /* No other profile is supported in the current SDK version 5 */
669 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
670 avctx->profile = FF_PROFILE_HEVC_MAIN;
673 hevc->level = ctx->level;
675 hevc->level = NV_ENC_LEVEL_AUTOSELECT;
679 hevc->tier = ctx->tier;
684 static int nvenc_setup_codec_config(AVCodecContext *avctx)
686 switch (avctx->codec->id) {
687 case AV_CODEC_ID_H264:
688 return nvenc_setup_h264_config(avctx);
689 case AV_CODEC_ID_HEVC:
690 return nvenc_setup_hevc_config(avctx);
695 static int nvenc_setup_encoder(AVCodecContext *avctx)
697 NVENCContext *ctx = avctx->priv_data;
698 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
699 NV_ENC_PRESET_CONFIG preset_cfg = { 0 };
700 AVCPBProperties *cpb_props;
703 ctx->params.version = NV_ENC_INITIALIZE_PARAMS_VER;
705 ctx->params.encodeHeight = avctx->height;
706 ctx->params.encodeWidth = avctx->width;
708 if (avctx->sample_aspect_ratio.num &&
709 avctx->sample_aspect_ratio.den &&
710 (avctx->sample_aspect_ratio.num != 1 ||
711 avctx->sample_aspect_ratio.den != 1)) {
712 av_reduce(&ctx->params.darWidth,
713 &ctx->params.darHeight,
714 avctx->width * avctx->sample_aspect_ratio.num,
715 avctx->height * avctx->sample_aspect_ratio.den,
718 ctx->params.darHeight = avctx->height;
719 ctx->params.darWidth = avctx->width;
722 ctx->params.frameRateNum = avctx->time_base.den;
723 ctx->params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
725 ctx->params.enableEncodeAsync = 0;
726 ctx->params.enablePTD = 1;
728 ctx->params.encodeConfig = &ctx->config;
730 nvec_map_preset(ctx);
732 preset_cfg.version = NV_ENC_PRESET_CONFIG_VER;
733 preset_cfg.presetCfg.version = NV_ENC_CONFIG_VER;
735 ret = nv->nvEncGetEncodePresetConfig(ctx->nvenc_ctx,
736 ctx->params.encodeGUID,
737 ctx->params.presetGUID,
739 if (ret != NV_ENC_SUCCESS)
740 return nvenc_print_error(avctx, ret, "Cannot get the preset configuration");
742 memcpy(&ctx->config, &preset_cfg.presetCfg, sizeof(ctx->config));
744 ctx->config.version = NV_ENC_CONFIG_VER;
746 if (avctx->gop_size > 0) {
747 if (avctx->max_b_frames > 0) {
751 * 3 two B-frames, and so on. */
752 ctx->config.frameIntervalP = avctx->max_b_frames + 1;
753 } else if (avctx->max_b_frames == 0) {
754 ctx->config.frameIntervalP = 1;
756 ctx->config.gopLength = avctx->gop_size;
757 } else if (avctx->gop_size == 0) {
758 ctx->config.frameIntervalP = 0;
759 ctx->config.gopLength = 1;
762 if (ctx->config.frameIntervalP > 1)
763 avctx->max_b_frames = ctx->config.frameIntervalP - 1;
765 ctx->initial_pts[0] = AV_NOPTS_VALUE;
766 ctx->initial_pts[1] = AV_NOPTS_VALUE;
768 nvenc_setup_rate_control(avctx);
770 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
771 ctx->config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
773 ctx->config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
776 if ((ret = nvenc_setup_codec_config(avctx)) < 0)
779 ret = nv->nvEncInitializeEncoder(ctx->nvenc_ctx, &ctx->params);
780 if (ret != NV_ENC_SUCCESS)
781 return nvenc_print_error(avctx, ret, "Cannot initialize the decoder");
783 cpb_props = ff_add_cpb_side_data(avctx);
785 return AVERROR(ENOMEM);
786 cpb_props->max_bitrate = avctx->rc_max_rate;
787 cpb_props->min_bitrate = avctx->rc_min_rate;
788 cpb_props->avg_bitrate = avctx->bit_rate;
789 cpb_props->buffer_size = avctx->rc_buffer_size;
794 static int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
796 NVENCContext *ctx = avctx->priv_data;
797 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
799 NV_ENC_CREATE_BITSTREAM_BUFFER out_buffer = { 0 };
801 switch (ctx->data_pix_fmt) {
802 case AV_PIX_FMT_YUV420P:
803 ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YV12_PL;
805 case AV_PIX_FMT_NV12:
806 ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_NV12_PL;
808 case AV_PIX_FMT_YUV444P:
809 ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YUV444_PL;
815 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
816 ctx->frames[idx].in_ref = av_frame_alloc();
817 if (!ctx->frames[idx].in_ref)
818 return AVERROR(ENOMEM);
820 NV_ENC_CREATE_INPUT_BUFFER in_buffer = { 0 };
822 in_buffer.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
824 in_buffer.width = avctx->width;
825 in_buffer.height = avctx->height;
827 in_buffer.bufferFmt = ctx->frames[idx].format;
828 in_buffer.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED;
830 ret = nv->nvEncCreateInputBuffer(ctx->nvenc_ctx, &in_buffer);
831 if (ret != NV_ENC_SUCCESS)
832 return nvenc_print_error(avctx, ret, "CreateInputBuffer failed");
834 ctx->frames[idx].in = in_buffer.inputBuffer;
837 out_buffer.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
838 /* 1MB is large enough to hold most output frames.
839 * NVENC increases this automatically if it is not enough. */
840 out_buffer.size = BITSTREAM_BUFFER_SIZE;
842 out_buffer.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED;
844 ret = nv->nvEncCreateBitstreamBuffer(ctx->nvenc_ctx, &out_buffer);
845 if (ret != NV_ENC_SUCCESS)
846 return nvenc_print_error(avctx, ret, "CreateBitstreamBuffer failed");
848 ctx->frames[idx].out = out_buffer.bitstreamBuffer;
853 static int nvenc_setup_surfaces(AVCodecContext *avctx)
855 NVENCContext *ctx = avctx->priv_data;
858 ctx->nb_surfaces = FFMAX(4 + avctx->max_b_frames,
860 ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
863 ctx->frames = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->frames));
865 return AVERROR(ENOMEM);
867 ctx->timestamps = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
868 if (!ctx->timestamps)
869 return AVERROR(ENOMEM);
870 ctx->pending = av_fifo_alloc(ctx->nb_surfaces * sizeof(*ctx->frames));
872 return AVERROR(ENOMEM);
873 ctx->ready = av_fifo_alloc(ctx->nb_surfaces * sizeof(*ctx->frames));
875 return AVERROR(ENOMEM);
877 for (i = 0; i < ctx->nb_surfaces; i++) {
878 if ((ret = nvenc_alloc_surface(avctx, i)) < 0)
885 #define EXTRADATA_SIZE 512
887 static int nvenc_setup_extradata(AVCodecContext *avctx)
889 NVENCContext *ctx = avctx->priv_data;
890 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
891 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
894 avctx->extradata = av_mallocz(EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
895 if (!avctx->extradata)
896 return AVERROR(ENOMEM);
898 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
899 payload.spsppsBuffer = avctx->extradata;
900 payload.inBufferSize = EXTRADATA_SIZE;
901 payload.outSPSPPSPayloadSize = &avctx->extradata_size;
903 ret = nv->nvEncGetSequenceParams(ctx->nvenc_ctx, &payload);
904 if (ret != NV_ENC_SUCCESS)
905 return nvenc_print_error(avctx, ret, "Cannot get the extradata");
910 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
912 NVENCContext *ctx = avctx->priv_data;
913 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
916 /* the encoder has to be flushed before it can be closed */
917 if (ctx->nvenc_ctx) {
918 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
919 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
921 nv->nvEncEncodePicture(ctx->nvenc_ctx, ¶ms);
924 av_fifo_free(ctx->timestamps);
925 av_fifo_free(ctx->pending);
926 av_fifo_free(ctx->ready);
929 for (i = 0; i < ctx->nb_surfaces; ++i) {
930 if (avctx->pix_fmt != AV_PIX_FMT_CUDA) {
931 nv->nvEncDestroyInputBuffer(ctx->nvenc_ctx, ctx->frames[i].in);
932 } else if (ctx->frames[i].in) {
933 nv->nvEncUnmapInputResource(ctx->nvenc_ctx, ctx->frames[i].in_map.mappedResource);
936 av_frame_free(&ctx->frames[i].in_ref);
937 nv->nvEncDestroyBitstreamBuffer(ctx->nvenc_ctx, ctx->frames[i].out);
940 for (i = 0; i < ctx->nb_registered_frames; i++) {
941 if (ctx->registered_frames[i].regptr)
942 nv->nvEncUnregisterResource(ctx->nvenc_ctx, ctx->registered_frames[i].regptr);
944 ctx->nb_registered_frames = 0;
946 av_freep(&ctx->frames);
949 nv->nvEncDestroyEncoder(ctx->nvenc_ctx);
951 if (ctx->cu_context_internal)
952 ctx->nvel.cu_ctx_destroy(ctx->cu_context_internal);
955 dlclose(ctx->nvel.nvenc);
959 dlclose(ctx->nvel.cuda);
965 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
967 NVENCContext *ctx = avctx->priv_data;
970 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
971 AVHWFramesContext *frames_ctx;
972 if (!avctx->hw_frames_ctx) {
973 av_log(avctx, AV_LOG_ERROR,
974 "hw_frames_ctx must be set when using GPU frames as input\n");
975 return AVERROR(EINVAL);
977 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
978 ctx->data_pix_fmt = frames_ctx->sw_format;
980 ctx->data_pix_fmt = avctx->pix_fmt;
983 if ((ret = nvenc_load_libraries(avctx)) < 0)
986 if ((ret = nvenc_setup_device(avctx)) < 0)
989 if ((ret = nvenc_setup_encoder(avctx)) < 0)
992 if ((ret = nvenc_setup_surfaces(avctx)) < 0)
995 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
996 if ((ret = nvenc_setup_extradata(avctx)) < 0)
1003 static NVENCFrame *get_free_frame(NVENCContext *ctx)
1007 for (i = 0; i < ctx->nb_surfaces; i++) {
1008 if (!ctx->frames[i].locked) {
1009 ctx->frames[i].locked = 1;
1010 return &ctx->frames[i];
1017 static int nvenc_copy_frame(NV_ENC_LOCK_INPUT_BUFFER *in, const AVFrame *frame)
1019 uint8_t *buf = in->bufferDataPtr;
1020 int off = frame->height * in->pitch;
1022 switch (frame->format) {
1023 case AV_PIX_FMT_YUV420P:
1024 av_image_copy_plane(buf, in->pitch,
1025 frame->data[0], frame->linesize[0],
1026 frame->width, frame->height);
1029 av_image_copy_plane(buf, in->pitch >> 1,
1030 frame->data[2], frame->linesize[2],
1031 frame->width >> 1, frame->height >> 1);
1035 av_image_copy_plane(buf, in->pitch >> 1,
1036 frame->data[1], frame->linesize[1],
1037 frame->width >> 1, frame->height >> 1);
1039 case AV_PIX_FMT_NV12:
1040 av_image_copy_plane(buf, in->pitch,
1041 frame->data[0], frame->linesize[0],
1042 frame->width, frame->height);
1045 av_image_copy_plane(buf, in->pitch,
1046 frame->data[1], frame->linesize[1],
1047 frame->width, frame->height >> 1);
1049 case AV_PIX_FMT_YUV444P:
1050 av_image_copy_plane(buf, in->pitch,
1051 frame->data[0], frame->linesize[0],
1052 frame->width, frame->height);
1055 av_image_copy_plane(buf, in->pitch,
1056 frame->data[1], frame->linesize[1],
1057 frame->width, frame->height);
1060 av_image_copy_plane(buf, in->pitch,
1061 frame->data[2], frame->linesize[2],
1062 frame->width, frame->height);
1071 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1073 NVENCContext *ctx = avctx->priv_data;
1074 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1077 if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1078 for (i = 0; i < ctx->nb_registered_frames; i++) {
1079 if (!ctx->registered_frames[i].mapped) {
1080 if (ctx->registered_frames[i].regptr) {
1081 nv->nvEncUnregisterResource(ctx->nvenc_ctx,
1082 ctx->registered_frames[i].regptr);
1083 ctx->registered_frames[i].regptr = NULL;
1089 return ctx->nb_registered_frames++;
1092 av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1093 return AVERROR(ENOMEM);
1096 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1098 NVENCContext *ctx = avctx->priv_data;
1099 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1100 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1101 NV_ENC_REGISTER_RESOURCE reg;
1104 for (i = 0; i < ctx->nb_registered_frames; i++) {
1105 if (ctx->registered_frames[i].ptr == (CUdeviceptr)frame->data[0])
1109 idx = nvenc_find_free_reg_resource(avctx);
1113 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1114 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1115 reg.width = frames_ctx->width;
1116 reg.height = frames_ctx->height;
1117 reg.bufferFormat = ctx->frames[0].format;
1118 reg.pitch = frame->linesize[0];
1119 reg.resourceToRegister = frame->data[0];
1121 ret = nv->nvEncRegisterResource(ctx->nvenc_ctx, ®);
1122 if (ret != NV_ENC_SUCCESS) {
1123 nvenc_print_error(avctx, ret, "Error registering an input resource");
1124 return AVERROR_UNKNOWN;
1127 ctx->registered_frames[idx].ptr = (CUdeviceptr)frame->data[0];
1128 ctx->registered_frames[idx].regptr = reg.registeredResource;
1132 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1133 NVENCFrame *nvenc_frame)
1135 NVENCContext *ctx = avctx->priv_data;
1136 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1139 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1142 ret = nvenc_register_frame(avctx, frame);
1144 av_log(avctx, AV_LOG_ERROR, "Could not register an input CUDA frame\n");
1149 ret = av_frame_ref(nvenc_frame->in_ref, frame);
1153 nvenc_frame->in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1154 nvenc_frame->in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1156 ret = nv->nvEncMapInputResource(ctx->nvenc_ctx, &nvenc_frame->in_map);
1157 if (ret != NV_ENC_SUCCESS) {
1158 av_frame_unref(nvenc_frame->in_ref);
1159 return nvenc_print_error(avctx, ret, "Error mapping an input resource");
1162 ctx->registered_frames[reg_idx].mapped = 1;
1163 nvenc_frame->reg_idx = reg_idx;
1164 nvenc_frame->in = nvenc_frame->in_map.mappedResource;
1166 NV_ENC_LOCK_INPUT_BUFFER params = { 0 };
1168 params.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1169 params.inputBuffer = nvenc_frame->in;
1171 ret = nv->nvEncLockInputBuffer(ctx->nvenc_ctx, ¶ms);
1172 if (ret != NV_ENC_SUCCESS)
1173 return nvenc_print_error(avctx, ret, "Cannot lock the buffer");
1175 ret = nvenc_copy_frame(¶ms, frame);
1177 nv->nvEncUnlockInputBuffer(ctx->nvenc_ctx, nvenc_frame->in);
1181 ret = nv->nvEncUnlockInputBuffer(ctx->nvenc_ctx, nvenc_frame->in);
1182 if (ret != NV_ENC_SUCCESS)
1183 return nvenc_print_error(avctx, ret, "Cannot unlock the buffer");
1189 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1190 NV_ENC_PIC_PARAMS *params)
1192 NVENCContext *ctx = avctx->priv_data;
1194 switch (avctx->codec->id) {
1195 case AV_CODEC_ID_H264:
1196 params->codecPicParams.h264PicParams.sliceMode =
1197 ctx->config.encodeCodecConfig.h264Config.sliceMode;
1198 params->codecPicParams.h264PicParams.sliceModeData =
1199 ctx->config.encodeCodecConfig.h264Config.sliceModeData;
1201 case AV_CODEC_ID_HEVC:
1202 params->codecPicParams.hevcPicParams.sliceMode =
1203 ctx->config.encodeCodecConfig.hevcConfig.sliceMode;
1204 params->codecPicParams.hevcPicParams.sliceModeData =
1205 ctx->config.encodeCodecConfig.hevcConfig.sliceModeData;
1210 static inline int nvenc_enqueue_timestamp(AVFifoBuffer *f, int64_t pts)
1212 return av_fifo_generic_write(f, &pts, sizeof(pts), NULL);
1215 static inline int nvenc_dequeue_timestamp(AVFifoBuffer *f, int64_t *pts)
1217 return av_fifo_generic_read(f, pts, sizeof(*pts), NULL);
1220 static int nvenc_set_timestamp(AVCodecContext *avctx,
1221 NV_ENC_LOCK_BITSTREAM *params,
1224 NVENCContext *ctx = avctx->priv_data;
1226 pkt->pts = params->outputTimeStamp;
1227 pkt->duration = params->outputDuration;
1229 /* generate the first dts by linearly extrapolating the
1230 * first two pts values to the past */
1231 if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
1232 ctx->initial_pts[1] != AV_NOPTS_VALUE) {
1233 int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
1236 if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
1237 (ts0 > 0 && ts1 < INT64_MIN + ts0))
1238 return AVERROR(ERANGE);
1241 if ((delta < 0 && ts0 > INT64_MAX + delta) ||
1242 (delta > 0 && ts0 < INT64_MIN + delta))
1243 return AVERROR(ERANGE);
1244 pkt->dts = ts0 - delta;
1246 ctx->first_packet_output = 1;
1249 return nvenc_dequeue_timestamp(ctx->timestamps, &pkt->dts);
1252 static int nvenc_get_output(AVCodecContext *avctx, AVPacket *pkt)
1254 NVENCContext *ctx = avctx->priv_data;
1255 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1256 NV_ENC_LOCK_BITSTREAM params = { 0 };
1260 ret = av_fifo_generic_read(ctx->ready, &frame, sizeof(frame), NULL);
1264 params.version = NV_ENC_LOCK_BITSTREAM_VER;
1265 params.outputBitstream = frame->out;
1267 ret = nv->nvEncLockBitstream(ctx->nvenc_ctx, ¶ms);
1269 return nvenc_print_error(avctx, ret, "Cannot lock the bitstream");
1271 ret = ff_alloc_packet(pkt, params.bitstreamSizeInBytes);
1275 memcpy(pkt->data, params.bitstreamBufferPtr, pkt->size);
1277 ret = nv->nvEncUnlockBitstream(ctx->nvenc_ctx, frame->out);
1279 return nvenc_print_error(avctx, ret, "Cannot unlock the bitstream");
1281 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1282 nv->nvEncUnmapInputResource(ctx->nvenc_ctx, frame->in_map.mappedResource);
1283 av_frame_unref(frame->in_ref);
1284 ctx->registered_frames[frame->reg_idx].mapped = 0;
1291 ret = nvenc_set_timestamp(avctx, ¶ms, pkt);
1295 switch (params.pictureType) {
1296 case NV_ENC_PIC_TYPE_IDR:
1297 pkt->flags |= AV_PKT_FLAG_KEY;
1298 #if FF_API_CODED_FRAME
1299 FF_DISABLE_DEPRECATION_WARNINGS
1300 case NV_ENC_PIC_TYPE_INTRA_REFRESH:
1301 case NV_ENC_PIC_TYPE_I:
1302 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
1304 case NV_ENC_PIC_TYPE_P:
1305 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
1307 case NV_ENC_PIC_TYPE_B:
1308 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;
1310 case NV_ENC_PIC_TYPE_BI:
1311 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_BI;
1313 FF_ENABLE_DEPRECATION_WARNINGS
1320 static int output_ready(AVCodecContext *avctx, int flush)
1322 NVENCContext *ctx = avctx->priv_data;
1323 int nb_ready, nb_pending;
1325 /* when B-frames are enabled, we wait for two initial timestamps to
1326 * calculate the first dts */
1327 if (!flush && avctx->max_b_frames > 0 &&
1328 (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
1331 nb_ready = av_fifo_size(ctx->ready) / sizeof(NVENCFrame*);
1332 nb_pending = av_fifo_size(ctx->pending) / sizeof(NVENCFrame*);
1334 return nb_ready > 0;
1335 return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
1338 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1339 const AVFrame *frame, int *got_packet)
1341 NVENCContext *ctx = avctx->priv_data;
1342 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1343 NV_ENC_PIC_PARAMS params = { 0 };
1344 NVENCFrame *nvenc_frame = NULL;
1347 params.version = NV_ENC_PIC_PARAMS_VER;
1350 nvenc_frame = get_free_frame(ctx);
1352 av_log(avctx, AV_LOG_ERROR, "No free surfaces\n");
1356 ret = nvenc_upload_frame(avctx, frame, nvenc_frame);
1360 params.inputBuffer = nvenc_frame->in;
1361 params.bufferFmt = nvenc_frame->format;
1362 params.inputWidth = frame->width;
1363 params.inputHeight = frame->height;
1364 params.outputBitstream = nvenc_frame->out;
1365 params.inputTimeStamp = frame->pts;
1367 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1368 if (frame->top_field_first)
1369 params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
1371 params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
1373 params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1376 nvenc_codec_specific_pic_params(avctx, ¶ms);
1378 ret = nvenc_enqueue_timestamp(ctx->timestamps, frame->pts);
1382 if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
1383 ctx->initial_pts[0] = frame->pts;
1384 else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
1385 ctx->initial_pts[1] = frame->pts;
1387 params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1390 enc_ret = nv->nvEncEncodePicture(ctx->nvenc_ctx, ¶ms);
1391 if (enc_ret != NV_ENC_SUCCESS &&
1392 enc_ret != NV_ENC_ERR_NEED_MORE_INPUT)
1393 return nvenc_print_error(avctx, enc_ret, "Error encoding the frame");
1396 ret = av_fifo_generic_write(ctx->pending, &nvenc_frame, sizeof(nvenc_frame), NULL);
1401 /* all the pending buffers are now ready for output */
1402 if (enc_ret == NV_ENC_SUCCESS) {
1403 while (av_fifo_size(ctx->pending) > 0) {
1404 av_fifo_generic_read(ctx->pending, &nvenc_frame, sizeof(nvenc_frame), NULL);
1405 av_fifo_generic_write(ctx->ready, &nvenc_frame, sizeof(nvenc_frame), NULL);
1409 if (output_ready(avctx, !frame)) {
1410 ret = nvenc_get_output(avctx, pkt);