3 * Copyright (C) 2015 Luca Barbato
4 * Copyright (C) 2015 Philip Langdale <philipl@overt.org>
5 * Copyright (C) 2014 Timo Rothenpieler <timo@rothenpieler.org>
7 * This file is part of Libav.
9 * Libav is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * Libav is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with Libav; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 #include <nvEncodeAPI.h>
29 #define CUDA_LIBNAME "libcuda.so"
34 #define NVENC_LIBNAME "libnvidia-encode.so"
40 #define NVENC_LIBNAME "nvEncodeAPI64.dll"
42 #define NVENC_LIBNAME "nvEncodeAPI.dll"
45 #define dlopen(filename, flags) LoadLibrary((filename))
46 #define dlsym(handle, symbol) GetProcAddress(handle, symbol)
47 #define dlclose(handle) FreeLibrary(handle)
50 #include "libavutil/common.h"
51 #include "libavutil/hwcontext.h"
52 #include "libavutil/imgutils.h"
53 #include "libavutil/mem.h"
59 #include "libavutil/hwcontext_cuda.h"
62 #define NVENC_CAP 0x30
63 #define BITSTREAM_BUFFER_SIZE 1024 * 1024
64 #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR || \
65 rc == NV_ENC_PARAMS_RC_2_PASS_QUALITY || \
66 rc == NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP)
68 #define LOAD_LIBRARY(l, path) \
70 if (!((l) = dlopen(path, RTLD_LAZY))) { \
71 av_log(avctx, AV_LOG_ERROR, \
74 return AVERROR_UNKNOWN; \
78 #define LOAD_SYMBOL(fun, lib, symbol) \
80 if (!((fun) = dlsym(lib, symbol))) { \
81 av_log(avctx, AV_LOG_ERROR, \
84 return AVERROR_UNKNOWN; \
88 const enum AVPixelFormat ff_nvenc_pix_fmts[] = {
103 { NV_ENC_SUCCESS, 0, "success" },
104 { NV_ENC_ERR_NO_ENCODE_DEVICE, AVERROR(ENOENT), "no encode device" },
105 { NV_ENC_ERR_UNSUPPORTED_DEVICE, AVERROR(ENOSYS), "unsupported device" },
106 { NV_ENC_ERR_INVALID_ENCODERDEVICE, AVERROR(EINVAL), "invalid encoder device" },
107 { NV_ENC_ERR_INVALID_DEVICE, AVERROR(EINVAL), "invalid device" },
108 { NV_ENC_ERR_DEVICE_NOT_EXIST, AVERROR(EIO), "device does not exist" },
109 { NV_ENC_ERR_INVALID_PTR, AVERROR(EFAULT), "invalid ptr" },
110 { NV_ENC_ERR_INVALID_EVENT, AVERROR(EINVAL), "invalid event" },
111 { NV_ENC_ERR_INVALID_PARAM, AVERROR(EINVAL), "invalid param" },
112 { NV_ENC_ERR_INVALID_CALL, AVERROR(EINVAL), "invalid call" },
113 { NV_ENC_ERR_OUT_OF_MEMORY, AVERROR(ENOMEM), "out of memory" },
114 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED, AVERROR(EINVAL), "encoder not initialized" },
115 { NV_ENC_ERR_UNSUPPORTED_PARAM, AVERROR(ENOSYS), "unsupported param" },
116 { NV_ENC_ERR_LOCK_BUSY, AVERROR(EAGAIN), "lock busy" },
117 { NV_ENC_ERR_NOT_ENOUGH_BUFFER, AVERROR(ENOBUFS), "not enough buffer" },
118 { NV_ENC_ERR_INVALID_VERSION, AVERROR(EINVAL), "invalid version" },
119 { NV_ENC_ERR_MAP_FAILED, AVERROR(EIO), "map failed" },
120 { NV_ENC_ERR_NEED_MORE_INPUT, AVERROR(EAGAIN), "need more input" },
121 { NV_ENC_ERR_ENCODER_BUSY, AVERROR(EAGAIN), "encoder busy" },
122 { NV_ENC_ERR_EVENT_NOT_REGISTERD, AVERROR(EBADF), "event not registered" },
123 { NV_ENC_ERR_GENERIC, AVERROR_UNKNOWN, "generic error" },
124 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY, AVERROR(EINVAL), "incompatible client key" },
125 { NV_ENC_ERR_UNIMPLEMENTED, AVERROR(ENOSYS), "unimplemented" },
126 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO), "resource register failed" },
127 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED, AVERROR(EBADF), "resource not registered" },
128 { NV_ENC_ERR_RESOURCE_NOT_MAPPED, AVERROR(EBADF), "resource not mapped" },
131 static int nvenc_map_error(NVENCSTATUS err, const char **desc)
134 for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
135 if (nvenc_errors[i].nverr == err) {
137 *desc = nvenc_errors[i].desc;
138 return nvenc_errors[i].averr;
142 *desc = "unknown error";
143 return AVERROR_UNKNOWN;
146 static int nvenc_print_error(void *log_ctx, NVENCSTATUS err,
147 const char *error_string)
151 ret = nvenc_map_error(err, &desc);
152 av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
156 static av_cold int nvenc_load_libraries(AVCodecContext *avctx)
158 NVENCContext *ctx = avctx->priv_data;
159 NVENCLibraryContext *nvel = &ctx->nvel;
160 PNVENCODEAPICREATEINSTANCE nvenc_create_instance;
164 nvel->cu_init = cuInit;
165 nvel->cu_device_get_count = cuDeviceGetCount;
166 nvel->cu_device_get = cuDeviceGet;
167 nvel->cu_device_get_name = cuDeviceGetName;
168 nvel->cu_device_compute_capability = cuDeviceComputeCapability;
169 nvel->cu_ctx_create = cuCtxCreate_v2;
170 nvel->cu_ctx_pop_current = cuCtxPopCurrent_v2;
171 nvel->cu_ctx_destroy = cuCtxDestroy_v2;
173 LOAD_LIBRARY(nvel->cuda, CUDA_LIBNAME);
175 LOAD_SYMBOL(nvel->cu_init, nvel->cuda, "cuInit");
176 LOAD_SYMBOL(nvel->cu_device_get_count, nvel->cuda, "cuDeviceGetCount");
177 LOAD_SYMBOL(nvel->cu_device_get, nvel->cuda, "cuDeviceGet");
178 LOAD_SYMBOL(nvel->cu_device_get_name, nvel->cuda, "cuDeviceGetName");
179 LOAD_SYMBOL(nvel->cu_device_compute_capability, nvel->cuda,
180 "cuDeviceComputeCapability");
181 LOAD_SYMBOL(nvel->cu_ctx_create, nvel->cuda, "cuCtxCreate_v2");
182 LOAD_SYMBOL(nvel->cu_ctx_pop_current, nvel->cuda, "cuCtxPopCurrent_v2");
183 LOAD_SYMBOL(nvel->cu_ctx_destroy, nvel->cuda, "cuCtxDestroy_v2");
186 LOAD_LIBRARY(nvel->nvenc, NVENC_LIBNAME);
188 LOAD_SYMBOL(nvenc_create_instance, nvel->nvenc,
189 "NvEncodeAPICreateInstance");
191 nvel->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
193 err = nvenc_create_instance(&nvel->nvenc_funcs);
194 if (err != NV_ENC_SUCCESS)
195 return nvenc_print_error(avctx, err, "Cannot create the NVENC instance");
200 static int nvenc_open_session(AVCodecContext *avctx)
202 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
203 NVENCContext *ctx = avctx->priv_data;
204 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
207 params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
208 params.apiVersion = NVENCAPI_VERSION;
209 params.device = ctx->cu_context;
210 params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
212 ret = nv->nvEncOpenEncodeSessionEx(¶ms, &ctx->nvenc_ctx);
213 if (ret != NV_ENC_SUCCESS) {
214 ctx->nvenc_ctx = NULL;
215 return nvenc_print_error(avctx, ret, "Cannot open the NVENC Session");
221 static int nvenc_check_codec_support(AVCodecContext *avctx)
223 NVENCContext *ctx = avctx->priv_data;
224 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
225 int i, ret, count = 0;
228 ret = nv->nvEncGetEncodeGUIDCount(ctx->nvenc_ctx, &count);
230 if (ret != NV_ENC_SUCCESS || !count)
231 return AVERROR(ENOSYS);
233 guids = av_malloc(count * sizeof(GUID));
235 return AVERROR(ENOMEM);
237 ret = nv->nvEncGetEncodeGUIDs(ctx->nvenc_ctx, guids, count, &count);
238 if (ret != NV_ENC_SUCCESS) {
239 ret = AVERROR(ENOSYS);
243 ret = AVERROR(ENOSYS);
244 for (i = 0; i < count; i++) {
245 if (!memcmp(&guids[i], &ctx->params.encodeGUID, sizeof(*guids))) {
257 static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
259 NVENCContext *ctx = avctx->priv_data;
260 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
261 NV_ENC_CAPS_PARAM params = { 0 };
264 params.version = NV_ENC_CAPS_PARAM_VER;
265 params.capsToQuery = cap;
267 ret = nv->nvEncGetEncodeCaps(ctx->nvenc_ctx, ctx->params.encodeGUID, ¶ms, &val);
269 if (ret == NV_ENC_SUCCESS)
274 static int nvenc_check_capabilities(AVCodecContext *avctx)
276 NVENCContext *ctx = avctx->priv_data;
279 ret = nvenc_check_codec_support(avctx);
281 av_log(avctx, AV_LOG_VERBOSE, "Codec not supported\n");
285 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
286 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P && ret <= 0) {
287 av_log(avctx, AV_LOG_VERBOSE, "YUV444P not supported\n");
288 return AVERROR(ENOSYS);
291 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
292 if (ret < avctx->width) {
293 av_log(avctx, AV_LOG_VERBOSE, "Width %d exceeds %d\n",
295 return AVERROR(ENOSYS);
298 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
299 if (ret < avctx->height) {
300 av_log(avctx, AV_LOG_VERBOSE, "Height %d exceeds %d\n",
302 return AVERROR(ENOSYS);
305 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
306 if (ret < avctx->max_b_frames) {
307 av_log(avctx, AV_LOG_VERBOSE, "Max B-frames %d exceed %d\n",
308 avctx->max_b_frames, ret);
310 return AVERROR(ENOSYS);
316 static int nvenc_check_device(AVCodecContext *avctx, int idx)
318 NVENCContext *ctx = avctx->priv_data;
319 NVENCLibraryContext *nvel = &ctx->nvel;
320 char name[128] = { 0 };
321 int major, minor, ret;
324 int loglevel = AV_LOG_VERBOSE;
326 if (ctx->device == LIST_DEVICES)
327 loglevel = AV_LOG_INFO;
329 ret = nvel->cu_device_get(&cu_device, idx);
330 if (ret != CUDA_SUCCESS) {
331 av_log(avctx, AV_LOG_ERROR,
332 "Cannot access the CUDA device %d\n",
337 ret = nvel->cu_device_get_name(name, sizeof(name), cu_device);
338 if (ret != CUDA_SUCCESS)
341 ret = nvel->cu_device_compute_capability(&major, &minor, cu_device);
342 if (ret != CUDA_SUCCESS)
345 av_log(avctx, loglevel, "Device %d [%s] ", cu_device, name);
347 if (((major << 4) | minor) < NVENC_CAP)
350 ret = nvel->cu_ctx_create(&ctx->cu_context_internal, 0, cu_device);
351 if (ret != CUDA_SUCCESS)
354 ctx->cu_context = ctx->cu_context_internal;
356 ret = nvel->cu_ctx_pop_current(&dummy);
357 if (ret != CUDA_SUCCESS)
360 if ((ret = nvenc_open_session(avctx)) < 0)
363 if ((ret = nvenc_check_capabilities(avctx)) < 0)
366 av_log(avctx, loglevel, "supports NVENC\n");
368 if (ctx->device == cu_device || ctx->device == ANY_DEVICE)
372 nvel->nvenc_funcs.nvEncDestroyEncoder(ctx->nvenc_ctx);
373 ctx->nvenc_ctx = NULL;
376 nvel->cu_ctx_destroy(ctx->cu_context_internal);
377 ctx->cu_context_internal = NULL;
381 av_log(avctx, loglevel, "does not support NVENC (major %d minor %d)\n",
384 return AVERROR(ENOSYS);
387 static int nvenc_setup_device(AVCodecContext *avctx)
389 NVENCContext *ctx = avctx->priv_data;
390 NVENCLibraryContext *nvel = &ctx->nvel;
392 switch (avctx->codec->id) {
393 case AV_CODEC_ID_H264:
394 ctx->params.encodeGUID = NV_ENC_CODEC_H264_GUID;
396 case AV_CODEC_ID_HEVC:
397 ctx->params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
403 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
405 AVHWFramesContext *frames_ctx;
406 AVCUDADeviceContext *device_hwctx;
409 if (!avctx->hw_frames_ctx)
410 return AVERROR(EINVAL);
412 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
413 device_hwctx = frames_ctx->device_ctx->hwctx;
415 ctx->cu_context = device_hwctx->cuda_ctx;
417 ret = nvenc_open_session(avctx);
421 ret = nvenc_check_capabilities(avctx);
428 int i, nb_devices = 0;
430 if ((nvel->cu_init(0)) != CUDA_SUCCESS) {
431 av_log(avctx, AV_LOG_ERROR,
432 "Cannot init CUDA\n");
433 return AVERROR_UNKNOWN;
436 if ((nvel->cu_device_get_count(&nb_devices)) != CUDA_SUCCESS) {
437 av_log(avctx, AV_LOG_ERROR,
438 "Cannot enumerate the CUDA devices\n");
439 return AVERROR_UNKNOWN;
443 for (i = 0; i < nb_devices; ++i) {
444 if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
448 if (ctx->device == LIST_DEVICES)
451 return AVERROR(ENOSYS);
457 typedef struct GUIDTuple {
462 static int nvec_map_preset(NVENCContext *ctx)
464 GUIDTuple presets[] = {
465 { NV_ENC_PRESET_DEFAULT_GUID },
466 { NV_ENC_PRESET_HP_GUID },
467 { NV_ENC_PRESET_HQ_GUID },
468 { NV_ENC_PRESET_BD_GUID },
469 { NV_ENC_PRESET_LOW_LATENCY_DEFAULT_GUID, NVENC_LOWLATENCY },
470 { NV_ENC_PRESET_LOW_LATENCY_HP_GUID, NVENC_LOWLATENCY },
471 { NV_ENC_PRESET_LOW_LATENCY_HQ_GUID, NVENC_LOWLATENCY },
472 { NV_ENC_PRESET_LOSSLESS_DEFAULT_GUID, NVENC_LOSSLESS },
473 { NV_ENC_PRESET_LOSSLESS_HP_GUID, NVENC_LOSSLESS },
477 GUIDTuple *t = &presets[ctx->preset];
479 ctx->params.presetGUID = t->guid;
480 ctx->flags = t->flags;
482 return AVERROR(EINVAL);
485 static void set_constqp(AVCodecContext *avctx, NV_ENC_RC_PARAMS *rc)
487 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
488 rc->constQP.qpInterB = avctx->global_quality;
489 rc->constQP.qpInterP = avctx->global_quality;
490 rc->constQP.qpIntra = avctx->global_quality;
493 static void set_vbr(AVCodecContext *avctx, NV_ENC_RC_PARAMS *rc)
495 if (avctx->qmin >= 0) {
497 rc->minQP.qpInterB = avctx->qmin;
498 rc->minQP.qpInterP = avctx->qmin;
499 rc->minQP.qpIntra = avctx->qmin;
502 if (avctx->qmax >= 0) {
504 rc->maxQP.qpInterB = avctx->qmax;
505 rc->maxQP.qpInterP = avctx->qmax;
506 rc->maxQP.qpIntra = avctx->qmax;
510 static void set_lossless(AVCodecContext *avctx, NV_ENC_RC_PARAMS *rc)
512 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
513 rc->constQP.qpInterB = 0;
514 rc->constQP.qpInterP = 0;
515 rc->constQP.qpIntra = 0;
518 static void nvenc_override_rate_control(AVCodecContext *avctx,
519 NV_ENC_RC_PARAMS *rc)
521 NVENCContext *ctx = avctx->priv_data;
524 case NV_ENC_PARAMS_RC_CONSTQP:
525 if (avctx->global_quality < 0) {
526 av_log(avctx, AV_LOG_WARNING,
527 "The constant quality rate-control requires "
528 "the 'global_quality' option set.\n");
531 set_constqp(avctx, rc);
533 case NV_ENC_PARAMS_RC_2_PASS_VBR:
534 case NV_ENC_PARAMS_RC_VBR:
535 if (avctx->qmin < 0 && avctx->qmax < 0) {
536 av_log(avctx, AV_LOG_WARNING,
537 "The variable bitrate rate-control requires "
538 "the 'qmin' and/or 'qmax' option set.\n");
541 case NV_ENC_PARAMS_RC_VBR_MINQP:
542 if (avctx->qmin < 0) {
543 av_log(avctx, AV_LOG_WARNING,
544 "The variable bitrate rate-control requires "
545 "the 'qmin' option set.\n");
550 case NV_ENC_PARAMS_RC_CBR:
552 case NV_ENC_PARAMS_RC_2_PASS_QUALITY:
553 case NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP:
554 if (!(ctx->flags & NVENC_LOWLATENCY)) {
555 av_log(avctx, AV_LOG_WARNING,
556 "The multipass rate-control requires "
557 "a low-latency preset.\n");
562 rc->rateControlMode = ctx->rc;
565 static void nvenc_setup_rate_control(AVCodecContext *avctx)
567 NVENCContext *ctx = avctx->priv_data;
568 NV_ENC_RC_PARAMS *rc = &ctx->config.rcParams;
570 if (avctx->bit_rate > 0)
571 rc->averageBitRate = avctx->bit_rate;
573 if (avctx->rc_max_rate > 0)
574 rc->maxBitRate = avctx->rc_max_rate;
577 nvenc_override_rate_control(avctx, rc);
578 } else if (ctx->flags & NVENC_LOSSLESS) {
579 set_lossless(avctx, rc);
580 } else if (avctx->global_quality > 0) {
581 set_constqp(avctx, rc);
582 } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
583 rc->rateControlMode = NV_ENC_PARAMS_RC_VBR;
587 if (avctx->rc_buffer_size > 0)
588 rc->vbvBufferSize = avctx->rc_buffer_size;
590 if (rc->averageBitRate > 0)
591 avctx->bit_rate = rc->averageBitRate;
594 static int nvenc_setup_h264_config(AVCodecContext *avctx)
596 NVENCContext *ctx = avctx->priv_data;
597 NV_ENC_CONFIG *cc = &ctx->config;
598 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
599 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
601 vui->colourDescriptionPresentFlag = avctx->colorspace != AVCOL_SPC_UNSPECIFIED ||
602 avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
603 avctx->color_trc != AVCOL_TRC_UNSPECIFIED;
605 vui->colourMatrix = avctx->colorspace;
606 vui->colourPrimaries = avctx->color_primaries;
607 vui->transferCharacteristics = avctx->color_trc;
609 vui->videoFullRangeFlag = avctx->color_range == AVCOL_RANGE_JPEG;
611 vui->videoSignalTypePresentFlag = vui->colourDescriptionPresentFlag ||
612 vui->videoFullRangeFlag;
614 h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
615 h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
618 h264->maxNumRefFrames = avctx->refs;
619 h264->idrPeriod = cc->gopLength;
622 h264->sliceModeData = FFMAX(avctx->slices, 1);
624 if (ctx->flags & NVENC_LOSSLESS)
625 h264->qpPrimeYZeroTransformBypassFlag = 1;
627 if (IS_CBR(cc->rcParams.rateControlMode)) {
628 h264->outputBufferingPeriodSEI = 1;
629 h264->outputPictureTimingSEI = 1;
633 avctx->profile = ctx->profile;
635 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P)
636 h264->chromaFormatIDC = 3;
638 h264->chromaFormatIDC = 1;
640 switch (ctx->profile) {
641 case NV_ENC_H264_PROFILE_BASELINE:
642 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
644 case NV_ENC_H264_PROFILE_MAIN:
645 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
647 case NV_ENC_H264_PROFILE_HIGH:
648 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
650 case NV_ENC_H264_PROFILE_HIGH_444:
651 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
653 case NV_ENC_H264_PROFILE_CONSTRAINED_HIGH:
654 cc->profileGUID = NV_ENC_H264_PROFILE_CONSTRAINED_HIGH_GUID;
658 h264->level = ctx->level;
663 static int nvenc_setup_hevc_config(AVCodecContext *avctx)
665 NVENCContext *ctx = avctx->priv_data;
666 NV_ENC_CONFIG *cc = &ctx->config;
667 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
668 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
670 vui->colourDescriptionPresentFlag = avctx->colorspace != AVCOL_SPC_UNSPECIFIED ||
671 avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
672 avctx->color_trc != AVCOL_TRC_UNSPECIFIED;
674 vui->colourMatrix = avctx->colorspace;
675 vui->colourPrimaries = avctx->color_primaries;
676 vui->transferCharacteristics = avctx->color_trc;
678 vui->videoFullRangeFlag = avctx->color_range == AVCOL_RANGE_JPEG;
680 vui->videoSignalTypePresentFlag = vui->colourDescriptionPresentFlag ||
681 vui->videoFullRangeFlag;
683 hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
684 hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
687 hevc->maxNumRefFramesInDPB = avctx->refs;
688 hevc->idrPeriod = cc->gopLength;
690 if (IS_CBR(cc->rcParams.rateControlMode)) {
691 hevc->outputBufferingPeriodSEI = 1;
692 hevc->outputPictureTimingSEI = 1;
695 /* No other profile is supported in the current SDK version 5 */
696 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
697 avctx->profile = FF_PROFILE_HEVC_MAIN;
700 hevc->sliceModeData = FFMAX(avctx->slices, 1);
703 hevc->level = ctx->level;
705 hevc->level = NV_ENC_LEVEL_AUTOSELECT;
709 hevc->tier = ctx->tier;
714 static int nvenc_setup_codec_config(AVCodecContext *avctx)
716 switch (avctx->codec->id) {
717 case AV_CODEC_ID_H264:
718 return nvenc_setup_h264_config(avctx);
719 case AV_CODEC_ID_HEVC:
720 return nvenc_setup_hevc_config(avctx);
725 static int nvenc_setup_encoder(AVCodecContext *avctx)
727 NVENCContext *ctx = avctx->priv_data;
728 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
729 NV_ENC_PRESET_CONFIG preset_cfg = { 0 };
730 AVCPBProperties *cpb_props;
733 ctx->params.version = NV_ENC_INITIALIZE_PARAMS_VER;
735 ctx->params.encodeHeight = avctx->height;
736 ctx->params.encodeWidth = avctx->width;
738 if (avctx->sample_aspect_ratio.num &&
739 avctx->sample_aspect_ratio.den &&
740 (avctx->sample_aspect_ratio.num != 1 ||
741 avctx->sample_aspect_ratio.den != 1)) {
742 av_reduce(&ctx->params.darWidth,
743 &ctx->params.darHeight,
744 avctx->width * avctx->sample_aspect_ratio.num,
745 avctx->height * avctx->sample_aspect_ratio.den,
748 ctx->params.darHeight = avctx->height;
749 ctx->params.darWidth = avctx->width;
752 // De-compensate for hardware, dubiously, trying to compensate for
753 // playback at 704 pixel width.
754 if (avctx->width == 720 && (avctx->height == 480 || avctx->height == 576)) {
755 av_reduce(&ctx->params.darWidth, &ctx->params.darHeight,
756 ctx->params.darWidth * 44,
757 ctx->params.darHeight * 45,
761 ctx->params.frameRateNum = avctx->time_base.den;
762 ctx->params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
764 ctx->params.enableEncodeAsync = 0;
765 ctx->params.enablePTD = 1;
767 ctx->params.encodeConfig = &ctx->config;
769 nvec_map_preset(ctx);
771 preset_cfg.version = NV_ENC_PRESET_CONFIG_VER;
772 preset_cfg.presetCfg.version = NV_ENC_CONFIG_VER;
774 ret = nv->nvEncGetEncodePresetConfig(ctx->nvenc_ctx,
775 ctx->params.encodeGUID,
776 ctx->params.presetGUID,
778 if (ret != NV_ENC_SUCCESS)
779 return nvenc_print_error(avctx, ret, "Cannot get the preset configuration");
781 memcpy(&ctx->config, &preset_cfg.presetCfg, sizeof(ctx->config));
783 ctx->config.version = NV_ENC_CONFIG_VER;
785 if (avctx->gop_size > 0) {
786 if (avctx->max_b_frames > 0) {
790 * 3 two B-frames, and so on. */
791 ctx->config.frameIntervalP = avctx->max_b_frames + 1;
792 } else if (avctx->max_b_frames == 0) {
793 ctx->config.frameIntervalP = 1;
795 ctx->config.gopLength = avctx->gop_size;
796 } else if (avctx->gop_size == 0) {
797 ctx->config.frameIntervalP = 0;
798 ctx->config.gopLength = 1;
801 if (ctx->config.frameIntervalP > 1)
802 avctx->max_b_frames = ctx->config.frameIntervalP - 1;
804 ctx->initial_pts[0] = AV_NOPTS_VALUE;
805 ctx->initial_pts[1] = AV_NOPTS_VALUE;
807 nvenc_setup_rate_control(avctx);
809 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
810 ctx->config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
812 ctx->config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
815 if ((ret = nvenc_setup_codec_config(avctx)) < 0)
818 ret = nv->nvEncInitializeEncoder(ctx->nvenc_ctx, &ctx->params);
819 if (ret != NV_ENC_SUCCESS)
820 return nvenc_print_error(avctx, ret, "Cannot initialize the decoder");
822 cpb_props = ff_add_cpb_side_data(avctx);
824 return AVERROR(ENOMEM);
825 cpb_props->max_bitrate = avctx->rc_max_rate;
826 cpb_props->min_bitrate = avctx->rc_min_rate;
827 cpb_props->avg_bitrate = avctx->bit_rate;
828 cpb_props->buffer_size = avctx->rc_buffer_size;
833 static int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
835 NVENCContext *ctx = avctx->priv_data;
836 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
838 NV_ENC_CREATE_BITSTREAM_BUFFER out_buffer = { 0 };
840 switch (ctx->data_pix_fmt) {
841 case AV_PIX_FMT_YUV420P:
842 ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YV12_PL;
844 case AV_PIX_FMT_NV12:
845 ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_NV12_PL;
847 case AV_PIX_FMT_YUV444P:
848 ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YUV444_PL;
854 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
855 ctx->frames[idx].in_ref = av_frame_alloc();
856 if (!ctx->frames[idx].in_ref)
857 return AVERROR(ENOMEM);
859 NV_ENC_CREATE_INPUT_BUFFER in_buffer = { 0 };
861 in_buffer.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
863 in_buffer.width = avctx->width;
864 in_buffer.height = avctx->height;
866 in_buffer.bufferFmt = ctx->frames[idx].format;
867 in_buffer.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED;
869 ret = nv->nvEncCreateInputBuffer(ctx->nvenc_ctx, &in_buffer);
870 if (ret != NV_ENC_SUCCESS)
871 return nvenc_print_error(avctx, ret, "CreateInputBuffer failed");
873 ctx->frames[idx].in = in_buffer.inputBuffer;
876 out_buffer.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
877 /* 1MB is large enough to hold most output frames.
878 * NVENC increases this automatically if it is not enough. */
879 out_buffer.size = BITSTREAM_BUFFER_SIZE;
881 out_buffer.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED;
883 ret = nv->nvEncCreateBitstreamBuffer(ctx->nvenc_ctx, &out_buffer);
884 if (ret != NV_ENC_SUCCESS)
885 return nvenc_print_error(avctx, ret, "CreateBitstreamBuffer failed");
887 ctx->frames[idx].out = out_buffer.bitstreamBuffer;
892 static int nvenc_setup_surfaces(AVCodecContext *avctx)
894 NVENCContext *ctx = avctx->priv_data;
897 ctx->nb_surfaces = FFMAX(4 + avctx->max_b_frames,
899 ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
902 ctx->frames = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->frames));
904 return AVERROR(ENOMEM);
906 ctx->timestamps = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
907 if (!ctx->timestamps)
908 return AVERROR(ENOMEM);
909 ctx->pending = av_fifo_alloc(ctx->nb_surfaces * sizeof(*ctx->frames));
911 return AVERROR(ENOMEM);
912 ctx->ready = av_fifo_alloc(ctx->nb_surfaces * sizeof(*ctx->frames));
914 return AVERROR(ENOMEM);
916 for (i = 0; i < ctx->nb_surfaces; i++) {
917 if ((ret = nvenc_alloc_surface(avctx, i)) < 0)
924 #define EXTRADATA_SIZE 512
926 static int nvenc_setup_extradata(AVCodecContext *avctx)
928 NVENCContext *ctx = avctx->priv_data;
929 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
930 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
933 avctx->extradata = av_mallocz(EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
934 if (!avctx->extradata)
935 return AVERROR(ENOMEM);
937 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
938 payload.spsppsBuffer = avctx->extradata;
939 payload.inBufferSize = EXTRADATA_SIZE;
940 payload.outSPSPPSPayloadSize = &avctx->extradata_size;
942 ret = nv->nvEncGetSequenceParams(ctx->nvenc_ctx, &payload);
943 if (ret != NV_ENC_SUCCESS)
944 return nvenc_print_error(avctx, ret, "Cannot get the extradata");
949 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
951 NVENCContext *ctx = avctx->priv_data;
952 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
955 /* the encoder has to be flushed before it can be closed */
956 if (ctx->nvenc_ctx) {
957 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
958 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
960 nv->nvEncEncodePicture(ctx->nvenc_ctx, ¶ms);
963 av_fifo_free(ctx->timestamps);
964 av_fifo_free(ctx->pending);
965 av_fifo_free(ctx->ready);
968 for (i = 0; i < ctx->nb_surfaces; ++i) {
969 if (avctx->pix_fmt != AV_PIX_FMT_CUDA) {
970 nv->nvEncDestroyInputBuffer(ctx->nvenc_ctx, ctx->frames[i].in);
971 } else if (ctx->frames[i].in) {
972 nv->nvEncUnmapInputResource(ctx->nvenc_ctx, ctx->frames[i].in_map.mappedResource);
975 av_frame_free(&ctx->frames[i].in_ref);
976 nv->nvEncDestroyBitstreamBuffer(ctx->nvenc_ctx, ctx->frames[i].out);
979 for (i = 0; i < ctx->nb_registered_frames; i++) {
980 if (ctx->registered_frames[i].regptr)
981 nv->nvEncUnregisterResource(ctx->nvenc_ctx, ctx->registered_frames[i].regptr);
983 ctx->nb_registered_frames = 0;
985 av_freep(&ctx->frames);
988 nv->nvEncDestroyEncoder(ctx->nvenc_ctx);
990 if (ctx->cu_context_internal)
991 ctx->nvel.cu_ctx_destroy(ctx->cu_context_internal);
994 dlclose(ctx->nvel.nvenc);
998 dlclose(ctx->nvel.cuda);
1004 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
1006 NVENCContext *ctx = avctx->priv_data;
1009 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1010 AVHWFramesContext *frames_ctx;
1011 if (!avctx->hw_frames_ctx) {
1012 av_log(avctx, AV_LOG_ERROR,
1013 "hw_frames_ctx must be set when using GPU frames as input\n");
1014 return AVERROR(EINVAL);
1016 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1017 ctx->data_pix_fmt = frames_ctx->sw_format;
1019 ctx->data_pix_fmt = avctx->pix_fmt;
1022 if ((ret = nvenc_load_libraries(avctx)) < 0)
1025 if ((ret = nvenc_setup_device(avctx)) < 0)
1028 if ((ret = nvenc_setup_encoder(avctx)) < 0)
1031 if ((ret = nvenc_setup_surfaces(avctx)) < 0)
1034 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1035 if ((ret = nvenc_setup_extradata(avctx)) < 0)
1042 static NVENCFrame *get_free_frame(NVENCContext *ctx)
1046 for (i = 0; i < ctx->nb_surfaces; i++) {
1047 if (!ctx->frames[i].locked) {
1048 ctx->frames[i].locked = 1;
1049 return &ctx->frames[i];
1056 static int nvenc_copy_frame(NV_ENC_LOCK_INPUT_BUFFER *in, const AVFrame *frame)
1058 uint8_t *buf = in->bufferDataPtr;
1059 int off = frame->height * in->pitch;
1061 switch (frame->format) {
1062 case AV_PIX_FMT_YUV420P:
1063 av_image_copy_plane(buf, in->pitch,
1064 frame->data[0], frame->linesize[0],
1065 frame->width, frame->height);
1068 av_image_copy_plane(buf, in->pitch >> 1,
1069 frame->data[2], frame->linesize[2],
1070 frame->width >> 1, frame->height >> 1);
1074 av_image_copy_plane(buf, in->pitch >> 1,
1075 frame->data[1], frame->linesize[1],
1076 frame->width >> 1, frame->height >> 1);
1078 case AV_PIX_FMT_NV12:
1079 av_image_copy_plane(buf, in->pitch,
1080 frame->data[0], frame->linesize[0],
1081 frame->width, frame->height);
1084 av_image_copy_plane(buf, in->pitch,
1085 frame->data[1], frame->linesize[1],
1086 frame->width, frame->height >> 1);
1088 case AV_PIX_FMT_YUV444P:
1089 av_image_copy_plane(buf, in->pitch,
1090 frame->data[0], frame->linesize[0],
1091 frame->width, frame->height);
1094 av_image_copy_plane(buf, in->pitch,
1095 frame->data[1], frame->linesize[1],
1096 frame->width, frame->height);
1099 av_image_copy_plane(buf, in->pitch,
1100 frame->data[2], frame->linesize[2],
1101 frame->width, frame->height);
1110 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1112 NVENCContext *ctx = avctx->priv_data;
1113 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1116 if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1117 for (i = 0; i < ctx->nb_registered_frames; i++) {
1118 if (!ctx->registered_frames[i].mapped) {
1119 if (ctx->registered_frames[i].regptr) {
1120 nv->nvEncUnregisterResource(ctx->nvenc_ctx,
1121 ctx->registered_frames[i].regptr);
1122 ctx->registered_frames[i].regptr = NULL;
1128 return ctx->nb_registered_frames++;
1131 av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1132 return AVERROR(ENOMEM);
1135 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1137 NVENCContext *ctx = avctx->priv_data;
1138 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1139 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1140 NV_ENC_REGISTER_RESOURCE reg;
1143 for (i = 0; i < ctx->nb_registered_frames; i++) {
1144 if (ctx->registered_frames[i].ptr == (CUdeviceptr)frame->data[0])
1148 idx = nvenc_find_free_reg_resource(avctx);
1152 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1153 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1154 reg.width = frames_ctx->width;
1155 reg.height = frames_ctx->height;
1156 reg.bufferFormat = ctx->frames[0].format;
1157 reg.pitch = frame->linesize[0];
1158 reg.resourceToRegister = frame->data[0];
1160 ret = nv->nvEncRegisterResource(ctx->nvenc_ctx, ®);
1161 if (ret != NV_ENC_SUCCESS) {
1162 nvenc_print_error(avctx, ret, "Error registering an input resource");
1163 return AVERROR_UNKNOWN;
1166 ctx->registered_frames[idx].ptr = (CUdeviceptr)frame->data[0];
1167 ctx->registered_frames[idx].regptr = reg.registeredResource;
1171 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1172 NVENCFrame *nvenc_frame)
1174 NVENCContext *ctx = avctx->priv_data;
1175 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1178 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1181 ret = nvenc_register_frame(avctx, frame);
1183 av_log(avctx, AV_LOG_ERROR, "Could not register an input CUDA frame\n");
1188 ret = av_frame_ref(nvenc_frame->in_ref, frame);
1192 nvenc_frame->in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1193 nvenc_frame->in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1195 ret = nv->nvEncMapInputResource(ctx->nvenc_ctx, &nvenc_frame->in_map);
1196 if (ret != NV_ENC_SUCCESS) {
1197 av_frame_unref(nvenc_frame->in_ref);
1198 return nvenc_print_error(avctx, ret, "Error mapping an input resource");
1201 ctx->registered_frames[reg_idx].mapped = 1;
1202 nvenc_frame->reg_idx = reg_idx;
1203 nvenc_frame->in = nvenc_frame->in_map.mappedResource;
1205 NV_ENC_LOCK_INPUT_BUFFER params = { 0 };
1207 params.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1208 params.inputBuffer = nvenc_frame->in;
1210 ret = nv->nvEncLockInputBuffer(ctx->nvenc_ctx, ¶ms);
1211 if (ret != NV_ENC_SUCCESS)
1212 return nvenc_print_error(avctx, ret, "Cannot lock the buffer");
1214 ret = nvenc_copy_frame(¶ms, frame);
1216 nv->nvEncUnlockInputBuffer(ctx->nvenc_ctx, nvenc_frame->in);
1220 ret = nv->nvEncUnlockInputBuffer(ctx->nvenc_ctx, nvenc_frame->in);
1221 if (ret != NV_ENC_SUCCESS)
1222 return nvenc_print_error(avctx, ret, "Cannot unlock the buffer");
1228 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1229 NV_ENC_PIC_PARAMS *params)
1231 NVENCContext *ctx = avctx->priv_data;
1233 switch (avctx->codec->id) {
1234 case AV_CODEC_ID_H264:
1235 params->codecPicParams.h264PicParams.sliceMode =
1236 ctx->config.encodeCodecConfig.h264Config.sliceMode;
1237 params->codecPicParams.h264PicParams.sliceModeData =
1238 ctx->config.encodeCodecConfig.h264Config.sliceModeData;
1240 case AV_CODEC_ID_HEVC:
1241 params->codecPicParams.hevcPicParams.sliceMode =
1242 ctx->config.encodeCodecConfig.hevcConfig.sliceMode;
1243 params->codecPicParams.hevcPicParams.sliceModeData =
1244 ctx->config.encodeCodecConfig.hevcConfig.sliceModeData;
1249 static inline int nvenc_enqueue_timestamp(AVFifoBuffer *f, int64_t pts)
1251 return av_fifo_generic_write(f, &pts, sizeof(pts), NULL);
1254 static inline int nvenc_dequeue_timestamp(AVFifoBuffer *f, int64_t *pts)
1256 return av_fifo_generic_read(f, pts, sizeof(*pts), NULL);
1259 static int nvenc_set_timestamp(AVCodecContext *avctx,
1260 NV_ENC_LOCK_BITSTREAM *params,
1263 NVENCContext *ctx = avctx->priv_data;
1265 pkt->pts = params->outputTimeStamp;
1266 pkt->duration = params->outputDuration;
1268 /* generate the first dts by linearly extrapolating the
1269 * first two pts values to the past */
1270 if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
1271 ctx->initial_pts[1] != AV_NOPTS_VALUE) {
1272 int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
1275 if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
1276 (ts0 > 0 && ts1 < INT64_MIN + ts0))
1277 return AVERROR(ERANGE);
1280 if ((delta < 0 && ts0 > INT64_MAX + delta) ||
1281 (delta > 0 && ts0 < INT64_MIN + delta))
1282 return AVERROR(ERANGE);
1283 pkt->dts = ts0 - delta;
1285 ctx->first_packet_output = 1;
1288 return nvenc_dequeue_timestamp(ctx->timestamps, &pkt->dts);
1291 static int nvenc_get_output(AVCodecContext *avctx, AVPacket *pkt)
1293 NVENCContext *ctx = avctx->priv_data;
1294 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1295 NV_ENC_LOCK_BITSTREAM params = { 0 };
1299 ret = av_fifo_generic_read(ctx->ready, &frame, sizeof(frame), NULL);
1303 params.version = NV_ENC_LOCK_BITSTREAM_VER;
1304 params.outputBitstream = frame->out;
1306 ret = nv->nvEncLockBitstream(ctx->nvenc_ctx, ¶ms);
1308 return nvenc_print_error(avctx, ret, "Cannot lock the bitstream");
1310 ret = ff_alloc_packet(pkt, params.bitstreamSizeInBytes);
1314 memcpy(pkt->data, params.bitstreamBufferPtr, pkt->size);
1316 ret = nv->nvEncUnlockBitstream(ctx->nvenc_ctx, frame->out);
1318 return nvenc_print_error(avctx, ret, "Cannot unlock the bitstream");
1320 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1321 nv->nvEncUnmapInputResource(ctx->nvenc_ctx, frame->in_map.mappedResource);
1322 av_frame_unref(frame->in_ref);
1323 ctx->registered_frames[frame->reg_idx].mapped = 0;
1330 ret = nvenc_set_timestamp(avctx, ¶ms, pkt);
1334 switch (params.pictureType) {
1335 case NV_ENC_PIC_TYPE_IDR:
1336 pkt->flags |= AV_PKT_FLAG_KEY;
1337 #if FF_API_CODED_FRAME
1338 FF_DISABLE_DEPRECATION_WARNINGS
1339 case NV_ENC_PIC_TYPE_INTRA_REFRESH:
1340 case NV_ENC_PIC_TYPE_I:
1341 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
1343 case NV_ENC_PIC_TYPE_P:
1344 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
1346 case NV_ENC_PIC_TYPE_B:
1347 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;
1349 case NV_ENC_PIC_TYPE_BI:
1350 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_BI;
1352 FF_ENABLE_DEPRECATION_WARNINGS
1359 static int output_ready(AVCodecContext *avctx, int flush)
1361 NVENCContext *ctx = avctx->priv_data;
1362 int nb_ready, nb_pending;
1364 /* when B-frames are enabled, we wait for two initial timestamps to
1365 * calculate the first dts */
1366 if (!flush && avctx->max_b_frames > 0 &&
1367 (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
1370 nb_ready = av_fifo_size(ctx->ready) / sizeof(NVENCFrame*);
1371 nb_pending = av_fifo_size(ctx->pending) / sizeof(NVENCFrame*);
1373 return nb_ready > 0;
1374 return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
1377 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1378 const AVFrame *frame, int *got_packet)
1380 NVENCContext *ctx = avctx->priv_data;
1381 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1382 NV_ENC_PIC_PARAMS params = { 0 };
1383 NVENCFrame *nvenc_frame = NULL;
1386 params.version = NV_ENC_PIC_PARAMS_VER;
1389 nvenc_frame = get_free_frame(ctx);
1391 av_log(avctx, AV_LOG_ERROR, "No free surfaces\n");
1395 ret = nvenc_upload_frame(avctx, frame, nvenc_frame);
1399 params.inputBuffer = nvenc_frame->in;
1400 params.bufferFmt = nvenc_frame->format;
1401 params.inputWidth = frame->width;
1402 params.inputHeight = frame->height;
1403 params.outputBitstream = nvenc_frame->out;
1404 params.inputTimeStamp = frame->pts;
1406 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1407 if (frame->top_field_first)
1408 params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
1410 params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
1412 params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1415 nvenc_codec_specific_pic_params(avctx, ¶ms);
1417 ret = nvenc_enqueue_timestamp(ctx->timestamps, frame->pts);
1421 if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
1422 ctx->initial_pts[0] = frame->pts;
1423 else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
1424 ctx->initial_pts[1] = frame->pts;
1426 params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1429 enc_ret = nv->nvEncEncodePicture(ctx->nvenc_ctx, ¶ms);
1430 if (enc_ret != NV_ENC_SUCCESS &&
1431 enc_ret != NV_ENC_ERR_NEED_MORE_INPUT)
1432 return nvenc_print_error(avctx, enc_ret, "Error encoding the frame");
1435 ret = av_fifo_generic_write(ctx->pending, &nvenc_frame, sizeof(nvenc_frame), NULL);
1440 /* all the pending buffers are now ready for output */
1441 if (enc_ret == NV_ENC_SUCCESS) {
1442 while (av_fifo_size(ctx->pending) > 0) {
1443 av_fifo_generic_read(ctx->pending, &nvenc_frame, sizeof(nvenc_frame), NULL);
1444 av_fifo_generic_write(ctx->ready, &nvenc_frame, sizeof(nvenc_frame), NULL);
1448 if (output_ready(avctx, !frame)) {
1449 ret = nvenc_get_output(avctx, pkt);