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_setup_encoder(AVCodecContext *avctx)
879 NVENCContext *ctx = avctx->priv_data;
880 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
881 NV_ENC_PRESET_CONFIG preset_cfg = { 0 };
882 AVCPBProperties *cpb_props;
885 ctx->params.version = NV_ENC_INITIALIZE_PARAMS_VER;
887 ctx->params.encodeHeight = avctx->height;
888 ctx->params.encodeWidth = avctx->width;
890 if (avctx->sample_aspect_ratio.num &&
891 avctx->sample_aspect_ratio.den &&
892 (avctx->sample_aspect_ratio.num != 1 ||
893 avctx->sample_aspect_ratio.den != 1)) {
894 av_reduce(&ctx->params.darWidth,
895 &ctx->params.darHeight,
896 avctx->width * avctx->sample_aspect_ratio.num,
897 avctx->height * avctx->sample_aspect_ratio.den,
900 ctx->params.darHeight = avctx->height;
901 ctx->params.darWidth = avctx->width;
904 // De-compensate for hardware, dubiously, trying to compensate for
905 // playback at 704 pixel width.
906 if (avctx->width == 720 && (avctx->height == 480 || avctx->height == 576)) {
907 av_reduce(&ctx->params.darWidth, &ctx->params.darHeight,
908 ctx->params.darWidth * 44,
909 ctx->params.darHeight * 45,
913 ctx->params.frameRateNum = avctx->time_base.den;
914 ctx->params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
916 ctx->params.enableEncodeAsync = 0;
917 ctx->params.enablePTD = 1;
919 ctx->params.encodeConfig = &ctx->config;
921 nvenc_map_preset(ctx);
923 preset_cfg.version = NV_ENC_PRESET_CONFIG_VER;
924 preset_cfg.presetCfg.version = NV_ENC_CONFIG_VER;
926 ret = nv->nvEncGetEncodePresetConfig(ctx->nvenc_ctx,
927 ctx->params.encodeGUID,
928 ctx->params.presetGUID,
930 if (ret != NV_ENC_SUCCESS)
931 return nvenc_print_error(avctx, ret, "Cannot get the preset configuration");
933 memcpy(&ctx->config, &preset_cfg.presetCfg, sizeof(ctx->config));
935 ctx->config.version = NV_ENC_CONFIG_VER;
937 if (avctx->gop_size > 0) {
938 if (avctx->max_b_frames > 0) {
942 * 3 two B-frames, and so on. */
943 ctx->config.frameIntervalP = avctx->max_b_frames + 1;
944 } else if (avctx->max_b_frames == 0) {
945 ctx->config.frameIntervalP = 1;
947 ctx->config.gopLength = avctx->gop_size;
948 } else if (avctx->gop_size == 0) {
949 ctx->config.frameIntervalP = 0;
950 ctx->config.gopLength = 1;
953 if (ctx->config.frameIntervalP > 1)
954 avctx->max_b_frames = ctx->config.frameIntervalP - 1;
956 ctx->initial_pts[0] = AV_NOPTS_VALUE;
957 ctx->initial_pts[1] = AV_NOPTS_VALUE;
959 nvenc_setup_rate_control(avctx);
961 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
962 ctx->config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
964 ctx->config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
967 if ((ret = nvenc_setup_codec_config(avctx)) < 0)
970 ret = nv->nvEncInitializeEncoder(ctx->nvenc_ctx, &ctx->params);
971 if (ret != NV_ENC_SUCCESS)
972 return nvenc_print_error(avctx, ret, "InitializeEncoder failed");
974 cpb_props = ff_add_cpb_side_data(avctx);
976 return AVERROR(ENOMEM);
977 cpb_props->max_bitrate = avctx->rc_max_rate;
978 cpb_props->min_bitrate = avctx->rc_min_rate;
979 cpb_props->avg_bitrate = avctx->bit_rate;
980 cpb_props->buffer_size = avctx->rc_buffer_size;
985 static int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
987 NVENCContext *ctx = avctx->priv_data;
988 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
990 NV_ENC_CREATE_BITSTREAM_BUFFER out_buffer = { 0 };
992 switch (ctx->data_pix_fmt) {
993 case AV_PIX_FMT_YUV420P:
994 ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YV12_PL;
996 case AV_PIX_FMT_NV12:
997 ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_NV12_PL;
999 case AV_PIX_FMT_YUV444P:
1000 ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YUV444_PL;
1002 #if NVENCAPI_MAJOR_VERSION >= 7
1003 case AV_PIX_FMT_P010:
1004 ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1006 case AV_PIX_FMT_YUV444P16:
1007 ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1009 #endif /* NVENCAPI_MAJOR_VERSION >= 7 */
1014 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1015 ctx->frames[idx].in_ref = av_frame_alloc();
1016 if (!ctx->frames[idx].in_ref)
1017 return AVERROR(ENOMEM);
1019 NV_ENC_CREATE_INPUT_BUFFER in_buffer = { 0 };
1021 in_buffer.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1023 in_buffer.width = avctx->width;
1024 in_buffer.height = avctx->height;
1026 in_buffer.bufferFmt = ctx->frames[idx].format;
1027 in_buffer.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED;
1029 ret = nv->nvEncCreateInputBuffer(ctx->nvenc_ctx, &in_buffer);
1030 if (ret != NV_ENC_SUCCESS)
1031 return nvenc_print_error(avctx, ret, "CreateInputBuffer failed");
1033 ctx->frames[idx].in = in_buffer.inputBuffer;
1036 out_buffer.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1037 /* 1MB is large enough to hold most output frames.
1038 * NVENC increases this automatically if it is not enough. */
1039 out_buffer.size = BITSTREAM_BUFFER_SIZE;
1041 out_buffer.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED;
1043 ret = nv->nvEncCreateBitstreamBuffer(ctx->nvenc_ctx, &out_buffer);
1044 if (ret != NV_ENC_SUCCESS)
1045 return nvenc_print_error(avctx, ret, "CreateBitstreamBuffer failed");
1047 ctx->frames[idx].out = out_buffer.bitstreamBuffer;
1052 static int nvenc_setup_surfaces(AVCodecContext *avctx)
1054 NVENCContext *ctx = avctx->priv_data;
1057 ctx->nb_surfaces = FFMAX(4 + avctx->max_b_frames,
1059 ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
1062 ctx->frames = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->frames));
1064 return AVERROR(ENOMEM);
1066 ctx->timestamps = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
1067 if (!ctx->timestamps)
1068 return AVERROR(ENOMEM);
1069 ctx->pending = av_fifo_alloc(ctx->nb_surfaces * sizeof(*ctx->frames));
1071 return AVERROR(ENOMEM);
1072 ctx->ready = av_fifo_alloc(ctx->nb_surfaces * sizeof(*ctx->frames));
1074 return AVERROR(ENOMEM);
1076 for (i = 0; i < ctx->nb_surfaces; i++) {
1077 if ((ret = nvenc_alloc_surface(avctx, i)) < 0)
1084 #define EXTRADATA_SIZE 512
1086 static int nvenc_setup_extradata(AVCodecContext *avctx)
1088 NVENCContext *ctx = avctx->priv_data;
1089 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1090 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1093 avctx->extradata = av_mallocz(EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
1094 if (!avctx->extradata)
1095 return AVERROR(ENOMEM);
1097 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1098 payload.spsppsBuffer = avctx->extradata;
1099 payload.inBufferSize = EXTRADATA_SIZE;
1100 payload.outSPSPPSPayloadSize = &avctx->extradata_size;
1102 ret = nv->nvEncGetSequenceParams(ctx->nvenc_ctx, &payload);
1103 if (ret != NV_ENC_SUCCESS)
1104 return nvenc_print_error(avctx, ret, "Cannot get the extradata");
1109 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
1111 NVENCContext *ctx = avctx->priv_data;
1112 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1115 /* the encoder has to be flushed before it can be closed */
1116 if (ctx->nvenc_ctx) {
1117 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
1118 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
1120 nv->nvEncEncodePicture(ctx->nvenc_ctx, ¶ms);
1123 av_fifo_free(ctx->timestamps);
1124 av_fifo_free(ctx->pending);
1125 av_fifo_free(ctx->ready);
1128 for (i = 0; i < ctx->nb_surfaces; ++i) {
1129 if (avctx->pix_fmt != AV_PIX_FMT_CUDA) {
1130 nv->nvEncDestroyInputBuffer(ctx->nvenc_ctx, ctx->frames[i].in);
1131 } else if (ctx->frames[i].in) {
1132 nv->nvEncUnmapInputResource(ctx->nvenc_ctx, ctx->frames[i].in_map.mappedResource);
1135 av_frame_free(&ctx->frames[i].in_ref);
1136 nv->nvEncDestroyBitstreamBuffer(ctx->nvenc_ctx, ctx->frames[i].out);
1139 for (i = 0; i < ctx->nb_registered_frames; i++) {
1140 if (ctx->registered_frames[i].regptr)
1141 nv->nvEncUnregisterResource(ctx->nvenc_ctx, ctx->registered_frames[i].regptr);
1143 ctx->nb_registered_frames = 0;
1145 av_freep(&ctx->frames);
1148 nv->nvEncDestroyEncoder(ctx->nvenc_ctx);
1150 if (ctx->cu_context_internal)
1151 ctx->nvel.cu_ctx_destroy(ctx->cu_context_internal);
1153 if (ctx->nvel.nvenc)
1154 dlclose(ctx->nvel.nvenc);
1158 dlclose(ctx->nvel.cuda);
1164 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
1166 NVENCContext *ctx = avctx->priv_data;
1169 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1170 AVHWFramesContext *frames_ctx;
1171 if (!avctx->hw_frames_ctx) {
1172 av_log(avctx, AV_LOG_ERROR,
1173 "hw_frames_ctx must be set when using GPU frames as input\n");
1174 return AVERROR(EINVAL);
1176 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1177 ctx->data_pix_fmt = frames_ctx->sw_format;
1179 ctx->data_pix_fmt = avctx->pix_fmt;
1182 if ((ret = nvenc_load_libraries(avctx)) < 0)
1185 if ((ret = nvenc_setup_device(avctx)) < 0)
1188 if ((ret = nvenc_setup_encoder(avctx)) < 0)
1191 if ((ret = nvenc_setup_surfaces(avctx)) < 0)
1194 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1195 if ((ret = nvenc_setup_extradata(avctx)) < 0)
1202 static NVENCFrame *get_free_frame(NVENCContext *ctx)
1206 for (i = 0; i < ctx->nb_surfaces; i++) {
1207 if (!ctx->frames[i].locked) {
1208 ctx->frames[i].locked = 1;
1209 return &ctx->frames[i];
1216 static int nvenc_copy_frame(NV_ENC_LOCK_INPUT_BUFFER *in, const AVFrame *frame)
1218 uint8_t *buf = in->bufferDataPtr;
1219 int off = frame->height * in->pitch;
1221 switch (frame->format) {
1222 case AV_PIX_FMT_YUV420P:
1223 av_image_copy_plane(buf, in->pitch,
1224 frame->data[0], frame->linesize[0],
1225 frame->width, frame->height);
1228 av_image_copy_plane(buf, in->pitch >> 1,
1229 frame->data[2], frame->linesize[2],
1230 frame->width >> 1, frame->height >> 1);
1234 av_image_copy_plane(buf, in->pitch >> 1,
1235 frame->data[1], frame->linesize[1],
1236 frame->width >> 1, frame->height >> 1);
1238 case AV_PIX_FMT_NV12:
1239 av_image_copy_plane(buf, in->pitch,
1240 frame->data[0], frame->linesize[0],
1241 frame->width, frame->height);
1244 av_image_copy_plane(buf, in->pitch,
1245 frame->data[1], frame->linesize[1],
1246 frame->width, frame->height >> 1);
1248 case AV_PIX_FMT_P010:
1249 av_image_copy_plane(buf, in->pitch,
1250 frame->data[0], frame->linesize[0],
1251 frame->width << 1, frame->height);
1254 av_image_copy_plane(buf, in->pitch,
1255 frame->data[1], frame->linesize[1],
1256 frame->width << 1, frame->height >> 1);
1258 case AV_PIX_FMT_YUV444P:
1259 av_image_copy_plane(buf, in->pitch,
1260 frame->data[0], frame->linesize[0],
1261 frame->width, frame->height);
1264 av_image_copy_plane(buf, in->pitch,
1265 frame->data[1], frame->linesize[1],
1266 frame->width, frame->height);
1269 av_image_copy_plane(buf, in->pitch,
1270 frame->data[2], frame->linesize[2],
1271 frame->width, frame->height);
1273 case AV_PIX_FMT_YUV444P16:
1274 av_image_copy_plane(buf, in->pitch,
1275 frame->data[0], frame->linesize[0],
1276 frame->width << 1, frame->height);
1279 av_image_copy_plane(buf, in->pitch,
1280 frame->data[1], frame->linesize[1],
1281 frame->width << 1, frame->height);
1284 av_image_copy_plane(buf, in->pitch,
1285 frame->data[2], frame->linesize[2],
1286 frame->width << 1, frame->height);
1295 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1297 NVENCContext *ctx = avctx->priv_data;
1298 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1301 if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1302 for (i = 0; i < ctx->nb_registered_frames; i++) {
1303 if (!ctx->registered_frames[i].mapped) {
1304 if (ctx->registered_frames[i].regptr) {
1305 nv->nvEncUnregisterResource(ctx->nvenc_ctx,
1306 ctx->registered_frames[i].regptr);
1307 ctx->registered_frames[i].regptr = NULL;
1313 return ctx->nb_registered_frames++;
1316 av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1317 return AVERROR(ENOMEM);
1320 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1322 NVENCContext *ctx = avctx->priv_data;
1323 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1324 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1325 NV_ENC_REGISTER_RESOURCE reg;
1328 for (i = 0; i < ctx->nb_registered_frames; i++) {
1329 if (ctx->registered_frames[i].ptr == (CUdeviceptr)frame->data[0])
1333 idx = nvenc_find_free_reg_resource(avctx);
1337 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1338 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1339 reg.width = frames_ctx->width;
1340 reg.height = frames_ctx->height;
1341 reg.bufferFormat = ctx->frames[0].format;
1342 reg.pitch = frame->linesize[0];
1343 reg.resourceToRegister = frame->data[0];
1345 ret = nv->nvEncRegisterResource(ctx->nvenc_ctx, ®);
1346 if (ret != NV_ENC_SUCCESS) {
1347 nvenc_print_error(avctx, ret, "Error registering an input resource");
1348 return AVERROR_UNKNOWN;
1351 ctx->registered_frames[idx].ptr = (CUdeviceptr)frame->data[0];
1352 ctx->registered_frames[idx].regptr = reg.registeredResource;
1356 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1357 NVENCFrame *nvenc_frame)
1359 NVENCContext *ctx = avctx->priv_data;
1360 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1363 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1366 ret = nvenc_register_frame(avctx, frame);
1368 av_log(avctx, AV_LOG_ERROR, "Could not register an input CUDA frame\n");
1373 ret = av_frame_ref(nvenc_frame->in_ref, frame);
1377 nvenc_frame->in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1378 nvenc_frame->in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1380 ret = nv->nvEncMapInputResource(ctx->nvenc_ctx, &nvenc_frame->in_map);
1381 if (ret != NV_ENC_SUCCESS) {
1382 av_frame_unref(nvenc_frame->in_ref);
1383 return nvenc_print_error(avctx, ret, "Error mapping an input resource");
1386 ctx->registered_frames[reg_idx].mapped = 1;
1387 nvenc_frame->reg_idx = reg_idx;
1388 nvenc_frame->in = nvenc_frame->in_map.mappedResource;
1390 NV_ENC_LOCK_INPUT_BUFFER params = { 0 };
1392 params.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1393 params.inputBuffer = nvenc_frame->in;
1395 ret = nv->nvEncLockInputBuffer(ctx->nvenc_ctx, ¶ms);
1396 if (ret != NV_ENC_SUCCESS)
1397 return nvenc_print_error(avctx, ret, "Cannot lock the buffer");
1399 ret = nvenc_copy_frame(¶ms, frame);
1401 nv->nvEncUnlockInputBuffer(ctx->nvenc_ctx, nvenc_frame->in);
1405 ret = nv->nvEncUnlockInputBuffer(ctx->nvenc_ctx, nvenc_frame->in);
1406 if (ret != NV_ENC_SUCCESS)
1407 return nvenc_print_error(avctx, ret, "Cannot unlock the buffer");
1413 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1414 NV_ENC_PIC_PARAMS *params)
1416 NVENCContext *ctx = avctx->priv_data;
1418 switch (avctx->codec->id) {
1419 case AV_CODEC_ID_H264:
1420 params->codecPicParams.h264PicParams.sliceMode =
1421 ctx->config.encodeCodecConfig.h264Config.sliceMode;
1422 params->codecPicParams.h264PicParams.sliceModeData =
1423 ctx->config.encodeCodecConfig.h264Config.sliceModeData;
1425 case AV_CODEC_ID_HEVC:
1426 params->codecPicParams.hevcPicParams.sliceMode =
1427 ctx->config.encodeCodecConfig.hevcConfig.sliceMode;
1428 params->codecPicParams.hevcPicParams.sliceModeData =
1429 ctx->config.encodeCodecConfig.hevcConfig.sliceModeData;
1434 static inline int nvenc_enqueue_timestamp(AVFifoBuffer *f, int64_t pts)
1436 return av_fifo_generic_write(f, &pts, sizeof(pts), NULL);
1439 static inline int nvenc_dequeue_timestamp(AVFifoBuffer *f, int64_t *pts)
1441 return av_fifo_generic_read(f, pts, sizeof(*pts), NULL);
1444 static int nvenc_set_timestamp(AVCodecContext *avctx,
1445 NV_ENC_LOCK_BITSTREAM *params,
1448 NVENCContext *ctx = avctx->priv_data;
1450 pkt->pts = params->outputTimeStamp;
1451 pkt->duration = params->outputDuration;
1453 /* generate the first dts by linearly extrapolating the
1454 * first two pts values to the past */
1455 if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
1456 ctx->initial_pts[1] != AV_NOPTS_VALUE) {
1457 int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
1460 if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
1461 (ts0 > 0 && ts1 < INT64_MIN + ts0))
1462 return AVERROR(ERANGE);
1465 if ((delta < 0 && ts0 > INT64_MAX + delta) ||
1466 (delta > 0 && ts0 < INT64_MIN + delta))
1467 return AVERROR(ERANGE);
1468 pkt->dts = ts0 - delta;
1470 ctx->first_packet_output = 1;
1473 return nvenc_dequeue_timestamp(ctx->timestamps, &pkt->dts);
1476 static int nvenc_get_output(AVCodecContext *avctx, AVPacket *pkt)
1478 NVENCContext *ctx = avctx->priv_data;
1479 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1480 NV_ENC_LOCK_BITSTREAM params = { 0 };
1484 ret = av_fifo_generic_read(ctx->ready, &frame, sizeof(frame), NULL);
1488 params.version = NV_ENC_LOCK_BITSTREAM_VER;
1489 params.outputBitstream = frame->out;
1491 ret = nv->nvEncLockBitstream(ctx->nvenc_ctx, ¶ms);
1493 return nvenc_print_error(avctx, ret, "Cannot lock the bitstream");
1495 ret = ff_alloc_packet(pkt, params.bitstreamSizeInBytes);
1499 memcpy(pkt->data, params.bitstreamBufferPtr, pkt->size);
1501 ret = nv->nvEncUnlockBitstream(ctx->nvenc_ctx, frame->out);
1503 return nvenc_print_error(avctx, ret, "Cannot unlock the bitstream");
1505 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1506 nv->nvEncUnmapInputResource(ctx->nvenc_ctx, frame->in_map.mappedResource);
1507 av_frame_unref(frame->in_ref);
1508 ctx->registered_frames[frame->reg_idx].mapped = 0;
1515 ret = nvenc_set_timestamp(avctx, ¶ms, pkt);
1519 switch (params.pictureType) {
1520 case NV_ENC_PIC_TYPE_IDR:
1521 pkt->flags |= AV_PKT_FLAG_KEY;
1522 #if FF_API_CODED_FRAME
1523 FF_DISABLE_DEPRECATION_WARNINGS
1524 case NV_ENC_PIC_TYPE_INTRA_REFRESH:
1525 case NV_ENC_PIC_TYPE_I:
1526 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
1528 case NV_ENC_PIC_TYPE_P:
1529 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
1531 case NV_ENC_PIC_TYPE_B:
1532 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;
1534 case NV_ENC_PIC_TYPE_BI:
1535 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_BI;
1537 FF_ENABLE_DEPRECATION_WARNINGS
1544 static int output_ready(AVCodecContext *avctx, int flush)
1546 NVENCContext *ctx = avctx->priv_data;
1547 int nb_ready, nb_pending;
1549 /* when B-frames are enabled, we wait for two initial timestamps to
1550 * calculate the first dts */
1551 if (!flush && avctx->max_b_frames > 0 &&
1552 (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
1555 nb_ready = av_fifo_size(ctx->ready) / sizeof(NVENCFrame*);
1556 nb_pending = av_fifo_size(ctx->pending) / sizeof(NVENCFrame*);
1558 return nb_ready > 0;
1559 return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
1562 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1563 const AVFrame *frame, int *got_packet)
1565 NVENCContext *ctx = avctx->priv_data;
1566 NVENCLibraryContext *nvel = &ctx->nvel;
1567 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1568 NV_ENC_PIC_PARAMS params = { 0 };
1569 NVENCFrame *nvenc_frame = NULL;
1573 params.version = NV_ENC_PIC_PARAMS_VER;
1576 nvenc_frame = get_free_frame(ctx);
1578 av_log(avctx, AV_LOG_ERROR, "No free surfaces\n");
1582 ret = nvenc_upload_frame(avctx, frame, nvenc_frame);
1586 params.inputBuffer = nvenc_frame->in;
1587 params.bufferFmt = nvenc_frame->format;
1588 params.inputWidth = frame->width;
1589 params.inputHeight = frame->height;
1590 params.outputBitstream = nvenc_frame->out;
1591 params.inputTimeStamp = frame->pts;
1593 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1594 if (frame->top_field_first)
1595 params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
1597 params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
1599 params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1602 nvenc_codec_specific_pic_params(avctx, ¶ms);
1604 ret = nvenc_enqueue_timestamp(ctx->timestamps, frame->pts);
1608 if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
1609 ctx->initial_pts[0] = frame->pts;
1610 else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
1611 ctx->initial_pts[1] = frame->pts;
1613 params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1616 nvel->cu_ctx_push_current(ctx->cu_context);
1617 enc_ret = nv->nvEncEncodePicture(ctx->nvenc_ctx, ¶ms);
1618 nvel->cu_ctx_pop_current(&dummy);
1620 if (enc_ret != NV_ENC_SUCCESS &&
1621 enc_ret != NV_ENC_ERR_NEED_MORE_INPUT)
1622 return nvenc_print_error(avctx, enc_ret, "Error encoding the frame");
1625 ret = av_fifo_generic_write(ctx->pending, &nvenc_frame, sizeof(nvenc_frame), NULL);
1630 /* all the pending buffers are now ready for output */
1631 if (enc_ret == NV_ENC_SUCCESS) {
1632 while (av_fifo_size(ctx->pending) > 0) {
1633 av_fifo_generic_read(ctx->pending, &nvenc_frame, sizeof(nvenc_frame), NULL);
1634 av_fifo_generic_write(ctx->ready, &nvenc_frame, sizeof(nvenc_frame), NULL);
1638 if (output_ready(avctx, !frame)) {
1639 ret = nvenc_get_output(avctx, pkt);