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[] = {
92 #if NVENCAPI_MAJOR_VERSION >= 7
102 #define IS_10BIT(pix_fmt) (pix_fmt == AV_PIX_FMT_P010 || \
103 pix_fmt == AV_PIX_FMT_YUV444P16)
105 #define IS_YUV444(pix_fmt) (pix_fmt == AV_PIX_FMT_YUV444P || \
106 pix_fmt == AV_PIX_FMT_YUV444P16)
108 static const struct {
113 { NV_ENC_SUCCESS, 0, "success" },
114 { NV_ENC_ERR_NO_ENCODE_DEVICE, AVERROR(ENOENT), "no encode device" },
115 { NV_ENC_ERR_UNSUPPORTED_DEVICE, AVERROR(ENOSYS), "unsupported device" },
116 { NV_ENC_ERR_INVALID_ENCODERDEVICE, AVERROR(EINVAL), "invalid encoder device" },
117 { NV_ENC_ERR_INVALID_DEVICE, AVERROR(EINVAL), "invalid device" },
118 { NV_ENC_ERR_DEVICE_NOT_EXIST, AVERROR(EIO), "device does not exist" },
119 { NV_ENC_ERR_INVALID_PTR, AVERROR(EFAULT), "invalid ptr" },
120 { NV_ENC_ERR_INVALID_EVENT, AVERROR(EINVAL), "invalid event" },
121 { NV_ENC_ERR_INVALID_PARAM, AVERROR(EINVAL), "invalid param" },
122 { NV_ENC_ERR_INVALID_CALL, AVERROR(EINVAL), "invalid call" },
123 { NV_ENC_ERR_OUT_OF_MEMORY, AVERROR(ENOMEM), "out of memory" },
124 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED, AVERROR(EINVAL), "encoder not initialized" },
125 { NV_ENC_ERR_UNSUPPORTED_PARAM, AVERROR(ENOSYS), "unsupported param" },
126 { NV_ENC_ERR_LOCK_BUSY, AVERROR(EBUSY), "lock busy" },
127 { NV_ENC_ERR_NOT_ENOUGH_BUFFER, AVERROR(ENOBUFS), "not enough buffer" },
128 { NV_ENC_ERR_INVALID_VERSION, AVERROR(EINVAL), "invalid version" },
129 { NV_ENC_ERR_MAP_FAILED, AVERROR(EIO), "map failed" },
130 /* this is error should always be treated specially, so this "mapping"
131 * is for completeness only */
132 { NV_ENC_ERR_NEED_MORE_INPUT, AVERROR_UNKNOWN, "need more input" },
133 { NV_ENC_ERR_ENCODER_BUSY, AVERROR(EBUSY), "encoder busy" },
134 { NV_ENC_ERR_EVENT_NOT_REGISTERD, AVERROR(EBADF), "event not registered" },
135 { NV_ENC_ERR_GENERIC, AVERROR_UNKNOWN, "generic error" },
136 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY, AVERROR(EINVAL), "incompatible client key" },
137 { NV_ENC_ERR_UNIMPLEMENTED, AVERROR(ENOSYS), "unimplemented" },
138 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO), "resource register failed" },
139 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED, AVERROR(EBADF), "resource not registered" },
140 { NV_ENC_ERR_RESOURCE_NOT_MAPPED, AVERROR(EBADF), "resource not mapped" },
143 static int nvenc_map_error(NVENCSTATUS err, const char **desc)
146 for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
147 if (nvenc_errors[i].nverr == err) {
149 *desc = nvenc_errors[i].desc;
150 return nvenc_errors[i].averr;
154 *desc = "unknown error";
155 return AVERROR_UNKNOWN;
158 static int nvenc_print_error(void *log_ctx, NVENCSTATUS err,
159 const char *error_string)
163 ret = nvenc_map_error(err, &desc);
164 av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
168 static av_cold int nvenc_load_libraries(AVCodecContext *avctx)
170 NVENCContext *ctx = avctx->priv_data;
171 NVENCLibraryContext *nvel = &ctx->nvel;
172 PNVENCODEAPICREATEINSTANCE nvenc_create_instance;
176 nvel->cu_init = cuInit;
177 nvel->cu_device_get_count = cuDeviceGetCount;
178 nvel->cu_device_get = cuDeviceGet;
179 nvel->cu_device_get_name = cuDeviceGetName;
180 nvel->cu_device_compute_capability = cuDeviceComputeCapability;
181 nvel->cu_ctx_create = cuCtxCreate_v2;
182 nvel->cu_ctx_pop_current = cuCtxPopCurrent_v2;
183 nvel->cu_ctx_push_current = cuCtxPushCurrent_v2;
184 nvel->cu_ctx_destroy = cuCtxDestroy_v2;
186 LOAD_LIBRARY(nvel->cuda, CUDA_LIBNAME);
188 LOAD_SYMBOL(nvel->cu_init, nvel->cuda, "cuInit");
189 LOAD_SYMBOL(nvel->cu_device_get_count, nvel->cuda, "cuDeviceGetCount");
190 LOAD_SYMBOL(nvel->cu_device_get, nvel->cuda, "cuDeviceGet");
191 LOAD_SYMBOL(nvel->cu_device_get_name, nvel->cuda, "cuDeviceGetName");
192 LOAD_SYMBOL(nvel->cu_device_compute_capability, nvel->cuda,
193 "cuDeviceComputeCapability");
194 LOAD_SYMBOL(nvel->cu_ctx_create, nvel->cuda, "cuCtxCreate_v2");
195 LOAD_SYMBOL(nvel->cu_ctx_pop_current, nvel->cuda, "cuCtxPopCurrent_v2");
196 LOAD_SYMBOL(nvel->cu_ctx_push_current, nvel->cuda, "cuCtxPushCurrent_v2");
197 LOAD_SYMBOL(nvel->cu_ctx_destroy, nvel->cuda, "cuCtxDestroy_v2");
200 LOAD_LIBRARY(nvel->nvenc, NVENC_LIBNAME);
202 LOAD_SYMBOL(nvenc_create_instance, nvel->nvenc,
203 "NvEncodeAPICreateInstance");
205 nvel->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
207 err = nvenc_create_instance(&nvel->nvenc_funcs);
208 if (err != NV_ENC_SUCCESS)
209 return nvenc_print_error(avctx, err, "Cannot create the NVENC instance");
214 static int nvenc_open_session(AVCodecContext *avctx)
216 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
217 NVENCContext *ctx = avctx->priv_data;
218 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
221 params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
222 params.apiVersion = NVENCAPI_VERSION;
223 params.device = ctx->cu_context;
224 params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
226 ret = nv->nvEncOpenEncodeSessionEx(¶ms, &ctx->nvenc_ctx);
227 if (ret != NV_ENC_SUCCESS) {
228 ctx->nvenc_ctx = NULL;
229 return nvenc_print_error(avctx, ret, "Cannot open the NVENC Session");
235 static int nvenc_check_codec_support(AVCodecContext *avctx)
237 NVENCContext *ctx = avctx->priv_data;
238 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
239 int i, ret, count = 0;
242 ret = nv->nvEncGetEncodeGUIDCount(ctx->nvenc_ctx, &count);
244 if (ret != NV_ENC_SUCCESS || !count)
245 return AVERROR(ENOSYS);
247 guids = av_malloc(count * sizeof(GUID));
249 return AVERROR(ENOMEM);
251 ret = nv->nvEncGetEncodeGUIDs(ctx->nvenc_ctx, guids, count, &count);
252 if (ret != NV_ENC_SUCCESS) {
253 ret = AVERROR(ENOSYS);
257 ret = AVERROR(ENOSYS);
258 for (i = 0; i < count; i++) {
259 if (!memcmp(&guids[i], &ctx->params.encodeGUID, sizeof(*guids))) {
271 static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
273 NVENCContext *ctx = avctx->priv_data;
274 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
275 NV_ENC_CAPS_PARAM params = { 0 };
278 params.version = NV_ENC_CAPS_PARAM_VER;
279 params.capsToQuery = cap;
281 ret = nv->nvEncGetEncodeCaps(ctx->nvenc_ctx, ctx->params.encodeGUID, ¶ms, &val);
283 if (ret == NV_ENC_SUCCESS)
288 static int nvenc_check_capabilities(AVCodecContext *avctx)
290 NVENCContext *ctx = avctx->priv_data;
293 ret = nvenc_check_codec_support(avctx);
295 av_log(avctx, AV_LOG_VERBOSE, "Codec not supported\n");
299 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
300 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P && ret <= 0) {
301 av_log(avctx, AV_LOG_VERBOSE, "YUV444P not supported\n");
302 return AVERROR(ENOSYS);
305 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
306 if (ret < avctx->width) {
307 av_log(avctx, AV_LOG_VERBOSE, "Width %d exceeds %d\n",
309 return AVERROR(ENOSYS);
312 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
313 if (ret < avctx->height) {
314 av_log(avctx, AV_LOG_VERBOSE, "Height %d exceeds %d\n",
316 return AVERROR(ENOSYS);
319 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
320 if (ret < avctx->max_b_frames) {
321 av_log(avctx, AV_LOG_VERBOSE, "Max B-frames %d exceed %d\n",
322 avctx->max_b_frames, ret);
324 return AVERROR(ENOSYS);
330 static int nvenc_check_device(AVCodecContext *avctx, int idx)
332 NVENCContext *ctx = avctx->priv_data;
333 NVENCLibraryContext *nvel = &ctx->nvel;
334 char name[128] = { 0 };
335 int major, minor, ret;
338 int loglevel = AV_LOG_VERBOSE;
340 if (ctx->device == LIST_DEVICES)
341 loglevel = AV_LOG_INFO;
343 ret = nvel->cu_device_get(&cu_device, idx);
344 if (ret != CUDA_SUCCESS) {
345 av_log(avctx, AV_LOG_ERROR,
346 "Cannot access the CUDA device %d\n",
351 ret = nvel->cu_device_get_name(name, sizeof(name), cu_device);
352 if (ret != CUDA_SUCCESS)
355 ret = nvel->cu_device_compute_capability(&major, &minor, cu_device);
356 if (ret != CUDA_SUCCESS)
359 av_log(avctx, loglevel, "Device %d [%s] ", cu_device, name);
361 if (((major << 4) | minor) < NVENC_CAP)
364 if (ctx->device != idx && ctx->device != ANY_DEVICE)
367 ret = nvel->cu_ctx_create(&ctx->cu_context_internal, 0, cu_device);
368 if (ret != CUDA_SUCCESS)
371 ctx->cu_context = ctx->cu_context_internal;
373 ret = nvel->cu_ctx_pop_current(&dummy);
374 if (ret != CUDA_SUCCESS)
377 if ((ret = nvenc_open_session(avctx)) < 0)
380 if ((ret = nvenc_check_capabilities(avctx)) < 0)
383 av_log(avctx, loglevel, "supports NVENC\n");
385 if (ctx->device == idx || ctx->device == ANY_DEVICE)
389 nvel->nvenc_funcs.nvEncDestroyEncoder(ctx->nvenc_ctx);
390 ctx->nvenc_ctx = NULL;
393 nvel->cu_ctx_destroy(ctx->cu_context_internal);
394 ctx->cu_context_internal = NULL;
398 av_log(avctx, loglevel, "does not support NVENC (major %d minor %d)\n",
401 return AVERROR(ENOSYS);
404 static int nvenc_setup_device(AVCodecContext *avctx)
406 NVENCContext *ctx = avctx->priv_data;
407 NVENCLibraryContext *nvel = &ctx->nvel;
409 switch (avctx->codec->id) {
410 case AV_CODEC_ID_H264:
411 ctx->params.encodeGUID = NV_ENC_CODEC_H264_GUID;
413 case AV_CODEC_ID_HEVC:
414 ctx->params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
420 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
422 AVHWFramesContext *frames_ctx;
423 AVCUDADeviceContext *device_hwctx;
426 if (!avctx->hw_frames_ctx)
427 return AVERROR(EINVAL);
429 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
430 device_hwctx = frames_ctx->device_ctx->hwctx;
432 ctx->cu_context = device_hwctx->cuda_ctx;
434 ret = nvenc_open_session(avctx);
438 ret = nvenc_check_capabilities(avctx);
445 int i, nb_devices = 0;
447 if ((nvel->cu_init(0)) != CUDA_SUCCESS) {
448 av_log(avctx, AV_LOG_ERROR,
449 "Cannot init CUDA\n");
450 return AVERROR_UNKNOWN;
453 if ((nvel->cu_device_get_count(&nb_devices)) != CUDA_SUCCESS) {
454 av_log(avctx, AV_LOG_ERROR,
455 "Cannot enumerate the CUDA devices\n");
456 return AVERROR_UNKNOWN;
460 for (i = 0; i < nb_devices; ++i) {
461 if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
465 if (ctx->device == LIST_DEVICES)
468 return AVERROR(ENOSYS);
474 typedef struct GUIDTuple {
479 #define PRESET_ALIAS(alias, name, ...) \
480 [PRESET_ ## alias] = { NV_ENC_PRESET_ ## name ## _GUID, __VA_ARGS__ }
482 #define PRESET(name, ...) PRESET_ALIAS(name, name, __VA_ARGS__)
484 static int nvenc_map_preset(NVENCContext *ctx)
486 GUIDTuple presets[] = {
491 PRESET(LOW_LATENCY_DEFAULT, NVENC_LOWLATENCY),
492 PRESET(LOW_LATENCY_HP, NVENC_LOWLATENCY),
493 PRESET(LOW_LATENCY_HQ, NVENC_LOWLATENCY),
494 PRESET(LOSSLESS_DEFAULT, NVENC_LOSSLESS),
495 PRESET(LOSSLESS_HP, NVENC_LOSSLESS),
496 PRESET_ALIAS(SLOW, HQ, NVENC_TWO_PASSES),
497 PRESET_ALIAS(MEDIUM, HQ, NVENC_ONE_PASS),
498 PRESET_ALIAS(FAST, HP, NVENC_ONE_PASS)
501 GUIDTuple *t = &presets[ctx->preset];
503 ctx->params.presetGUID = t->guid;
504 ctx->flags = t->flags;
506 return AVERROR(EINVAL);
512 static void set_constqp(AVCodecContext *avctx, NV_ENC_RC_PARAMS *rc)
514 NVENCContext *ctx = avctx->priv_data;
515 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
517 if (ctx->init_qp_p >= 0) {
518 rc->constQP.qpInterP = ctx->init_qp_p;
519 if (ctx->init_qp_i >= 0 && ctx->init_qp_b >= 0) {
520 rc->constQP.qpIntra = ctx->init_qp_i;
521 rc->constQP.qpInterB = ctx->init_qp_b;
522 } else if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
523 rc->constQP.qpIntra = av_clip(rc->constQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
524 rc->constQP.qpInterB = av_clip(rc->constQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
526 rc->constQP.qpIntra = rc->constQP.qpInterP;
527 rc->constQP.qpInterB = rc->constQP.qpInterP;
529 } else if (avctx->global_quality >= 0) {
530 rc->constQP.qpInterP = avctx->global_quality;
531 rc->constQP.qpInterB = avctx->global_quality;
532 rc->constQP.qpIntra = avctx->global_quality;
536 static void set_vbr(AVCodecContext *avctx, NV_ENC_RC_PARAMS *rc)
538 NVENCContext *ctx = avctx->priv_data;
540 if (avctx->qmin >= 0) {
542 rc->minQP.qpInterB = avctx->qmin;
543 rc->minQP.qpInterP = avctx->qmin;
544 rc->minQP.qpIntra = avctx->qmin;
547 if (avctx->qmax >= 0) {
549 rc->maxQP.qpInterB = avctx->qmax;
550 rc->maxQP.qpInterP = avctx->qmax;
551 rc->maxQP.qpIntra = avctx->qmax;
554 if (ctx->init_qp_p >= 0) {
555 rc->enableInitialRCQP = 1;
556 rc->initialRCQP.qpInterP = ctx->init_qp_p;
557 if (ctx->init_qp_i < 0) {
558 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
559 rc->initialRCQP.qpIntra = av_clip(rc->initialRCQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
561 rc->initialRCQP.qpIntra = rc->initialRCQP.qpInterP;
564 rc->initialRCQP.qpIntra = ctx->init_qp_i;
567 if (ctx->init_qp_b < 0) {
568 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
569 rc->initialRCQP.qpInterB = av_clip(rc->initialRCQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
571 rc->initialRCQP.qpInterB = rc->initialRCQP.qpInterP;
574 rc->initialRCQP.qpInterB = ctx->init_qp_b;
579 static void set_lossless(AVCodecContext *avctx, NV_ENC_RC_PARAMS *rc)
581 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
582 rc->constQP.qpInterB = 0;
583 rc->constQP.qpInterP = 0;
584 rc->constQP.qpIntra = 0;
587 static void nvenc_override_rate_control(AVCodecContext *avctx,
588 NV_ENC_RC_PARAMS *rc)
590 NVENCContext *ctx = avctx->priv_data;
593 case NV_ENC_PARAMS_RC_CONSTQP:
594 set_constqp(avctx, rc);
596 case NV_ENC_PARAMS_RC_2_PASS_VBR:
597 case NV_ENC_PARAMS_RC_VBR:
600 case NV_ENC_PARAMS_RC_VBR_MINQP:
601 if (avctx->qmin < 0) {
602 av_log(avctx, AV_LOG_WARNING,
603 "The variable bitrate rate-control requires "
604 "the 'qmin' option set.\n");
609 case NV_ENC_PARAMS_RC_CBR:
611 case NV_ENC_PARAMS_RC_2_PASS_QUALITY:
612 case NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP:
613 if (!(ctx->flags & NVENC_LOWLATENCY)) {
614 av_log(avctx, AV_LOG_WARNING,
615 "The multipass rate-control requires "
616 "a low-latency preset.\n");
621 rc->rateControlMode = ctx->rc;
624 static void nvenc_setup_rate_control(AVCodecContext *avctx)
626 NVENCContext *ctx = avctx->priv_data;
627 NV_ENC_RC_PARAMS *rc = &ctx->config.rcParams;
629 if (avctx->bit_rate > 0)
630 rc->averageBitRate = avctx->bit_rate;
632 if (avctx->rc_max_rate > 0)
633 rc->maxBitRate = avctx->rc_max_rate;
636 nvenc_override_rate_control(avctx, rc);
637 } else if (ctx->flags & NVENC_LOSSLESS) {
638 set_lossless(avctx, rc);
639 } else if (avctx->global_quality > 0) {
640 set_constqp(avctx, rc);
642 if (ctx->flags & NVENC_TWO_PASSES)
643 rc->rateControlMode = NV_ENC_PARAMS_RC_2_PASS_VBR;
645 rc->rateControlMode = NV_ENC_PARAMS_RC_VBR;
649 if (avctx->rc_buffer_size > 0)
650 rc->vbvBufferSize = avctx->rc_buffer_size;
652 if (rc->averageBitRate > 0)
653 avctx->bit_rate = rc->averageBitRate;
655 #if NVENCAPI_MAJOR_VERSION >= 7
657 ctx->config.rcParams.enableAQ = 1;
658 ctx->config.rcParams.aqStrength = ctx->aq_strength;
659 av_log(avctx, AV_LOG_VERBOSE, "AQ enabled.\n");
662 if (ctx->temporal_aq) {
663 ctx->config.rcParams.enableTemporalAQ = 1;
664 av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ enabled.\n");
667 if (ctx->rc_lookahead > 0) {
668 int lkd_bound = FFMIN(ctx->nb_surfaces, ctx->async_depth) -
669 ctx->config.frameIntervalP - 4;
672 av_log(avctx, AV_LOG_WARNING,
673 "Lookahead not enabled. Increase buffer delay (-delay).\n");
675 ctx->config.rcParams.enableLookahead = 1;
676 ctx->config.rcParams.lookaheadDepth = av_clip(ctx->rc_lookahead, 0, lkd_bound);
677 ctx->config.rcParams.disableIadapt = ctx->no_scenecut;
678 ctx->config.rcParams.disableBadapt = !ctx->b_adapt;
679 av_log(avctx, AV_LOG_VERBOSE,
680 "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",
681 ctx->config.rcParams.lookaheadDepth,
682 ctx->config.rcParams.disableIadapt ? "disabled" : "enabled",
683 ctx->config.rcParams.disableBadapt ? "disabled" : "enabled");
687 if (ctx->strict_gop) {
688 ctx->config.rcParams.strictGOPTarget = 1;
689 av_log(avctx, AV_LOG_VERBOSE, "Strict GOP target enabled.\n");
693 ctx->config.rcParams.enableNonRefP = 1;
695 if (ctx->zerolatency)
696 ctx->config.rcParams.zeroReorderDelay = 1;
699 ctx->config.rcParams.targetQuality = ctx->quality;
700 #endif /* NVENCAPI_MAJOR_VERSION >= 7 */
703 static int nvenc_setup_h264_config(AVCodecContext *avctx)
705 NVENCContext *ctx = avctx->priv_data;
706 NV_ENC_CONFIG *cc = &ctx->config;
707 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
708 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
710 vui->colourDescriptionPresentFlag = avctx->colorspace != AVCOL_SPC_UNSPECIFIED ||
711 avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
712 avctx->color_trc != AVCOL_TRC_UNSPECIFIED;
714 vui->colourMatrix = avctx->colorspace;
715 vui->colourPrimaries = avctx->color_primaries;
716 vui->transferCharacteristics = avctx->color_trc;
718 vui->videoFullRangeFlag = avctx->color_range == AVCOL_RANGE_JPEG;
720 vui->videoSignalTypePresentFlag = vui->colourDescriptionPresentFlag ||
721 vui->videoFullRangeFlag;
723 h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
724 h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
727 h264->maxNumRefFrames = avctx->refs;
728 h264->idrPeriod = cc->gopLength;
731 h264->sliceModeData = FFMAX(avctx->slices, 1);
733 if (ctx->flags & NVENC_LOSSLESS)
734 h264->qpPrimeYZeroTransformBypassFlag = 1;
736 if (IS_CBR(cc->rcParams.rateControlMode)) {
737 h264->outputBufferingPeriodSEI = 1;
738 h264->outputPictureTimingSEI = 1;
742 avctx->profile = ctx->profile;
744 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P)
745 h264->chromaFormatIDC = 3;
747 h264->chromaFormatIDC = 1;
749 switch (ctx->profile) {
750 case NV_ENC_H264_PROFILE_BASELINE:
751 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
753 case NV_ENC_H264_PROFILE_MAIN:
754 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
756 case NV_ENC_H264_PROFILE_HIGH:
757 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
759 case NV_ENC_H264_PROFILE_HIGH_444:
760 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
762 case NV_ENC_H264_PROFILE_CONSTRAINED_HIGH:
763 cc->profileGUID = NV_ENC_H264_PROFILE_CONSTRAINED_HIGH_GUID;
767 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P) {
768 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
769 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
772 h264->level = ctx->level;
777 static int nvenc_setup_hevc_config(AVCodecContext *avctx)
779 NVENCContext *ctx = avctx->priv_data;
780 NV_ENC_CONFIG *cc = &ctx->config;
781 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
782 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
784 vui->colourDescriptionPresentFlag = avctx->colorspace != AVCOL_SPC_UNSPECIFIED ||
785 avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
786 avctx->color_trc != AVCOL_TRC_UNSPECIFIED;
788 vui->colourMatrix = avctx->colorspace;
789 vui->colourPrimaries = avctx->color_primaries;
790 vui->transferCharacteristics = avctx->color_trc;
792 vui->videoFullRangeFlag = avctx->color_range == AVCOL_RANGE_JPEG;
794 vui->videoSignalTypePresentFlag = vui->colourDescriptionPresentFlag ||
795 vui->videoFullRangeFlag;
797 hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
798 hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
801 hevc->maxNumRefFramesInDPB = avctx->refs;
802 hevc->idrPeriod = cc->gopLength;
804 if (IS_CBR(cc->rcParams.rateControlMode)) {
805 hevc->outputBufferingPeriodSEI = 1;
806 hevc->outputPictureTimingSEI = 1;
809 switch (ctx->profile) {
810 case NV_ENC_HEVC_PROFILE_MAIN:
811 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
812 avctx->profile = FF_PROFILE_HEVC_MAIN;
814 #if NVENCAPI_MAJOR_VERSION >= 7
815 case NV_ENC_HEVC_PROFILE_MAIN_10:
816 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
817 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
819 case NV_ENC_HEVC_PROFILE_REXT:
820 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
821 avctx->profile = FF_PROFILE_HEVC_REXT;
823 #endif /* NVENCAPI_MAJOR_VERSION >= 7 */
826 // force setting profile for various input formats
827 switch (ctx->data_pix_fmt) {
828 case AV_PIX_FMT_YUV420P:
829 case AV_PIX_FMT_NV12:
830 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
831 avctx->profile = FF_PROFILE_HEVC_MAIN;
833 #if NVENCAPI_MAJOR_VERSION >= 7
834 case AV_PIX_FMT_P010:
835 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
836 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
838 case AV_PIX_FMT_YUV444P:
839 case AV_PIX_FMT_YUV444P16:
840 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
841 avctx->profile = FF_PROFILE_HEVC_REXT;
843 #endif /* NVENCAPI_MAJOR_VERSION >= 7 */
846 #if NVENCAPI_MAJOR_VERSION >= 7
847 hevc->chromaFormatIDC = IS_YUV444(ctx->data_pix_fmt) ? 3 : 1;
848 hevc->pixelBitDepthMinus8 = IS_10BIT(ctx->data_pix_fmt) ? 2 : 0;
849 #endif /* NVENCAPI_MAJOR_VERSION >= 7 */
852 hevc->sliceModeData = FFMAX(avctx->slices, 1);
855 hevc->level = ctx->level;
857 hevc->level = NV_ENC_LEVEL_AUTOSELECT;
861 hevc->tier = ctx->tier;
866 static int nvenc_setup_codec_config(AVCodecContext *avctx)
868 switch (avctx->codec->id) {
869 case AV_CODEC_ID_H264:
870 return nvenc_setup_h264_config(avctx);
871 case AV_CODEC_ID_HEVC:
872 return nvenc_setup_hevc_config(avctx);
877 static int nvenc_recalc_surfaces(AVCodecContext *avctx)
879 NVENCContext *ctx = avctx->priv_data;
880 // default minimum of 4 surfaces
881 // multiply by 2 for number of NVENCs on gpu (hardcode to 2)
882 // another multiply by 2 to avoid blocking next PBB group
883 int nb_surfaces = FFMAX(4, ctx->config.frameIntervalP * 2 * 2);
886 if (ctx->rc_lookahead > 0) {
887 // +1 is to account for lkd_bound calculation later
888 // +4 is to allow sufficient pipelining with lookahead
889 nb_surfaces = FFMAX(1, FFMAX(nb_surfaces, ctx->rc_lookahead + ctx->config.frameIntervalP + 1 + 4));
890 if (nb_surfaces > ctx->nb_surfaces && ctx->nb_surfaces > 0) {
891 av_log(avctx, AV_LOG_WARNING,
892 "Defined rc_lookahead requires more surfaces, "
893 "increasing used surfaces %d -> %d\n",
894 ctx->nb_surfaces, nb_surfaces);
896 ctx->nb_surfaces = FFMAX(nb_surfaces, ctx->nb_surfaces);
898 if (ctx->config.frameIntervalP > 1 &&
899 ctx->nb_surfaces < nb_surfaces && ctx->nb_surfaces > 0) {
900 av_log(avctx, AV_LOG_WARNING,
901 "Defined b-frame requires more surfaces, "
902 "increasing used surfaces %d -> %d\n",
903 ctx->nb_surfaces, nb_surfaces);
904 ctx->nb_surfaces = FFMAX(ctx->nb_surfaces, nb_surfaces);
905 } else if (ctx->nb_surfaces <= 0)
906 ctx->nb_surfaces = nb_surfaces;
907 // otherwise use user specified value
910 ctx->nb_surfaces = FFMAX(1, FFMIN(MAX_REGISTERED_FRAMES, ctx->nb_surfaces));
911 ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
915 static int nvenc_setup_encoder(AVCodecContext *avctx)
917 NVENCContext *ctx = avctx->priv_data;
918 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
919 NV_ENC_PRESET_CONFIG preset_cfg = { 0 };
920 AVCPBProperties *cpb_props;
923 ctx->params.version = NV_ENC_INITIALIZE_PARAMS_VER;
925 ctx->params.encodeHeight = avctx->height;
926 ctx->params.encodeWidth = avctx->width;
928 if (avctx->sample_aspect_ratio.num &&
929 avctx->sample_aspect_ratio.den &&
930 (avctx->sample_aspect_ratio.num != 1 ||
931 avctx->sample_aspect_ratio.den != 1)) {
932 av_reduce(&ctx->params.darWidth,
933 &ctx->params.darHeight,
934 avctx->width * avctx->sample_aspect_ratio.num,
935 avctx->height * avctx->sample_aspect_ratio.den,
938 ctx->params.darHeight = avctx->height;
939 ctx->params.darWidth = avctx->width;
942 // De-compensate for hardware, dubiously, trying to compensate for
943 // playback at 704 pixel width.
944 if (avctx->width == 720 && (avctx->height == 480 || avctx->height == 576)) {
945 av_reduce(&ctx->params.darWidth, &ctx->params.darHeight,
946 ctx->params.darWidth * 44,
947 ctx->params.darHeight * 45,
951 ctx->params.frameRateNum = avctx->time_base.den;
952 ctx->params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
954 ctx->params.enableEncodeAsync = 0;
955 ctx->params.enablePTD = 1;
957 ctx->params.encodeConfig = &ctx->config;
959 nvenc_map_preset(ctx);
961 preset_cfg.version = NV_ENC_PRESET_CONFIG_VER;
962 preset_cfg.presetCfg.version = NV_ENC_CONFIG_VER;
964 ret = nv->nvEncGetEncodePresetConfig(ctx->nvenc_ctx,
965 ctx->params.encodeGUID,
966 ctx->params.presetGUID,
968 if (ret != NV_ENC_SUCCESS)
969 return nvenc_print_error(avctx, ret, "Cannot get the preset configuration");
971 memcpy(&ctx->config, &preset_cfg.presetCfg, sizeof(ctx->config));
973 ctx->config.version = NV_ENC_CONFIG_VER;
975 if (avctx->gop_size > 0) {
976 if (avctx->max_b_frames > 0) {
980 * 3 two B-frames, and so on. */
981 ctx->config.frameIntervalP = avctx->max_b_frames + 1;
982 } else if (avctx->max_b_frames == 0) {
983 ctx->config.frameIntervalP = 1;
985 ctx->config.gopLength = avctx->gop_size;
986 } else if (avctx->gop_size == 0) {
987 ctx->config.frameIntervalP = 0;
988 ctx->config.gopLength = 1;
991 if (ctx->config.frameIntervalP > 1)
992 avctx->max_b_frames = ctx->config.frameIntervalP - 1;
994 ctx->initial_pts[0] = AV_NOPTS_VALUE;
995 ctx->initial_pts[1] = AV_NOPTS_VALUE;
997 nvenc_recalc_surfaces(avctx);
999 nvenc_setup_rate_control(avctx);
1001 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1002 ctx->config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
1004 ctx->config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
1007 if ((ret = nvenc_setup_codec_config(avctx)) < 0)
1010 ret = nv->nvEncInitializeEncoder(ctx->nvenc_ctx, &ctx->params);
1011 if (ret != NV_ENC_SUCCESS)
1012 return nvenc_print_error(avctx, ret, "InitializeEncoder failed");
1014 cpb_props = ff_add_cpb_side_data(avctx);
1016 return AVERROR(ENOMEM);
1017 cpb_props->max_bitrate = avctx->rc_max_rate;
1018 cpb_props->min_bitrate = avctx->rc_min_rate;
1019 cpb_props->avg_bitrate = avctx->bit_rate;
1020 cpb_props->buffer_size = avctx->rc_buffer_size;
1025 static int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
1027 NVENCContext *ctx = avctx->priv_data;
1028 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1029 NVENCFrame *tmp_surface = &ctx->frames[idx];
1031 NV_ENC_CREATE_BITSTREAM_BUFFER out_buffer = { 0 };
1033 switch (ctx->data_pix_fmt) {
1034 case AV_PIX_FMT_YUV420P:
1035 ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YV12_PL;
1037 case AV_PIX_FMT_NV12:
1038 ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_NV12_PL;
1040 case AV_PIX_FMT_YUV444P:
1041 ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YUV444_PL;
1043 #if NVENCAPI_MAJOR_VERSION >= 7
1044 case AV_PIX_FMT_P010:
1045 ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1047 case AV_PIX_FMT_YUV444P16:
1048 ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1050 #endif /* NVENCAPI_MAJOR_VERSION >= 7 */
1055 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1056 ctx->frames[idx].in_ref = av_frame_alloc();
1057 if (!ctx->frames[idx].in_ref)
1058 return AVERROR(ENOMEM);
1060 NV_ENC_CREATE_INPUT_BUFFER in_buffer = { 0 };
1062 in_buffer.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1064 in_buffer.width = avctx->width;
1065 in_buffer.height = avctx->height;
1067 in_buffer.bufferFmt = ctx->frames[idx].format;
1068 in_buffer.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED;
1070 ret = nv->nvEncCreateInputBuffer(ctx->nvenc_ctx, &in_buffer);
1071 if (ret != NV_ENC_SUCCESS)
1072 return nvenc_print_error(avctx, ret, "CreateInputBuffer failed");
1074 ctx->frames[idx].in = in_buffer.inputBuffer;
1077 out_buffer.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1078 /* 1MB is large enough to hold most output frames.
1079 * NVENC increases this automatically if it is not enough. */
1080 out_buffer.size = BITSTREAM_BUFFER_SIZE;
1082 out_buffer.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED;
1084 ret = nv->nvEncCreateBitstreamBuffer(ctx->nvenc_ctx, &out_buffer);
1085 if (ret != NV_ENC_SUCCESS)
1086 return nvenc_print_error(avctx, ret, "CreateBitstreamBuffer failed");
1088 ctx->frames[idx].out = out_buffer.bitstreamBuffer;
1090 av_fifo_generic_write(ctx->unused_surface_queue, &tmp_surface, sizeof(tmp_surface), NULL);
1095 static int nvenc_setup_surfaces(AVCodecContext *avctx)
1097 NVENCContext *ctx = avctx->priv_data;
1100 ctx->frames = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->frames));
1102 return AVERROR(ENOMEM);
1104 ctx->timestamps = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
1105 if (!ctx->timestamps)
1106 return AVERROR(ENOMEM);
1107 ctx->unused_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NVENCFrame*));
1108 if (!ctx->unused_surface_queue)
1109 return AVERROR(ENOMEM);
1110 ctx->pending = av_fifo_alloc(ctx->nb_surfaces * sizeof(*ctx->frames));
1112 return AVERROR(ENOMEM);
1113 ctx->ready = av_fifo_alloc(ctx->nb_surfaces * sizeof(*ctx->frames));
1115 return AVERROR(ENOMEM);
1117 for (i = 0; i < ctx->nb_surfaces; i++) {
1118 if ((ret = nvenc_alloc_surface(avctx, i)) < 0)
1125 #define EXTRADATA_SIZE 512
1127 static int nvenc_setup_extradata(AVCodecContext *avctx)
1129 NVENCContext *ctx = avctx->priv_data;
1130 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1131 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1134 avctx->extradata = av_mallocz(EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
1135 if (!avctx->extradata)
1136 return AVERROR(ENOMEM);
1138 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1139 payload.spsppsBuffer = avctx->extradata;
1140 payload.inBufferSize = EXTRADATA_SIZE;
1141 payload.outSPSPPSPayloadSize = &avctx->extradata_size;
1143 ret = nv->nvEncGetSequenceParams(ctx->nvenc_ctx, &payload);
1144 if (ret != NV_ENC_SUCCESS)
1145 return nvenc_print_error(avctx, ret, "Cannot get the extradata");
1150 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
1152 NVENCContext *ctx = avctx->priv_data;
1153 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1156 /* the encoder has to be flushed before it can be closed */
1157 if (ctx->nvenc_ctx) {
1158 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
1159 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
1161 nv->nvEncEncodePicture(ctx->nvenc_ctx, ¶ms);
1164 av_fifo_free(ctx->timestamps);
1165 av_fifo_free(ctx->pending);
1166 av_fifo_free(ctx->ready);
1167 av_fifo_free(ctx->unused_surface_queue);
1170 for (i = 0; i < ctx->nb_surfaces; ++i) {
1171 if (avctx->pix_fmt != AV_PIX_FMT_CUDA) {
1172 nv->nvEncDestroyInputBuffer(ctx->nvenc_ctx, ctx->frames[i].in);
1173 } else if (ctx->frames[i].in) {
1174 nv->nvEncUnmapInputResource(ctx->nvenc_ctx, ctx->frames[i].in_map.mappedResource);
1177 av_frame_free(&ctx->frames[i].in_ref);
1178 nv->nvEncDestroyBitstreamBuffer(ctx->nvenc_ctx, ctx->frames[i].out);
1181 for (i = 0; i < ctx->nb_registered_frames; i++) {
1182 if (ctx->registered_frames[i].regptr)
1183 nv->nvEncUnregisterResource(ctx->nvenc_ctx, ctx->registered_frames[i].regptr);
1185 ctx->nb_registered_frames = 0;
1187 av_freep(&ctx->frames);
1190 nv->nvEncDestroyEncoder(ctx->nvenc_ctx);
1192 if (ctx->cu_context_internal)
1193 ctx->nvel.cu_ctx_destroy(ctx->cu_context_internal);
1195 if (ctx->nvel.nvenc)
1196 dlclose(ctx->nvel.nvenc);
1200 dlclose(ctx->nvel.cuda);
1206 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
1208 NVENCContext *ctx = avctx->priv_data;
1211 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1212 AVHWFramesContext *frames_ctx;
1213 if (!avctx->hw_frames_ctx) {
1214 av_log(avctx, AV_LOG_ERROR,
1215 "hw_frames_ctx must be set when using GPU frames as input\n");
1216 return AVERROR(EINVAL);
1218 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1219 ctx->data_pix_fmt = frames_ctx->sw_format;
1221 ctx->data_pix_fmt = avctx->pix_fmt;
1224 if ((ret = nvenc_load_libraries(avctx)) < 0)
1227 if ((ret = nvenc_setup_device(avctx)) < 0)
1230 if ((ret = nvenc_setup_encoder(avctx)) < 0)
1233 if ((ret = nvenc_setup_surfaces(avctx)) < 0)
1236 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1237 if ((ret = nvenc_setup_extradata(avctx)) < 0)
1244 static NVENCFrame *get_free_frame(NVENCContext *ctx)
1246 NVENCFrame *tmp_surf;
1248 if (!(av_fifo_size(ctx->unused_surface_queue) > 0))
1252 av_fifo_generic_read(ctx->unused_surface_queue, &tmp_surf, sizeof(tmp_surf), NULL);
1256 static int nvenc_copy_frame(NV_ENC_LOCK_INPUT_BUFFER *in, const AVFrame *frame)
1258 uint8_t *buf = in->bufferDataPtr;
1259 int off = frame->height * in->pitch;
1261 switch (frame->format) {
1262 case AV_PIX_FMT_YUV420P:
1263 av_image_copy_plane(buf, in->pitch,
1264 frame->data[0], frame->linesize[0],
1265 frame->width, frame->height);
1268 av_image_copy_plane(buf, in->pitch >> 1,
1269 frame->data[2], frame->linesize[2],
1270 frame->width >> 1, frame->height >> 1);
1274 av_image_copy_plane(buf, in->pitch >> 1,
1275 frame->data[1], frame->linesize[1],
1276 frame->width >> 1, frame->height >> 1);
1278 case AV_PIX_FMT_NV12:
1279 av_image_copy_plane(buf, in->pitch,
1280 frame->data[0], frame->linesize[0],
1281 frame->width, frame->height);
1284 av_image_copy_plane(buf, in->pitch,
1285 frame->data[1], frame->linesize[1],
1286 frame->width, frame->height >> 1);
1288 case AV_PIX_FMT_P010:
1289 av_image_copy_plane(buf, in->pitch,
1290 frame->data[0], frame->linesize[0],
1291 frame->width << 1, frame->height);
1294 av_image_copy_plane(buf, in->pitch,
1295 frame->data[1], frame->linesize[1],
1296 frame->width << 1, frame->height >> 1);
1298 case AV_PIX_FMT_YUV444P:
1299 av_image_copy_plane(buf, in->pitch,
1300 frame->data[0], frame->linesize[0],
1301 frame->width, frame->height);
1304 av_image_copy_plane(buf, in->pitch,
1305 frame->data[1], frame->linesize[1],
1306 frame->width, frame->height);
1309 av_image_copy_plane(buf, in->pitch,
1310 frame->data[2], frame->linesize[2],
1311 frame->width, frame->height);
1313 case AV_PIX_FMT_YUV444P16:
1314 av_image_copy_plane(buf, in->pitch,
1315 frame->data[0], frame->linesize[0],
1316 frame->width << 1, frame->height);
1319 av_image_copy_plane(buf, in->pitch,
1320 frame->data[1], frame->linesize[1],
1321 frame->width << 1, frame->height);
1324 av_image_copy_plane(buf, in->pitch,
1325 frame->data[2], frame->linesize[2],
1326 frame->width << 1, frame->height);
1335 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1337 NVENCContext *ctx = avctx->priv_data;
1338 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1341 if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1342 for (i = 0; i < ctx->nb_registered_frames; i++) {
1343 if (!ctx->registered_frames[i].mapped) {
1344 if (ctx->registered_frames[i].regptr) {
1345 nv->nvEncUnregisterResource(ctx->nvenc_ctx,
1346 ctx->registered_frames[i].regptr);
1347 ctx->registered_frames[i].regptr = NULL;
1353 return ctx->nb_registered_frames++;
1356 av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1357 return AVERROR(ENOMEM);
1360 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1362 NVENCContext *ctx = avctx->priv_data;
1363 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1364 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1365 NV_ENC_REGISTER_RESOURCE reg;
1368 for (i = 0; i < ctx->nb_registered_frames; i++) {
1369 if (ctx->registered_frames[i].ptr == (CUdeviceptr)frame->data[0])
1373 idx = nvenc_find_free_reg_resource(avctx);
1377 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1378 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1379 reg.width = frames_ctx->width;
1380 reg.height = frames_ctx->height;
1381 reg.bufferFormat = ctx->frames[0].format;
1382 reg.pitch = frame->linesize[0];
1383 reg.resourceToRegister = frame->data[0];
1385 ret = nv->nvEncRegisterResource(ctx->nvenc_ctx, ®);
1386 if (ret != NV_ENC_SUCCESS) {
1387 nvenc_print_error(avctx, ret, "Error registering an input resource");
1388 return AVERROR_UNKNOWN;
1391 ctx->registered_frames[idx].ptr = (CUdeviceptr)frame->data[0];
1392 ctx->registered_frames[idx].regptr = reg.registeredResource;
1396 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1397 NVENCFrame *nvenc_frame)
1399 NVENCContext *ctx = avctx->priv_data;
1400 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1403 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1406 ret = nvenc_register_frame(avctx, frame);
1408 av_log(avctx, AV_LOG_ERROR, "Could not register an input CUDA frame\n");
1413 ret = av_frame_ref(nvenc_frame->in_ref, frame);
1417 nvenc_frame->in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1418 nvenc_frame->in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1420 ret = nv->nvEncMapInputResource(ctx->nvenc_ctx, &nvenc_frame->in_map);
1421 if (ret != NV_ENC_SUCCESS) {
1422 av_frame_unref(nvenc_frame->in_ref);
1423 return nvenc_print_error(avctx, ret, "Error mapping an input resource");
1426 ctx->registered_frames[reg_idx].mapped = 1;
1427 nvenc_frame->reg_idx = reg_idx;
1428 nvenc_frame->in = nvenc_frame->in_map.mappedResource;
1430 NV_ENC_LOCK_INPUT_BUFFER params = { 0 };
1432 params.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1433 params.inputBuffer = nvenc_frame->in;
1435 ret = nv->nvEncLockInputBuffer(ctx->nvenc_ctx, ¶ms);
1436 if (ret != NV_ENC_SUCCESS)
1437 return nvenc_print_error(avctx, ret, "Cannot lock the buffer");
1439 ret = nvenc_copy_frame(¶ms, frame);
1441 nv->nvEncUnlockInputBuffer(ctx->nvenc_ctx, nvenc_frame->in);
1445 ret = nv->nvEncUnlockInputBuffer(ctx->nvenc_ctx, nvenc_frame->in);
1446 if (ret != NV_ENC_SUCCESS)
1447 return nvenc_print_error(avctx, ret, "Cannot unlock the buffer");
1453 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1454 NV_ENC_PIC_PARAMS *params)
1456 NVENCContext *ctx = avctx->priv_data;
1458 switch (avctx->codec->id) {
1459 case AV_CODEC_ID_H264:
1460 params->codecPicParams.h264PicParams.sliceMode =
1461 ctx->config.encodeCodecConfig.h264Config.sliceMode;
1462 params->codecPicParams.h264PicParams.sliceModeData =
1463 ctx->config.encodeCodecConfig.h264Config.sliceModeData;
1465 case AV_CODEC_ID_HEVC:
1466 params->codecPicParams.hevcPicParams.sliceMode =
1467 ctx->config.encodeCodecConfig.hevcConfig.sliceMode;
1468 params->codecPicParams.hevcPicParams.sliceModeData =
1469 ctx->config.encodeCodecConfig.hevcConfig.sliceModeData;
1474 static inline int nvenc_enqueue_timestamp(AVFifoBuffer *f, int64_t pts)
1476 return av_fifo_generic_write(f, &pts, sizeof(pts), NULL);
1479 static inline int nvenc_dequeue_timestamp(AVFifoBuffer *f, int64_t *pts)
1481 return av_fifo_generic_read(f, pts, sizeof(*pts), NULL);
1484 static int nvenc_set_timestamp(AVCodecContext *avctx,
1485 NV_ENC_LOCK_BITSTREAM *params,
1488 NVENCContext *ctx = avctx->priv_data;
1490 pkt->pts = params->outputTimeStamp;
1491 pkt->duration = params->outputDuration;
1493 /* generate the first dts by linearly extrapolating the
1494 * first two pts values to the past */
1495 if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
1496 ctx->initial_pts[1] != AV_NOPTS_VALUE) {
1497 int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
1500 if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
1501 (ts0 > 0 && ts1 < INT64_MIN + ts0))
1502 return AVERROR(ERANGE);
1505 if ((delta < 0 && ts0 > INT64_MAX + delta) ||
1506 (delta > 0 && ts0 < INT64_MIN + delta))
1507 return AVERROR(ERANGE);
1508 pkt->dts = ts0 - delta;
1510 ctx->first_packet_output = 1;
1513 return nvenc_dequeue_timestamp(ctx->timestamps, &pkt->dts);
1516 static int nvenc_get_output(AVCodecContext *avctx, AVPacket *pkt)
1518 NVENCContext *ctx = avctx->priv_data;
1519 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1520 NV_ENC_LOCK_BITSTREAM params = { 0 };
1524 ret = av_fifo_generic_read(ctx->ready, &frame, sizeof(frame), NULL);
1528 params.version = NV_ENC_LOCK_BITSTREAM_VER;
1529 params.outputBitstream = frame->out;
1531 ret = nv->nvEncLockBitstream(ctx->nvenc_ctx, ¶ms);
1533 return nvenc_print_error(avctx, ret, "Cannot lock the bitstream");
1535 ret = ff_alloc_packet(pkt, params.bitstreamSizeInBytes);
1539 memcpy(pkt->data, params.bitstreamBufferPtr, pkt->size);
1541 ret = nv->nvEncUnlockBitstream(ctx->nvenc_ctx, frame->out);
1543 return nvenc_print_error(avctx, ret, "Cannot unlock the bitstream");
1545 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1546 nv->nvEncUnmapInputResource(ctx->nvenc_ctx, frame->in_map.mappedResource);
1547 av_frame_unref(frame->in_ref);
1548 ctx->registered_frames[frame->reg_idx].mapped = 0;
1553 av_fifo_generic_write(ctx->unused_surface_queue, &frame, sizeof(frame), NULL);
1555 ret = nvenc_set_timestamp(avctx, ¶ms, pkt);
1559 switch (params.pictureType) {
1560 case NV_ENC_PIC_TYPE_IDR:
1561 pkt->flags |= AV_PKT_FLAG_KEY;
1562 #if FF_API_CODED_FRAME
1563 FF_DISABLE_DEPRECATION_WARNINGS
1564 case NV_ENC_PIC_TYPE_INTRA_REFRESH:
1565 case NV_ENC_PIC_TYPE_I:
1566 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
1568 case NV_ENC_PIC_TYPE_P:
1569 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
1571 case NV_ENC_PIC_TYPE_B:
1572 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;
1574 case NV_ENC_PIC_TYPE_BI:
1575 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_BI;
1577 FF_ENABLE_DEPRECATION_WARNINGS
1584 static int output_ready(AVCodecContext *avctx, int flush)
1586 NVENCContext *ctx = avctx->priv_data;
1587 int nb_ready, nb_pending;
1589 /* when B-frames are enabled, we wait for two initial timestamps to
1590 * calculate the first dts */
1591 if (!flush && avctx->max_b_frames > 0 &&
1592 (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
1595 nb_ready = av_fifo_size(ctx->ready) / sizeof(NVENCFrame*);
1596 nb_pending = av_fifo_size(ctx->pending) / sizeof(NVENCFrame*);
1598 return nb_ready > 0;
1599 return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
1602 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1603 const AVFrame *frame, int *got_packet)
1605 NVENCContext *ctx = avctx->priv_data;
1606 NVENCLibraryContext *nvel = &ctx->nvel;
1607 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1608 NV_ENC_PIC_PARAMS params = { 0 };
1609 NVENCFrame *nvenc_frame = NULL;
1613 params.version = NV_ENC_PIC_PARAMS_VER;
1616 nvenc_frame = get_free_frame(ctx);
1618 av_log(avctx, AV_LOG_ERROR, "No free surfaces\n");
1622 ret = nvenc_upload_frame(avctx, frame, nvenc_frame);
1626 params.inputBuffer = nvenc_frame->in;
1627 params.bufferFmt = nvenc_frame->format;
1628 params.inputWidth = frame->width;
1629 params.inputHeight = frame->height;
1630 params.outputBitstream = nvenc_frame->out;
1631 params.inputTimeStamp = frame->pts;
1633 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1634 if (frame->top_field_first)
1635 params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
1637 params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
1639 params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1642 nvenc_codec_specific_pic_params(avctx, ¶ms);
1644 ret = nvenc_enqueue_timestamp(ctx->timestamps, frame->pts);
1648 if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
1649 ctx->initial_pts[0] = frame->pts;
1650 else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
1651 ctx->initial_pts[1] = frame->pts;
1653 params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1656 nvel->cu_ctx_push_current(ctx->cu_context);
1657 enc_ret = nv->nvEncEncodePicture(ctx->nvenc_ctx, ¶ms);
1658 nvel->cu_ctx_pop_current(&dummy);
1660 if (enc_ret != NV_ENC_SUCCESS &&
1661 enc_ret != NV_ENC_ERR_NEED_MORE_INPUT)
1662 return nvenc_print_error(avctx, enc_ret, "Error encoding the frame");
1665 ret = av_fifo_generic_write(ctx->pending, &nvenc_frame, sizeof(nvenc_frame), NULL);
1670 /* all the pending buffers are now ready for output */
1671 if (enc_ret == NV_ENC_SUCCESS) {
1672 while (av_fifo_size(ctx->pending) > 0) {
1673 av_fifo_generic_read(ctx->pending, &nvenc_frame, sizeof(nvenc_frame), NULL);
1674 av_fifo_generic_write(ctx->ready, &nvenc_frame, sizeof(nvenc_frame), NULL);
1678 if (output_ready(avctx, !frame)) {
1679 ret = nvenc_get_output(avctx, pkt);