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;
621 if (ctx->flags & NVENC_LOSSLESS)
622 h264->qpPrimeYZeroTransformBypassFlag = 1;
624 if (IS_CBR(cc->rcParams.rateControlMode)) {
625 h264->outputBufferingPeriodSEI = 1;
626 h264->outputPictureTimingSEI = 1;
630 avctx->profile = ctx->profile;
632 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P)
633 h264->chromaFormatIDC = 3;
635 h264->chromaFormatIDC = 1;
637 switch (ctx->profile) {
638 case NV_ENC_H264_PROFILE_BASELINE:
639 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
641 case NV_ENC_H264_PROFILE_MAIN:
642 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
644 case NV_ENC_H264_PROFILE_HIGH:
645 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
647 case NV_ENC_H264_PROFILE_HIGH_444:
648 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
650 case NV_ENC_H264_PROFILE_CONSTRAINED_HIGH:
651 cc->profileGUID = NV_ENC_H264_PROFILE_CONSTRAINED_HIGH_GUID;
655 h264->level = ctx->level;
660 static int nvenc_setup_hevc_config(AVCodecContext *avctx)
662 NVENCContext *ctx = avctx->priv_data;
663 NV_ENC_CONFIG *cc = &ctx->config;
664 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
665 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
667 vui->colourDescriptionPresentFlag = avctx->colorspace != AVCOL_SPC_UNSPECIFIED ||
668 avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
669 avctx->color_trc != AVCOL_TRC_UNSPECIFIED;
671 vui->colourMatrix = avctx->colorspace;
672 vui->colourPrimaries = avctx->color_primaries;
673 vui->transferCharacteristics = avctx->color_trc;
675 vui->videoFullRangeFlag = avctx->color_range == AVCOL_RANGE_JPEG;
677 vui->videoSignalTypePresentFlag = vui->colourDescriptionPresentFlag ||
678 vui->videoFullRangeFlag;
680 hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
681 hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
684 hevc->maxNumRefFramesInDPB = avctx->refs;
685 hevc->idrPeriod = cc->gopLength;
687 if (IS_CBR(cc->rcParams.rateControlMode)) {
688 hevc->outputBufferingPeriodSEI = 1;
689 hevc->outputPictureTimingSEI = 1;
692 /* No other profile is supported in the current SDK version 5 */
693 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
694 avctx->profile = FF_PROFILE_HEVC_MAIN;
697 hevc->level = ctx->level;
699 hevc->level = NV_ENC_LEVEL_AUTOSELECT;
703 hevc->tier = ctx->tier;
708 static int nvenc_setup_codec_config(AVCodecContext *avctx)
710 switch (avctx->codec->id) {
711 case AV_CODEC_ID_H264:
712 return nvenc_setup_h264_config(avctx);
713 case AV_CODEC_ID_HEVC:
714 return nvenc_setup_hevc_config(avctx);
719 static int nvenc_setup_encoder(AVCodecContext *avctx)
721 NVENCContext *ctx = avctx->priv_data;
722 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
723 NV_ENC_PRESET_CONFIG preset_cfg = { 0 };
724 AVCPBProperties *cpb_props;
727 ctx->params.version = NV_ENC_INITIALIZE_PARAMS_VER;
729 ctx->params.encodeHeight = avctx->height;
730 ctx->params.encodeWidth = avctx->width;
732 if (avctx->sample_aspect_ratio.num &&
733 avctx->sample_aspect_ratio.den &&
734 (avctx->sample_aspect_ratio.num != 1 ||
735 avctx->sample_aspect_ratio.den != 1)) {
736 av_reduce(&ctx->params.darWidth,
737 &ctx->params.darHeight,
738 avctx->width * avctx->sample_aspect_ratio.num,
739 avctx->height * avctx->sample_aspect_ratio.den,
742 ctx->params.darHeight = avctx->height;
743 ctx->params.darWidth = avctx->width;
746 // De-compensate for hardware, dubiously, trying to compensate for
747 // playback at 704 pixel width.
748 if (avctx->width == 720 && (avctx->height == 480 || avctx->height == 576)) {
749 av_reduce(&ctx->params.darWidth, &ctx->params.darHeight,
750 ctx->params.darWidth * 44,
751 ctx->params.darHeight * 45,
755 ctx->params.frameRateNum = avctx->time_base.den;
756 ctx->params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
758 ctx->params.enableEncodeAsync = 0;
759 ctx->params.enablePTD = 1;
761 ctx->params.encodeConfig = &ctx->config;
763 nvec_map_preset(ctx);
765 preset_cfg.version = NV_ENC_PRESET_CONFIG_VER;
766 preset_cfg.presetCfg.version = NV_ENC_CONFIG_VER;
768 ret = nv->nvEncGetEncodePresetConfig(ctx->nvenc_ctx,
769 ctx->params.encodeGUID,
770 ctx->params.presetGUID,
772 if (ret != NV_ENC_SUCCESS)
773 return nvenc_print_error(avctx, ret, "Cannot get the preset configuration");
775 memcpy(&ctx->config, &preset_cfg.presetCfg, sizeof(ctx->config));
777 ctx->config.version = NV_ENC_CONFIG_VER;
779 if (avctx->gop_size > 0) {
780 if (avctx->max_b_frames > 0) {
784 * 3 two B-frames, and so on. */
785 ctx->config.frameIntervalP = avctx->max_b_frames + 1;
786 } else if (avctx->max_b_frames == 0) {
787 ctx->config.frameIntervalP = 1;
789 ctx->config.gopLength = avctx->gop_size;
790 } else if (avctx->gop_size == 0) {
791 ctx->config.frameIntervalP = 0;
792 ctx->config.gopLength = 1;
795 if (ctx->config.frameIntervalP > 1)
796 avctx->max_b_frames = ctx->config.frameIntervalP - 1;
798 ctx->initial_pts[0] = AV_NOPTS_VALUE;
799 ctx->initial_pts[1] = AV_NOPTS_VALUE;
801 nvenc_setup_rate_control(avctx);
803 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
804 ctx->config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
806 ctx->config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
809 if ((ret = nvenc_setup_codec_config(avctx)) < 0)
812 ret = nv->nvEncInitializeEncoder(ctx->nvenc_ctx, &ctx->params);
813 if (ret != NV_ENC_SUCCESS)
814 return nvenc_print_error(avctx, ret, "Cannot initialize the decoder");
816 cpb_props = ff_add_cpb_side_data(avctx);
818 return AVERROR(ENOMEM);
819 cpb_props->max_bitrate = avctx->rc_max_rate;
820 cpb_props->min_bitrate = avctx->rc_min_rate;
821 cpb_props->avg_bitrate = avctx->bit_rate;
822 cpb_props->buffer_size = avctx->rc_buffer_size;
827 static int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
829 NVENCContext *ctx = avctx->priv_data;
830 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
832 NV_ENC_CREATE_BITSTREAM_BUFFER out_buffer = { 0 };
834 switch (ctx->data_pix_fmt) {
835 case AV_PIX_FMT_YUV420P:
836 ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YV12_PL;
838 case AV_PIX_FMT_NV12:
839 ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_NV12_PL;
841 case AV_PIX_FMT_YUV444P:
842 ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YUV444_PL;
848 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
849 ctx->frames[idx].in_ref = av_frame_alloc();
850 if (!ctx->frames[idx].in_ref)
851 return AVERROR(ENOMEM);
853 NV_ENC_CREATE_INPUT_BUFFER in_buffer = { 0 };
855 in_buffer.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
857 in_buffer.width = avctx->width;
858 in_buffer.height = avctx->height;
860 in_buffer.bufferFmt = ctx->frames[idx].format;
861 in_buffer.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED;
863 ret = nv->nvEncCreateInputBuffer(ctx->nvenc_ctx, &in_buffer);
864 if (ret != NV_ENC_SUCCESS)
865 return nvenc_print_error(avctx, ret, "CreateInputBuffer failed");
867 ctx->frames[idx].in = in_buffer.inputBuffer;
870 out_buffer.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
871 /* 1MB is large enough to hold most output frames.
872 * NVENC increases this automatically if it is not enough. */
873 out_buffer.size = BITSTREAM_BUFFER_SIZE;
875 out_buffer.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED;
877 ret = nv->nvEncCreateBitstreamBuffer(ctx->nvenc_ctx, &out_buffer);
878 if (ret != NV_ENC_SUCCESS)
879 return nvenc_print_error(avctx, ret, "CreateBitstreamBuffer failed");
881 ctx->frames[idx].out = out_buffer.bitstreamBuffer;
886 static int nvenc_setup_surfaces(AVCodecContext *avctx)
888 NVENCContext *ctx = avctx->priv_data;
891 ctx->nb_surfaces = FFMAX(4 + avctx->max_b_frames,
893 ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
896 ctx->frames = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->frames));
898 return AVERROR(ENOMEM);
900 ctx->timestamps = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
901 if (!ctx->timestamps)
902 return AVERROR(ENOMEM);
903 ctx->pending = av_fifo_alloc(ctx->nb_surfaces * sizeof(*ctx->frames));
905 return AVERROR(ENOMEM);
906 ctx->ready = av_fifo_alloc(ctx->nb_surfaces * sizeof(*ctx->frames));
908 return AVERROR(ENOMEM);
910 for (i = 0; i < ctx->nb_surfaces; i++) {
911 if ((ret = nvenc_alloc_surface(avctx, i)) < 0)
918 #define EXTRADATA_SIZE 512
920 static int nvenc_setup_extradata(AVCodecContext *avctx)
922 NVENCContext *ctx = avctx->priv_data;
923 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
924 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
927 avctx->extradata = av_mallocz(EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
928 if (!avctx->extradata)
929 return AVERROR(ENOMEM);
931 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
932 payload.spsppsBuffer = avctx->extradata;
933 payload.inBufferSize = EXTRADATA_SIZE;
934 payload.outSPSPPSPayloadSize = &avctx->extradata_size;
936 ret = nv->nvEncGetSequenceParams(ctx->nvenc_ctx, &payload);
937 if (ret != NV_ENC_SUCCESS)
938 return nvenc_print_error(avctx, ret, "Cannot get the extradata");
943 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
945 NVENCContext *ctx = avctx->priv_data;
946 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
949 /* the encoder has to be flushed before it can be closed */
950 if (ctx->nvenc_ctx) {
951 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
952 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
954 nv->nvEncEncodePicture(ctx->nvenc_ctx, ¶ms);
957 av_fifo_free(ctx->timestamps);
958 av_fifo_free(ctx->pending);
959 av_fifo_free(ctx->ready);
962 for (i = 0; i < ctx->nb_surfaces; ++i) {
963 if (avctx->pix_fmt != AV_PIX_FMT_CUDA) {
964 nv->nvEncDestroyInputBuffer(ctx->nvenc_ctx, ctx->frames[i].in);
965 } else if (ctx->frames[i].in) {
966 nv->nvEncUnmapInputResource(ctx->nvenc_ctx, ctx->frames[i].in_map.mappedResource);
969 av_frame_free(&ctx->frames[i].in_ref);
970 nv->nvEncDestroyBitstreamBuffer(ctx->nvenc_ctx, ctx->frames[i].out);
973 for (i = 0; i < ctx->nb_registered_frames; i++) {
974 if (ctx->registered_frames[i].regptr)
975 nv->nvEncUnregisterResource(ctx->nvenc_ctx, ctx->registered_frames[i].regptr);
977 ctx->nb_registered_frames = 0;
979 av_freep(&ctx->frames);
982 nv->nvEncDestroyEncoder(ctx->nvenc_ctx);
984 if (ctx->cu_context_internal)
985 ctx->nvel.cu_ctx_destroy(ctx->cu_context_internal);
988 dlclose(ctx->nvel.nvenc);
992 dlclose(ctx->nvel.cuda);
998 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
1000 NVENCContext *ctx = avctx->priv_data;
1003 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1004 AVHWFramesContext *frames_ctx;
1005 if (!avctx->hw_frames_ctx) {
1006 av_log(avctx, AV_LOG_ERROR,
1007 "hw_frames_ctx must be set when using GPU frames as input\n");
1008 return AVERROR(EINVAL);
1010 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1011 ctx->data_pix_fmt = frames_ctx->sw_format;
1013 ctx->data_pix_fmt = avctx->pix_fmt;
1016 if ((ret = nvenc_load_libraries(avctx)) < 0)
1019 if ((ret = nvenc_setup_device(avctx)) < 0)
1022 if ((ret = nvenc_setup_encoder(avctx)) < 0)
1025 if ((ret = nvenc_setup_surfaces(avctx)) < 0)
1028 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1029 if ((ret = nvenc_setup_extradata(avctx)) < 0)
1036 static NVENCFrame *get_free_frame(NVENCContext *ctx)
1040 for (i = 0; i < ctx->nb_surfaces; i++) {
1041 if (!ctx->frames[i].locked) {
1042 ctx->frames[i].locked = 1;
1043 return &ctx->frames[i];
1050 static int nvenc_copy_frame(NV_ENC_LOCK_INPUT_BUFFER *in, const AVFrame *frame)
1052 uint8_t *buf = in->bufferDataPtr;
1053 int off = frame->height * in->pitch;
1055 switch (frame->format) {
1056 case AV_PIX_FMT_YUV420P:
1057 av_image_copy_plane(buf, in->pitch,
1058 frame->data[0], frame->linesize[0],
1059 frame->width, frame->height);
1062 av_image_copy_plane(buf, in->pitch >> 1,
1063 frame->data[2], frame->linesize[2],
1064 frame->width >> 1, frame->height >> 1);
1068 av_image_copy_plane(buf, in->pitch >> 1,
1069 frame->data[1], frame->linesize[1],
1070 frame->width >> 1, frame->height >> 1);
1072 case AV_PIX_FMT_NV12:
1073 av_image_copy_plane(buf, in->pitch,
1074 frame->data[0], frame->linesize[0],
1075 frame->width, frame->height);
1078 av_image_copy_plane(buf, in->pitch,
1079 frame->data[1], frame->linesize[1],
1080 frame->width, frame->height >> 1);
1082 case AV_PIX_FMT_YUV444P:
1083 av_image_copy_plane(buf, in->pitch,
1084 frame->data[0], frame->linesize[0],
1085 frame->width, frame->height);
1088 av_image_copy_plane(buf, in->pitch,
1089 frame->data[1], frame->linesize[1],
1090 frame->width, frame->height);
1093 av_image_copy_plane(buf, in->pitch,
1094 frame->data[2], frame->linesize[2],
1095 frame->width, frame->height);
1104 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1106 NVENCContext *ctx = avctx->priv_data;
1107 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1110 if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1111 for (i = 0; i < ctx->nb_registered_frames; i++) {
1112 if (!ctx->registered_frames[i].mapped) {
1113 if (ctx->registered_frames[i].regptr) {
1114 nv->nvEncUnregisterResource(ctx->nvenc_ctx,
1115 ctx->registered_frames[i].regptr);
1116 ctx->registered_frames[i].regptr = NULL;
1122 return ctx->nb_registered_frames++;
1125 av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1126 return AVERROR(ENOMEM);
1129 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1131 NVENCContext *ctx = avctx->priv_data;
1132 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1133 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1134 NV_ENC_REGISTER_RESOURCE reg;
1137 for (i = 0; i < ctx->nb_registered_frames; i++) {
1138 if (ctx->registered_frames[i].ptr == (CUdeviceptr)frame->data[0])
1142 idx = nvenc_find_free_reg_resource(avctx);
1146 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1147 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1148 reg.width = frames_ctx->width;
1149 reg.height = frames_ctx->height;
1150 reg.bufferFormat = ctx->frames[0].format;
1151 reg.pitch = frame->linesize[0];
1152 reg.resourceToRegister = frame->data[0];
1154 ret = nv->nvEncRegisterResource(ctx->nvenc_ctx, ®);
1155 if (ret != NV_ENC_SUCCESS) {
1156 nvenc_print_error(avctx, ret, "Error registering an input resource");
1157 return AVERROR_UNKNOWN;
1160 ctx->registered_frames[idx].ptr = (CUdeviceptr)frame->data[0];
1161 ctx->registered_frames[idx].regptr = reg.registeredResource;
1165 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1166 NVENCFrame *nvenc_frame)
1168 NVENCContext *ctx = avctx->priv_data;
1169 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1172 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1175 ret = nvenc_register_frame(avctx, frame);
1177 av_log(avctx, AV_LOG_ERROR, "Could not register an input CUDA frame\n");
1182 ret = av_frame_ref(nvenc_frame->in_ref, frame);
1186 nvenc_frame->in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1187 nvenc_frame->in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1189 ret = nv->nvEncMapInputResource(ctx->nvenc_ctx, &nvenc_frame->in_map);
1190 if (ret != NV_ENC_SUCCESS) {
1191 av_frame_unref(nvenc_frame->in_ref);
1192 return nvenc_print_error(avctx, ret, "Error mapping an input resource");
1195 ctx->registered_frames[reg_idx].mapped = 1;
1196 nvenc_frame->reg_idx = reg_idx;
1197 nvenc_frame->in = nvenc_frame->in_map.mappedResource;
1199 NV_ENC_LOCK_INPUT_BUFFER params = { 0 };
1201 params.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1202 params.inputBuffer = nvenc_frame->in;
1204 ret = nv->nvEncLockInputBuffer(ctx->nvenc_ctx, ¶ms);
1205 if (ret != NV_ENC_SUCCESS)
1206 return nvenc_print_error(avctx, ret, "Cannot lock the buffer");
1208 ret = nvenc_copy_frame(¶ms, frame);
1210 nv->nvEncUnlockInputBuffer(ctx->nvenc_ctx, nvenc_frame->in);
1214 ret = nv->nvEncUnlockInputBuffer(ctx->nvenc_ctx, nvenc_frame->in);
1215 if (ret != NV_ENC_SUCCESS)
1216 return nvenc_print_error(avctx, ret, "Cannot unlock the buffer");
1222 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1223 NV_ENC_PIC_PARAMS *params)
1225 NVENCContext *ctx = avctx->priv_data;
1227 switch (avctx->codec->id) {
1228 case AV_CODEC_ID_H264:
1229 params->codecPicParams.h264PicParams.sliceMode =
1230 ctx->config.encodeCodecConfig.h264Config.sliceMode;
1231 params->codecPicParams.h264PicParams.sliceModeData =
1232 ctx->config.encodeCodecConfig.h264Config.sliceModeData;
1234 case AV_CODEC_ID_HEVC:
1235 params->codecPicParams.hevcPicParams.sliceMode =
1236 ctx->config.encodeCodecConfig.hevcConfig.sliceMode;
1237 params->codecPicParams.hevcPicParams.sliceModeData =
1238 ctx->config.encodeCodecConfig.hevcConfig.sliceModeData;
1243 static inline int nvenc_enqueue_timestamp(AVFifoBuffer *f, int64_t pts)
1245 return av_fifo_generic_write(f, &pts, sizeof(pts), NULL);
1248 static inline int nvenc_dequeue_timestamp(AVFifoBuffer *f, int64_t *pts)
1250 return av_fifo_generic_read(f, pts, sizeof(*pts), NULL);
1253 static int nvenc_set_timestamp(AVCodecContext *avctx,
1254 NV_ENC_LOCK_BITSTREAM *params,
1257 NVENCContext *ctx = avctx->priv_data;
1259 pkt->pts = params->outputTimeStamp;
1260 pkt->duration = params->outputDuration;
1262 /* generate the first dts by linearly extrapolating the
1263 * first two pts values to the past */
1264 if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
1265 ctx->initial_pts[1] != AV_NOPTS_VALUE) {
1266 int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
1269 if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
1270 (ts0 > 0 && ts1 < INT64_MIN + ts0))
1271 return AVERROR(ERANGE);
1274 if ((delta < 0 && ts0 > INT64_MAX + delta) ||
1275 (delta > 0 && ts0 < INT64_MIN + delta))
1276 return AVERROR(ERANGE);
1277 pkt->dts = ts0 - delta;
1279 ctx->first_packet_output = 1;
1282 return nvenc_dequeue_timestamp(ctx->timestamps, &pkt->dts);
1285 static int nvenc_get_output(AVCodecContext *avctx, AVPacket *pkt)
1287 NVENCContext *ctx = avctx->priv_data;
1288 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1289 NV_ENC_LOCK_BITSTREAM params = { 0 };
1293 ret = av_fifo_generic_read(ctx->ready, &frame, sizeof(frame), NULL);
1297 params.version = NV_ENC_LOCK_BITSTREAM_VER;
1298 params.outputBitstream = frame->out;
1300 ret = nv->nvEncLockBitstream(ctx->nvenc_ctx, ¶ms);
1302 return nvenc_print_error(avctx, ret, "Cannot lock the bitstream");
1304 ret = ff_alloc_packet(pkt, params.bitstreamSizeInBytes);
1308 memcpy(pkt->data, params.bitstreamBufferPtr, pkt->size);
1310 ret = nv->nvEncUnlockBitstream(ctx->nvenc_ctx, frame->out);
1312 return nvenc_print_error(avctx, ret, "Cannot unlock the bitstream");
1314 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1315 nv->nvEncUnmapInputResource(ctx->nvenc_ctx, frame->in_map.mappedResource);
1316 av_frame_unref(frame->in_ref);
1317 ctx->registered_frames[frame->reg_idx].mapped = 0;
1324 ret = nvenc_set_timestamp(avctx, ¶ms, pkt);
1328 switch (params.pictureType) {
1329 case NV_ENC_PIC_TYPE_IDR:
1330 pkt->flags |= AV_PKT_FLAG_KEY;
1331 #if FF_API_CODED_FRAME
1332 FF_DISABLE_DEPRECATION_WARNINGS
1333 case NV_ENC_PIC_TYPE_INTRA_REFRESH:
1334 case NV_ENC_PIC_TYPE_I:
1335 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
1337 case NV_ENC_PIC_TYPE_P:
1338 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
1340 case NV_ENC_PIC_TYPE_B:
1341 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;
1343 case NV_ENC_PIC_TYPE_BI:
1344 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_BI;
1346 FF_ENABLE_DEPRECATION_WARNINGS
1353 static int output_ready(AVCodecContext *avctx, int flush)
1355 NVENCContext *ctx = avctx->priv_data;
1356 int nb_ready, nb_pending;
1358 /* when B-frames are enabled, we wait for two initial timestamps to
1359 * calculate the first dts */
1360 if (!flush && avctx->max_b_frames > 0 &&
1361 (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
1364 nb_ready = av_fifo_size(ctx->ready) / sizeof(NVENCFrame*);
1365 nb_pending = av_fifo_size(ctx->pending) / sizeof(NVENCFrame*);
1367 return nb_ready > 0;
1368 return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
1371 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1372 const AVFrame *frame, int *got_packet)
1374 NVENCContext *ctx = avctx->priv_data;
1375 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1376 NV_ENC_PIC_PARAMS params = { 0 };
1377 NVENCFrame *nvenc_frame = NULL;
1380 params.version = NV_ENC_PIC_PARAMS_VER;
1383 nvenc_frame = get_free_frame(ctx);
1385 av_log(avctx, AV_LOG_ERROR, "No free surfaces\n");
1389 ret = nvenc_upload_frame(avctx, frame, nvenc_frame);
1393 params.inputBuffer = nvenc_frame->in;
1394 params.bufferFmt = nvenc_frame->format;
1395 params.inputWidth = frame->width;
1396 params.inputHeight = frame->height;
1397 params.outputBitstream = nvenc_frame->out;
1398 params.inputTimeStamp = frame->pts;
1400 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1401 if (frame->top_field_first)
1402 params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
1404 params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
1406 params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1409 nvenc_codec_specific_pic_params(avctx, ¶ms);
1411 ret = nvenc_enqueue_timestamp(ctx->timestamps, frame->pts);
1415 if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
1416 ctx->initial_pts[0] = frame->pts;
1417 else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
1418 ctx->initial_pts[1] = frame->pts;
1420 params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1423 enc_ret = nv->nvEncEncodePicture(ctx->nvenc_ctx, ¶ms);
1424 if (enc_ret != NV_ENC_SUCCESS &&
1425 enc_ret != NV_ENC_ERR_NEED_MORE_INPUT)
1426 return nvenc_print_error(avctx, enc_ret, "Error encoding the frame");
1429 ret = av_fifo_generic_write(ctx->pending, &nvenc_frame, sizeof(nvenc_frame), NULL);
1434 /* all the pending buffers are now ready for output */
1435 if (enc_ret == NV_ENC_SUCCESS) {
1436 while (av_fifo_size(ctx->pending) > 0) {
1437 av_fifo_generic_read(ctx->pending, &nvenc_frame, sizeof(nvenc_frame), NULL);
1438 av_fifo_generic_write(ctx->ready, &nvenc_frame, sizeof(nvenc_frame), NULL);
1442 if (output_ready(avctx, !frame)) {
1443 ret = nvenc_get_output(avctx, pkt);