2 * H.264/HEVC hardware encoding using nvidia nvenc
3 * Copyright (c) 2016 Timo Rothenpieler <timo@rothenpieler.org>
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
26 #include "libavutil/hwcontext_cuda.h"
27 #include "libavutil/hwcontext.h"
28 #include "libavutil/imgutils.h"
29 #include "libavutil/avassert.h"
30 #include "libavutil/mem.h"
31 #include "libavutil/pixdesc.h"
34 #define NVENC_CAP 0x30
35 #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR || \
36 rc == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ || \
37 rc == NV_ENC_PARAMS_RC_CBR_HQ)
39 const enum AVPixelFormat ff_nvenc_pix_fmts[] = {
44 AV_PIX_FMT_P016, // Truncated to 10bits
45 AV_PIX_FMT_YUV444P16, // Truncated to 10bits
55 #define IS_10BIT(pix_fmt) (pix_fmt == AV_PIX_FMT_P010 || \
56 pix_fmt == AV_PIX_FMT_P016 || \
57 pix_fmt == AV_PIX_FMT_YUV444P16)
59 #define IS_YUV444(pix_fmt) (pix_fmt == AV_PIX_FMT_YUV444P || \
60 pix_fmt == AV_PIX_FMT_YUV444P16)
67 { NV_ENC_SUCCESS, 0, "success" },
68 { NV_ENC_ERR_NO_ENCODE_DEVICE, AVERROR(ENOENT), "no encode device" },
69 { NV_ENC_ERR_UNSUPPORTED_DEVICE, AVERROR(ENOSYS), "unsupported device" },
70 { NV_ENC_ERR_INVALID_ENCODERDEVICE, AVERROR(EINVAL), "invalid encoder device" },
71 { NV_ENC_ERR_INVALID_DEVICE, AVERROR(EINVAL), "invalid device" },
72 { NV_ENC_ERR_DEVICE_NOT_EXIST, AVERROR(EIO), "device does not exist" },
73 { NV_ENC_ERR_INVALID_PTR, AVERROR(EFAULT), "invalid ptr" },
74 { NV_ENC_ERR_INVALID_EVENT, AVERROR(EINVAL), "invalid event" },
75 { NV_ENC_ERR_INVALID_PARAM, AVERROR(EINVAL), "invalid param" },
76 { NV_ENC_ERR_INVALID_CALL, AVERROR(EINVAL), "invalid call" },
77 { NV_ENC_ERR_OUT_OF_MEMORY, AVERROR(ENOMEM), "out of memory" },
78 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED, AVERROR(EINVAL), "encoder not initialized" },
79 { NV_ENC_ERR_UNSUPPORTED_PARAM, AVERROR(ENOSYS), "unsupported param" },
80 { NV_ENC_ERR_LOCK_BUSY, AVERROR(EAGAIN), "lock busy" },
81 { NV_ENC_ERR_NOT_ENOUGH_BUFFER, AVERROR_BUFFER_TOO_SMALL, "not enough buffer"},
82 { NV_ENC_ERR_INVALID_VERSION, AVERROR(EINVAL), "invalid version" },
83 { NV_ENC_ERR_MAP_FAILED, AVERROR(EIO), "map failed" },
84 { NV_ENC_ERR_NEED_MORE_INPUT, AVERROR(EAGAIN), "need more input" },
85 { NV_ENC_ERR_ENCODER_BUSY, AVERROR(EAGAIN), "encoder busy" },
86 { NV_ENC_ERR_EVENT_NOT_REGISTERD, AVERROR(EBADF), "event not registered" },
87 { NV_ENC_ERR_GENERIC, AVERROR_UNKNOWN, "generic error" },
88 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY, AVERROR(EINVAL), "incompatible client key" },
89 { NV_ENC_ERR_UNIMPLEMENTED, AVERROR(ENOSYS), "unimplemented" },
90 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO), "resource register failed" },
91 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED, AVERROR(EBADF), "resource not registered" },
92 { NV_ENC_ERR_RESOURCE_NOT_MAPPED, AVERROR(EBADF), "resource not mapped" },
95 static int nvenc_map_error(NVENCSTATUS err, const char **desc)
98 for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
99 if (nvenc_errors[i].nverr == err) {
101 *desc = nvenc_errors[i].desc;
102 return nvenc_errors[i].averr;
106 *desc = "unknown error";
107 return AVERROR_UNKNOWN;
110 static int nvenc_print_error(void *log_ctx, NVENCSTATUS err,
111 const char *error_string)
115 ret = nvenc_map_error(err, &desc);
116 av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
120 static void nvenc_print_driver_requirement(AVCodecContext *avctx, int level)
122 #if NVENCAPI_CHECK_VERSION(8, 1)
123 # if defined(_WIN32) || defined(__CYGWIN__)
124 const char *minver = "390.77";
126 const char *minver = "390.25";
129 # if defined(_WIN32) || defined(__CYGWIN__)
130 const char *minver = "378.66";
132 const char *minver = "378.13";
135 av_log(avctx, level, "The minimum required Nvidia driver for nvenc is %s or newer\n", minver);
138 static av_cold int nvenc_load_libraries(AVCodecContext *avctx)
140 NvencContext *ctx = avctx->priv_data;
141 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
143 uint32_t nvenc_max_ver;
146 ret = cuda_load_functions(&dl_fn->cuda_dl, avctx);
150 ret = nvenc_load_functions(&dl_fn->nvenc_dl, avctx);
152 nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
156 err = dl_fn->nvenc_dl->NvEncodeAPIGetMaxSupportedVersion(&nvenc_max_ver);
157 if (err != NV_ENC_SUCCESS)
158 return nvenc_print_error(avctx, err, "Failed to query nvenc max version");
160 av_log(avctx, AV_LOG_VERBOSE, "Loaded Nvenc version %d.%d\n", nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
162 if ((NVENCAPI_MAJOR_VERSION << 4 | NVENCAPI_MINOR_VERSION) > nvenc_max_ver) {
163 av_log(avctx, AV_LOG_ERROR, "Driver does not support the required nvenc API version. "
164 "Required: %d.%d Found: %d.%d\n",
165 NVENCAPI_MAJOR_VERSION, NVENCAPI_MINOR_VERSION,
166 nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
167 nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
168 return AVERROR(ENOSYS);
171 dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
173 err = dl_fn->nvenc_dl->NvEncodeAPICreateInstance(&dl_fn->nvenc_funcs);
174 if (err != NV_ENC_SUCCESS)
175 return nvenc_print_error(avctx, err, "Failed to create nvenc instance");
177 av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
182 static int nvenc_push_context(AVCodecContext *avctx)
184 NvencContext *ctx = avctx->priv_data;
185 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
188 if (ctx->d3d11_device)
191 cu_res = dl_fn->cuda_dl->cuCtxPushCurrent(ctx->cu_context);
192 if (cu_res != CUDA_SUCCESS) {
193 av_log(avctx, AV_LOG_ERROR, "cuCtxPushCurrent failed\n");
194 return AVERROR_EXTERNAL;
200 static int nvenc_pop_context(AVCodecContext *avctx)
202 NvencContext *ctx = avctx->priv_data;
203 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
207 if (ctx->d3d11_device)
210 cu_res = dl_fn->cuda_dl->cuCtxPopCurrent(&dummy);
211 if (cu_res != CUDA_SUCCESS) {
212 av_log(avctx, AV_LOG_ERROR, "cuCtxPopCurrent failed\n");
213 return AVERROR_EXTERNAL;
219 static av_cold int nvenc_open_session(AVCodecContext *avctx)
221 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
222 NvencContext *ctx = avctx->priv_data;
223 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
226 params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
227 params.apiVersion = NVENCAPI_VERSION;
228 if (ctx->d3d11_device) {
229 params.device = ctx->d3d11_device;
230 params.deviceType = NV_ENC_DEVICE_TYPE_DIRECTX;
232 params.device = ctx->cu_context;
233 params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
236 ret = p_nvenc->nvEncOpenEncodeSessionEx(¶ms, &ctx->nvencoder);
237 if (ret != NV_ENC_SUCCESS) {
238 ctx->nvencoder = NULL;
239 return nvenc_print_error(avctx, ret, "OpenEncodeSessionEx failed");
245 static int nvenc_check_codec_support(AVCodecContext *avctx)
247 NvencContext *ctx = avctx->priv_data;
248 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
249 int i, ret, count = 0;
252 ret = p_nvenc->nvEncGetEncodeGUIDCount(ctx->nvencoder, &count);
254 if (ret != NV_ENC_SUCCESS || !count)
255 return AVERROR(ENOSYS);
257 guids = av_malloc(count * sizeof(GUID));
259 return AVERROR(ENOMEM);
261 ret = p_nvenc->nvEncGetEncodeGUIDs(ctx->nvencoder, guids, count, &count);
262 if (ret != NV_ENC_SUCCESS) {
263 ret = AVERROR(ENOSYS);
267 ret = AVERROR(ENOSYS);
268 for (i = 0; i < count; i++) {
269 if (!memcmp(&guids[i], &ctx->init_encode_params.encodeGUID, sizeof(*guids))) {
281 static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
283 NvencContext *ctx = avctx->priv_data;
284 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
285 NV_ENC_CAPS_PARAM params = { 0 };
288 params.version = NV_ENC_CAPS_PARAM_VER;
289 params.capsToQuery = cap;
291 ret = p_nvenc->nvEncGetEncodeCaps(ctx->nvencoder, ctx->init_encode_params.encodeGUID, ¶ms, &val);
293 if (ret == NV_ENC_SUCCESS)
298 static int nvenc_check_capabilities(AVCodecContext *avctx)
300 NvencContext *ctx = avctx->priv_data;
303 ret = nvenc_check_codec_support(avctx);
305 av_log(avctx, AV_LOG_VERBOSE, "Codec not supported\n");
309 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
310 if (IS_YUV444(ctx->data_pix_fmt) && ret <= 0) {
311 av_log(avctx, AV_LOG_VERBOSE, "YUV444P not supported\n");
312 return AVERROR(ENOSYS);
315 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOSSLESS_ENCODE);
316 if (ctx->preset >= PRESET_LOSSLESS_DEFAULT && ret <= 0) {
317 av_log(avctx, AV_LOG_VERBOSE, "Lossless encoding not supported\n");
318 return AVERROR(ENOSYS);
321 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
322 if (ret < avctx->width) {
323 av_log(avctx, AV_LOG_VERBOSE, "Width %d exceeds %d\n",
325 return AVERROR(ENOSYS);
328 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
329 if (ret < avctx->height) {
330 av_log(avctx, AV_LOG_VERBOSE, "Height %d exceeds %d\n",
332 return AVERROR(ENOSYS);
335 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
336 if (ret < avctx->max_b_frames) {
337 av_log(avctx, AV_LOG_VERBOSE, "Max B-frames %d exceed %d\n",
338 avctx->max_b_frames, ret);
340 return AVERROR(ENOSYS);
343 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_FIELD_ENCODING);
344 if (ret < 1 && avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
345 av_log(avctx, AV_LOG_VERBOSE,
346 "Interlaced encoding is not supported. Supported level: %d\n",
348 return AVERROR(ENOSYS);
351 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_10BIT_ENCODE);
352 if (IS_10BIT(ctx->data_pix_fmt) && ret <= 0) {
353 av_log(avctx, AV_LOG_VERBOSE, "10 bit encode not supported\n");
354 return AVERROR(ENOSYS);
357 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOOKAHEAD);
358 if (ctx->rc_lookahead > 0 && ret <= 0) {
359 av_log(avctx, AV_LOG_VERBOSE, "RC lookahead not supported\n");
360 return AVERROR(ENOSYS);
363 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_TEMPORAL_AQ);
364 if (ctx->temporal_aq > 0 && ret <= 0) {
365 av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ not supported\n");
366 return AVERROR(ENOSYS);
369 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_WEIGHTED_PREDICTION);
370 if (ctx->weighted_pred > 0 && ret <= 0) {
371 av_log (avctx, AV_LOG_VERBOSE, "Weighted Prediction not supported\n");
372 return AVERROR(ENOSYS);
375 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_CABAC);
376 if (ctx->coder == NV_ENC_H264_ENTROPY_CODING_MODE_CABAC && ret <= 0) {
377 av_log(avctx, AV_LOG_VERBOSE, "CABAC entropy coding not supported\n");
378 return AVERROR(ENOSYS);
381 #ifdef NVENC_HAVE_BFRAME_REF_MODE
382 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_BFRAME_REF_MODE);
383 if (ctx->b_ref_mode == NV_ENC_BFRAME_REF_MODE_EACH && ret != 1) {
384 av_log(avctx, AV_LOG_VERBOSE, "Each B frame as reference is not supported\n");
385 return AVERROR(ENOSYS);
386 } else if (ctx->b_ref_mode != NV_ENC_BFRAME_REF_MODE_DISABLED && ret == 0) {
387 av_log(avctx, AV_LOG_VERBOSE, "B frames as references are not supported\n");
388 return AVERROR(ENOSYS);
391 if (ctx->b_ref_mode != 0) {
392 av_log(avctx, AV_LOG_VERBOSE, "B frames as references need SDK 8.1 at build time\n");
393 return AVERROR(ENOSYS);
400 static av_cold int nvenc_check_device(AVCodecContext *avctx, int idx)
402 NvencContext *ctx = avctx->priv_data;
403 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
404 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
405 char name[128] = { 0};
406 int major, minor, ret;
409 int loglevel = AV_LOG_VERBOSE;
411 if (ctx->device == LIST_DEVICES)
412 loglevel = AV_LOG_INFO;
414 cu_res = dl_fn->cuda_dl->cuDeviceGet(&cu_device, idx);
415 if (cu_res != CUDA_SUCCESS) {
416 av_log(avctx, AV_LOG_ERROR,
417 "Cannot access the CUDA device %d\n",
422 cu_res = dl_fn->cuda_dl->cuDeviceGetName(name, sizeof(name), cu_device);
423 if (cu_res != CUDA_SUCCESS) {
424 av_log(avctx, AV_LOG_ERROR, "cuDeviceGetName failed on device %d\n", idx);
428 cu_res = dl_fn->cuda_dl->cuDeviceComputeCapability(&major, &minor, cu_device);
429 if (cu_res != CUDA_SUCCESS) {
430 av_log(avctx, AV_LOG_ERROR, "cuDeviceComputeCapability failed on device %d\n", idx);
434 av_log(avctx, loglevel, "[ GPU #%d - < %s > has Compute SM %d.%d ]\n", idx, name, major, minor);
435 if (((major << 4) | minor) < NVENC_CAP) {
436 av_log(avctx, loglevel, "does not support NVENC\n");
440 if (ctx->device != idx && ctx->device != ANY_DEVICE)
443 cu_res = dl_fn->cuda_dl->cuCtxCreate(&ctx->cu_context_internal, 0, cu_device);
444 if (cu_res != CUDA_SUCCESS) {
445 av_log(avctx, AV_LOG_FATAL, "Failed creating CUDA context for NVENC: 0x%x\n", (int)cu_res);
449 ctx->cu_context = ctx->cu_context_internal;
451 if ((ret = nvenc_pop_context(avctx)) < 0)
454 if ((ret = nvenc_open_session(avctx)) < 0)
457 if ((ret = nvenc_check_capabilities(avctx)) < 0)
460 av_log(avctx, loglevel, "supports NVENC\n");
462 dl_fn->nvenc_device_count++;
464 if (ctx->device == idx || ctx->device == ANY_DEVICE)
468 if ((ret = nvenc_push_context(avctx)) < 0)
471 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
472 ctx->nvencoder = NULL;
474 if ((ret = nvenc_pop_context(avctx)) < 0)
478 dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal);
479 ctx->cu_context_internal = NULL;
482 return AVERROR(ENOSYS);
485 static av_cold int nvenc_setup_device(AVCodecContext *avctx)
487 NvencContext *ctx = avctx->priv_data;
488 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
490 switch (avctx->codec->id) {
491 case AV_CODEC_ID_H264:
492 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
494 case AV_CODEC_ID_HEVC:
495 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
501 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11 || avctx->hw_frames_ctx || avctx->hw_device_ctx) {
502 AVHWFramesContext *frames_ctx;
503 AVHWDeviceContext *hwdev_ctx;
504 AVCUDADeviceContext *cuda_device_hwctx = NULL;
506 AVD3D11VADeviceContext *d3d11_device_hwctx = NULL;
510 if (avctx->hw_frames_ctx) {
511 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
512 if (frames_ctx->format == AV_PIX_FMT_CUDA)
513 cuda_device_hwctx = frames_ctx->device_ctx->hwctx;
515 else if (frames_ctx->format == AV_PIX_FMT_D3D11)
516 d3d11_device_hwctx = frames_ctx->device_ctx->hwctx;
519 return AVERROR(EINVAL);
520 } else if (avctx->hw_device_ctx) {
521 hwdev_ctx = (AVHWDeviceContext*)avctx->hw_device_ctx->data;
522 if (hwdev_ctx->type == AV_HWDEVICE_TYPE_CUDA)
523 cuda_device_hwctx = hwdev_ctx->hwctx;
525 else if (hwdev_ctx->type == AV_HWDEVICE_TYPE_D3D11VA)
526 d3d11_device_hwctx = hwdev_ctx->hwctx;
529 return AVERROR(EINVAL);
531 return AVERROR(EINVAL);
534 if (cuda_device_hwctx) {
535 ctx->cu_context = cuda_device_hwctx->cuda_ctx;
538 else if (d3d11_device_hwctx) {
539 ctx->d3d11_device = d3d11_device_hwctx->device;
540 ID3D11Device_AddRef(ctx->d3d11_device);
544 ret = nvenc_open_session(avctx);
548 ret = nvenc_check_capabilities(avctx);
550 av_log(avctx, AV_LOG_FATAL, "Provided device doesn't support required NVENC features\n");
554 int i, nb_devices = 0;
556 if ((dl_fn->cuda_dl->cuInit(0)) != CUDA_SUCCESS) {
557 av_log(avctx, AV_LOG_ERROR,
558 "Cannot init CUDA\n");
559 return AVERROR_UNKNOWN;
562 if ((dl_fn->cuda_dl->cuDeviceGetCount(&nb_devices)) != CUDA_SUCCESS) {
563 av_log(avctx, AV_LOG_ERROR,
564 "Cannot enumerate the CUDA devices\n");
565 return AVERROR_UNKNOWN;
569 av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
570 return AVERROR_EXTERNAL;
573 av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", nb_devices);
575 dl_fn->nvenc_device_count = 0;
576 for (i = 0; i < nb_devices; ++i) {
577 if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
581 if (ctx->device == LIST_DEVICES)
584 if (!dl_fn->nvenc_device_count) {
585 av_log(avctx, AV_LOG_FATAL, "No NVENC capable devices found\n");
586 return AVERROR_EXTERNAL;
589 av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->device, nb_devices);
590 return AVERROR(EINVAL);
596 typedef struct GUIDTuple {
601 #define PRESET_ALIAS(alias, name, ...) \
602 [PRESET_ ## alias] = { NV_ENC_PRESET_ ## name ## _GUID, __VA_ARGS__ }
604 #define PRESET(name, ...) PRESET_ALIAS(name, name, __VA_ARGS__)
606 static void nvenc_map_preset(NvencContext *ctx)
608 GUIDTuple presets[] = {
613 PRESET_ALIAS(SLOW, HQ, NVENC_TWO_PASSES),
614 PRESET_ALIAS(MEDIUM, HQ, NVENC_ONE_PASS),
615 PRESET_ALIAS(FAST, HP, NVENC_ONE_PASS),
616 PRESET(LOW_LATENCY_DEFAULT, NVENC_LOWLATENCY),
617 PRESET(LOW_LATENCY_HP, NVENC_LOWLATENCY),
618 PRESET(LOW_LATENCY_HQ, NVENC_LOWLATENCY),
619 PRESET(LOSSLESS_DEFAULT, NVENC_LOSSLESS),
620 PRESET(LOSSLESS_HP, NVENC_LOSSLESS),
623 GUIDTuple *t = &presets[ctx->preset];
625 ctx->init_encode_params.presetGUID = t->guid;
626 ctx->flags = t->flags;
632 static av_cold void set_constqp(AVCodecContext *avctx)
634 NvencContext *ctx = avctx->priv_data;
635 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
637 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
639 if (ctx->init_qp_p >= 0) {
640 rc->constQP.qpInterP = ctx->init_qp_p;
641 if (ctx->init_qp_i >= 0 && ctx->init_qp_b >= 0) {
642 rc->constQP.qpIntra = ctx->init_qp_i;
643 rc->constQP.qpInterB = ctx->init_qp_b;
644 } else if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
645 rc->constQP.qpIntra = av_clip(
646 rc->constQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
647 rc->constQP.qpInterB = av_clip(
648 rc->constQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
650 rc->constQP.qpIntra = rc->constQP.qpInterP;
651 rc->constQP.qpInterB = rc->constQP.qpInterP;
653 } else if (ctx->cqp >= 0) {
654 rc->constQP.qpInterP = rc->constQP.qpInterB = rc->constQP.qpIntra = ctx->cqp;
655 if (avctx->b_quant_factor != 0.0)
656 rc->constQP.qpInterB = av_clip(ctx->cqp * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
657 if (avctx->i_quant_factor != 0.0)
658 rc->constQP.qpIntra = av_clip(ctx->cqp * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
665 static av_cold void set_vbr(AVCodecContext *avctx)
667 NvencContext *ctx = avctx->priv_data;
668 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
671 if (avctx->qmin >= 0 && avctx->qmax >= 0) {
675 rc->minQP.qpInterB = avctx->qmin;
676 rc->minQP.qpInterP = avctx->qmin;
677 rc->minQP.qpIntra = avctx->qmin;
679 rc->maxQP.qpInterB = avctx->qmax;
680 rc->maxQP.qpInterP = avctx->qmax;
681 rc->maxQP.qpIntra = avctx->qmax;
683 qp_inter_p = (avctx->qmax + 3 * avctx->qmin) / 4; // biased towards Qmin
684 } else if (avctx->qmin >= 0) {
687 rc->minQP.qpInterB = avctx->qmin;
688 rc->minQP.qpInterP = avctx->qmin;
689 rc->minQP.qpIntra = avctx->qmin;
691 qp_inter_p = avctx->qmin;
693 qp_inter_p = 26; // default to 26
696 rc->enableInitialRCQP = 1;
698 if (ctx->init_qp_p < 0) {
699 rc->initialRCQP.qpInterP = qp_inter_p;
701 rc->initialRCQP.qpInterP = ctx->init_qp_p;
704 if (ctx->init_qp_i < 0) {
705 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
706 rc->initialRCQP.qpIntra = av_clip(
707 rc->initialRCQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
709 rc->initialRCQP.qpIntra = rc->initialRCQP.qpInterP;
712 rc->initialRCQP.qpIntra = ctx->init_qp_i;
715 if (ctx->init_qp_b < 0) {
716 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
717 rc->initialRCQP.qpInterB = av_clip(
718 rc->initialRCQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
720 rc->initialRCQP.qpInterB = rc->initialRCQP.qpInterP;
723 rc->initialRCQP.qpInterB = ctx->init_qp_b;
727 static av_cold void set_lossless(AVCodecContext *avctx)
729 NvencContext *ctx = avctx->priv_data;
730 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
732 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
733 rc->constQP.qpInterB = 0;
734 rc->constQP.qpInterP = 0;
735 rc->constQP.qpIntra = 0;
741 static void nvenc_override_rate_control(AVCodecContext *avctx)
743 NvencContext *ctx = avctx->priv_data;
744 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
747 case NV_ENC_PARAMS_RC_CONSTQP:
750 case NV_ENC_PARAMS_RC_VBR_MINQP:
751 if (avctx->qmin < 0) {
752 av_log(avctx, AV_LOG_WARNING,
753 "The variable bitrate rate-control requires "
754 "the 'qmin' option set.\n");
759 case NV_ENC_PARAMS_RC_VBR_HQ:
760 case NV_ENC_PARAMS_RC_VBR:
763 case NV_ENC_PARAMS_RC_CBR:
764 case NV_ENC_PARAMS_RC_CBR_HQ:
765 case NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ:
769 rc->rateControlMode = ctx->rc;
772 static av_cold int nvenc_recalc_surfaces(AVCodecContext *avctx)
774 NvencContext *ctx = avctx->priv_data;
775 // default minimum of 4 surfaces
776 // multiply by 2 for number of NVENCs on gpu (hardcode to 2)
777 // another multiply by 2 to avoid blocking next PBB group
778 int nb_surfaces = FFMAX(4, ctx->encode_config.frameIntervalP * 2 * 2);
781 if (ctx->rc_lookahead > 0) {
782 // +1 is to account for lkd_bound calculation later
783 // +4 is to allow sufficient pipelining with lookahead
784 nb_surfaces = FFMAX(1, FFMAX(nb_surfaces, ctx->rc_lookahead + ctx->encode_config.frameIntervalP + 1 + 4));
785 if (nb_surfaces > ctx->nb_surfaces && ctx->nb_surfaces > 0)
787 av_log(avctx, AV_LOG_WARNING,
788 "Defined rc_lookahead requires more surfaces, "
789 "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
791 ctx->nb_surfaces = FFMAX(nb_surfaces, ctx->nb_surfaces);
793 if (ctx->encode_config.frameIntervalP > 1 && ctx->nb_surfaces < nb_surfaces && ctx->nb_surfaces > 0)
795 av_log(avctx, AV_LOG_WARNING,
796 "Defined b-frame requires more surfaces, "
797 "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
798 ctx->nb_surfaces = FFMAX(ctx->nb_surfaces, nb_surfaces);
800 else if (ctx->nb_surfaces <= 0)
801 ctx->nb_surfaces = nb_surfaces;
802 // otherwise use user specified value
805 ctx->nb_surfaces = FFMAX(1, FFMIN(MAX_REGISTERED_FRAMES, ctx->nb_surfaces));
806 ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
811 static av_cold void nvenc_setup_rate_control(AVCodecContext *avctx)
813 NvencContext *ctx = avctx->priv_data;
815 if (avctx->global_quality > 0)
816 av_log(avctx, AV_LOG_WARNING, "Using global_quality with nvenc is deprecated. Use qp instead.\n");
818 if (ctx->cqp < 0 && avctx->global_quality > 0)
819 ctx->cqp = avctx->global_quality;
821 if (avctx->bit_rate > 0) {
822 ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
823 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
824 ctx->encode_config.rcParams.maxBitRate = ctx->encode_config.rcParams.averageBitRate;
827 if (avctx->rc_max_rate > 0)
828 ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
831 if (ctx->flags & NVENC_ONE_PASS)
833 if (ctx->flags & NVENC_TWO_PASSES)
836 if (ctx->twopass < 0)
837 ctx->twopass = (ctx->flags & NVENC_LOWLATENCY) != 0;
841 ctx->rc = NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ;
843 ctx->rc = NV_ENC_PARAMS_RC_CBR;
845 } else if (ctx->cqp >= 0) {
846 ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
847 } else if (ctx->twopass) {
848 ctx->rc = NV_ENC_PARAMS_RC_VBR_HQ;
849 } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
850 ctx->rc = NV_ENC_PARAMS_RC_VBR_MINQP;
854 if (ctx->rc >= 0 && ctx->rc & RC_MODE_DEPRECATED) {
855 av_log(avctx, AV_LOG_WARNING, "Specified rc mode is deprecated.\n");
856 av_log(avctx, AV_LOG_WARNING, "\tll_2pass_quality -> cbr_ld_hq\n");
857 av_log(avctx, AV_LOG_WARNING, "\tll_2pass_size -> cbr_hq\n");
858 av_log(avctx, AV_LOG_WARNING, "\tvbr_2pass -> vbr_hq\n");
859 av_log(avctx, AV_LOG_WARNING, "\tvbr_minqp -> (no replacement)\n");
861 ctx->rc &= ~RC_MODE_DEPRECATED;
864 if (ctx->flags & NVENC_LOSSLESS) {
866 } else if (ctx->rc >= 0) {
867 nvenc_override_rate_control(avctx);
869 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
873 if (avctx->rc_buffer_size > 0) {
874 ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
875 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
876 ctx->encode_config.rcParams.vbvBufferSize = 2 * ctx->encode_config.rcParams.averageBitRate;
880 ctx->encode_config.rcParams.enableAQ = 1;
881 ctx->encode_config.rcParams.aqStrength = ctx->aq_strength;
882 av_log(avctx, AV_LOG_VERBOSE, "AQ enabled.\n");
885 if (ctx->temporal_aq) {
886 ctx->encode_config.rcParams.enableTemporalAQ = 1;
887 av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ enabled.\n");
890 if (ctx->rc_lookahead > 0) {
891 int lkd_bound = FFMIN(ctx->nb_surfaces, ctx->async_depth) -
892 ctx->encode_config.frameIntervalP - 4;
895 av_log(avctx, AV_LOG_WARNING,
896 "Lookahead not enabled. Increase buffer delay (-delay).\n");
898 ctx->encode_config.rcParams.enableLookahead = 1;
899 ctx->encode_config.rcParams.lookaheadDepth = av_clip(ctx->rc_lookahead, 0, lkd_bound);
900 ctx->encode_config.rcParams.disableIadapt = ctx->no_scenecut;
901 ctx->encode_config.rcParams.disableBadapt = !ctx->b_adapt;
902 av_log(avctx, AV_LOG_VERBOSE,
903 "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",
904 ctx->encode_config.rcParams.lookaheadDepth,
905 ctx->encode_config.rcParams.disableIadapt ? "disabled" : "enabled",
906 ctx->encode_config.rcParams.disableBadapt ? "disabled" : "enabled");
910 if (ctx->strict_gop) {
911 ctx->encode_config.rcParams.strictGOPTarget = 1;
912 av_log(avctx, AV_LOG_VERBOSE, "Strict GOP target enabled.\n");
916 ctx->encode_config.rcParams.enableNonRefP = 1;
918 if (ctx->zerolatency)
919 ctx->encode_config.rcParams.zeroReorderDelay = 1;
923 //convert from float to fixed point 8.8
924 int tmp_quality = (int)(ctx->quality * 256.0f);
925 ctx->encode_config.rcParams.targetQuality = (uint8_t)(tmp_quality >> 8);
926 ctx->encode_config.rcParams.targetQualityLSB = (uint8_t)(tmp_quality & 0xff);
930 static av_cold int nvenc_setup_h264_config(AVCodecContext *avctx)
932 NvencContext *ctx = avctx->priv_data;
933 NV_ENC_CONFIG *cc = &ctx->encode_config;
934 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
935 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
937 vui->colourMatrix = avctx->colorspace;
938 vui->colourPrimaries = avctx->color_primaries;
939 vui->transferCharacteristics = avctx->color_trc;
940 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
941 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
943 vui->colourDescriptionPresentFlag =
944 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
946 vui->videoSignalTypePresentFlag =
947 (vui->colourDescriptionPresentFlag
948 || vui->videoFormat != 5
949 || vui->videoFullRangeFlag != 0);
952 h264->sliceModeData = 1;
954 h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
955 h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
956 h264->outputAUD = ctx->aud;
958 if (avctx->refs >= 0) {
959 /* 0 means "let the hardware decide" */
960 h264->maxNumRefFrames = avctx->refs;
962 if (avctx->gop_size >= 0) {
963 h264->idrPeriod = cc->gopLength;
966 if (IS_CBR(cc->rcParams.rateControlMode)) {
967 h264->outputBufferingPeriodSEI = 1;
970 h264->outputPictureTimingSEI = 1;
972 if (cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ ||
973 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_HQ ||
974 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_VBR_HQ) {
975 h264->adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
976 h264->fmoMode = NV_ENC_H264_FMO_DISABLE;
979 if (ctx->flags & NVENC_LOSSLESS) {
980 h264->qpPrimeYZeroTransformBypassFlag = 1;
982 switch(ctx->profile) {
983 case NV_ENC_H264_PROFILE_BASELINE:
984 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
985 avctx->profile = FF_PROFILE_H264_BASELINE;
987 case NV_ENC_H264_PROFILE_MAIN:
988 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
989 avctx->profile = FF_PROFILE_H264_MAIN;
991 case NV_ENC_H264_PROFILE_HIGH:
992 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
993 avctx->profile = FF_PROFILE_H264_HIGH;
995 case NV_ENC_H264_PROFILE_HIGH_444P:
996 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
997 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
1002 // force setting profile as high444p if input is AV_PIX_FMT_YUV444P
1003 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P) {
1004 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1005 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
1008 h264->chromaFormatIDC = avctx->profile == FF_PROFILE_H264_HIGH_444_PREDICTIVE ? 3 : 1;
1010 h264->level = ctx->level;
1012 if (ctx->coder >= 0)
1013 h264->entropyCodingMode = ctx->coder;
1015 #ifdef NVENC_HAVE_BFRAME_REF_MODE
1016 h264->useBFramesAsRef = ctx->b_ref_mode;
1022 static av_cold int nvenc_setup_hevc_config(AVCodecContext *avctx)
1024 NvencContext *ctx = avctx->priv_data;
1025 NV_ENC_CONFIG *cc = &ctx->encode_config;
1026 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
1027 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
1029 vui->colourMatrix = avctx->colorspace;
1030 vui->colourPrimaries = avctx->color_primaries;
1031 vui->transferCharacteristics = avctx->color_trc;
1032 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
1033 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
1035 vui->colourDescriptionPresentFlag =
1036 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
1038 vui->videoSignalTypePresentFlag =
1039 (vui->colourDescriptionPresentFlag
1040 || vui->videoFormat != 5
1041 || vui->videoFullRangeFlag != 0);
1043 hevc->sliceMode = 3;
1044 hevc->sliceModeData = 1;
1046 hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
1047 hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
1048 hevc->outputAUD = ctx->aud;
1050 if (avctx->refs >= 0) {
1051 /* 0 means "let the hardware decide" */
1052 hevc->maxNumRefFramesInDPB = avctx->refs;
1054 if (avctx->gop_size >= 0) {
1055 hevc->idrPeriod = cc->gopLength;
1058 if (IS_CBR(cc->rcParams.rateControlMode)) {
1059 hevc->outputBufferingPeriodSEI = 1;
1062 hevc->outputPictureTimingSEI = 1;
1064 switch (ctx->profile) {
1065 case NV_ENC_HEVC_PROFILE_MAIN:
1066 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
1067 avctx->profile = FF_PROFILE_HEVC_MAIN;
1069 case NV_ENC_HEVC_PROFILE_MAIN_10:
1070 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1071 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
1073 case NV_ENC_HEVC_PROFILE_REXT:
1074 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1075 avctx->profile = FF_PROFILE_HEVC_REXT;
1079 // force setting profile as main10 if input is 10 bit
1080 if (IS_10BIT(ctx->data_pix_fmt)) {
1081 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1082 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
1085 // force setting profile as rext if input is yuv444
1086 if (IS_YUV444(ctx->data_pix_fmt)) {
1087 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1088 avctx->profile = FF_PROFILE_HEVC_REXT;
1091 hevc->chromaFormatIDC = IS_YUV444(ctx->data_pix_fmt) ? 3 : 1;
1093 hevc->pixelBitDepthMinus8 = IS_10BIT(ctx->data_pix_fmt) ? 2 : 0;
1095 hevc->level = ctx->level;
1097 hevc->tier = ctx->tier;
1102 static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx)
1104 switch (avctx->codec->id) {
1105 case AV_CODEC_ID_H264:
1106 return nvenc_setup_h264_config(avctx);
1107 case AV_CODEC_ID_HEVC:
1108 return nvenc_setup_hevc_config(avctx);
1109 /* Earlier switch/case will return if unknown codec is passed. */
1115 static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
1117 NvencContext *ctx = avctx->priv_data;
1118 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1119 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1121 NV_ENC_PRESET_CONFIG preset_config = { 0 };
1122 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
1123 AVCPBProperties *cpb_props;
1127 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1128 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
1130 ctx->init_encode_params.encodeHeight = avctx->height;
1131 ctx->init_encode_params.encodeWidth = avctx->width;
1133 ctx->init_encode_params.encodeConfig = &ctx->encode_config;
1135 nvenc_map_preset(ctx);
1137 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
1138 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
1140 nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder,
1141 ctx->init_encode_params.encodeGUID,
1142 ctx->init_encode_params.presetGUID,
1144 if (nv_status != NV_ENC_SUCCESS)
1145 return nvenc_print_error(avctx, nv_status, "Cannot get the preset configuration");
1147 memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
1149 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1153 if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0) {
1154 dw*= avctx->sample_aspect_ratio.num;
1155 dh*= avctx->sample_aspect_ratio.den;
1157 av_reduce(&dw, &dh, dw, dh, 1024 * 1024);
1158 ctx->init_encode_params.darHeight = dh;
1159 ctx->init_encode_params.darWidth = dw;
1161 ctx->init_encode_params.frameRateNum = avctx->time_base.den;
1162 ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
1164 ctx->init_encode_params.enableEncodeAsync = 0;
1165 ctx->init_encode_params.enablePTD = 1;
1167 if (ctx->weighted_pred == 1)
1168 ctx->init_encode_params.enableWeightedPrediction = 1;
1170 if (ctx->bluray_compat) {
1172 avctx->refs = FFMIN(FFMAX(avctx->refs, 0), 6);
1173 avctx->max_b_frames = FFMIN(avctx->max_b_frames, 3);
1174 switch (avctx->codec->id) {
1175 case AV_CODEC_ID_H264:
1176 /* maximum level depends on used resolution */
1178 case AV_CODEC_ID_HEVC:
1179 ctx->level = NV_ENC_LEVEL_HEVC_51;
1180 ctx->tier = NV_ENC_TIER_HEVC_HIGH;
1185 if (avctx->gop_size > 0) {
1186 if (avctx->max_b_frames >= 0) {
1187 /* 0 is intra-only, 1 is I/P only, 2 is one B-Frame, 3 two B-frames, and so on. */
1188 ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
1191 ctx->encode_config.gopLength = avctx->gop_size;
1192 } else if (avctx->gop_size == 0) {
1193 ctx->encode_config.frameIntervalP = 0;
1194 ctx->encode_config.gopLength = 1;
1197 ctx->initial_pts[0] = AV_NOPTS_VALUE;
1198 ctx->initial_pts[1] = AV_NOPTS_VALUE;
1200 nvenc_recalc_surfaces(avctx);
1202 nvenc_setup_rate_control(avctx);
1204 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1205 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
1207 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
1210 res = nvenc_setup_codec_config(avctx);
1214 res = nvenc_push_context(avctx);
1218 nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
1220 res = nvenc_pop_context(avctx);
1224 if (nv_status != NV_ENC_SUCCESS) {
1225 return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
1228 if (ctx->encode_config.frameIntervalP > 1)
1229 avctx->has_b_frames = 2;
1231 if (ctx->encode_config.rcParams.averageBitRate > 0)
1232 avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
1234 cpb_props = ff_add_cpb_side_data(avctx);
1236 return AVERROR(ENOMEM);
1237 cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
1238 cpb_props->avg_bitrate = avctx->bit_rate;
1239 cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
1244 static NV_ENC_BUFFER_FORMAT nvenc_map_buffer_format(enum AVPixelFormat pix_fmt)
1247 case AV_PIX_FMT_YUV420P:
1248 return NV_ENC_BUFFER_FORMAT_YV12_PL;
1249 case AV_PIX_FMT_NV12:
1250 return NV_ENC_BUFFER_FORMAT_NV12_PL;
1251 case AV_PIX_FMT_P010:
1252 case AV_PIX_FMT_P016:
1253 return NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1254 case AV_PIX_FMT_YUV444P:
1255 return NV_ENC_BUFFER_FORMAT_YUV444_PL;
1256 case AV_PIX_FMT_YUV444P16:
1257 return NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1258 case AV_PIX_FMT_0RGB32:
1259 return NV_ENC_BUFFER_FORMAT_ARGB;
1260 case AV_PIX_FMT_0BGR32:
1261 return NV_ENC_BUFFER_FORMAT_ABGR;
1263 return NV_ENC_BUFFER_FORMAT_UNDEFINED;
1267 static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
1269 NvencContext *ctx = avctx->priv_data;
1270 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1271 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1272 NvencSurface* tmp_surface = &ctx->surfaces[idx];
1274 NVENCSTATUS nv_status;
1275 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
1276 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1278 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1279 ctx->surfaces[idx].in_ref = av_frame_alloc();
1280 if (!ctx->surfaces[idx].in_ref)
1281 return AVERROR(ENOMEM);
1283 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1285 ctx->surfaces[idx].format = nvenc_map_buffer_format(ctx->data_pix_fmt);
1286 if (ctx->surfaces[idx].format == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1287 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1288 av_get_pix_fmt_name(ctx->data_pix_fmt));
1289 return AVERROR(EINVAL);
1292 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1293 allocSurf.width = avctx->width;
1294 allocSurf.height = avctx->height;
1295 allocSurf.bufferFmt = ctx->surfaces[idx].format;
1297 nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
1298 if (nv_status != NV_ENC_SUCCESS) {
1299 return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
1302 ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
1303 ctx->surfaces[idx].width = allocSurf.width;
1304 ctx->surfaces[idx].height = allocSurf.height;
1307 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
1308 if (nv_status != NV_ENC_SUCCESS) {
1309 int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
1310 if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
1311 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
1312 av_frame_free(&ctx->surfaces[idx].in_ref);
1316 ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1317 ctx->surfaces[idx].size = allocOut.size;
1319 av_fifo_generic_write(ctx->unused_surface_queue, &tmp_surface, sizeof(tmp_surface), NULL);
1324 static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx)
1326 NvencContext *ctx = avctx->priv_data;
1327 int i, res = 0, res2;
1329 ctx->surfaces = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->surfaces));
1331 return AVERROR(ENOMEM);
1333 ctx->timestamp_list = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
1334 if (!ctx->timestamp_list)
1335 return AVERROR(ENOMEM);
1337 ctx->unused_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1338 if (!ctx->unused_surface_queue)
1339 return AVERROR(ENOMEM);
1341 ctx->output_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1342 if (!ctx->output_surface_queue)
1343 return AVERROR(ENOMEM);
1344 ctx->output_surface_ready_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1345 if (!ctx->output_surface_ready_queue)
1346 return AVERROR(ENOMEM);
1348 res = nvenc_push_context(avctx);
1352 for (i = 0; i < ctx->nb_surfaces; i++) {
1353 if ((res = nvenc_alloc_surface(avctx, i)) < 0)
1358 res2 = nvenc_pop_context(avctx);
1365 static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
1367 NvencContext *ctx = avctx->priv_data;
1368 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1369 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1371 NVENCSTATUS nv_status;
1372 uint32_t outSize = 0;
1373 char tmpHeader[256];
1374 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1375 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1377 payload.spsppsBuffer = tmpHeader;
1378 payload.inBufferSize = sizeof(tmpHeader);
1379 payload.outSPSPPSPayloadSize = &outSize;
1381 nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
1382 if (nv_status != NV_ENC_SUCCESS) {
1383 return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
1386 avctx->extradata_size = outSize;
1387 avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
1389 if (!avctx->extradata) {
1390 return AVERROR(ENOMEM);
1393 memcpy(avctx->extradata, tmpHeader, outSize);
1398 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
1400 NvencContext *ctx = avctx->priv_data;
1401 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1402 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1405 /* the encoder has to be flushed before it can be closed */
1406 if (ctx->nvencoder) {
1407 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
1408 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
1410 res = nvenc_push_context(avctx);
1414 p_nvenc->nvEncEncodePicture(ctx->nvencoder, ¶ms);
1417 av_fifo_freep(&ctx->timestamp_list);
1418 av_fifo_freep(&ctx->output_surface_ready_queue);
1419 av_fifo_freep(&ctx->output_surface_queue);
1420 av_fifo_freep(&ctx->unused_surface_queue);
1422 if (ctx->surfaces && (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11)) {
1423 for (i = 0; i < ctx->nb_registered_frames; i++) {
1424 if (ctx->registered_frames[i].mapped)
1425 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[i].in_map.mappedResource);
1426 if (ctx->registered_frames[i].regptr)
1427 p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1429 ctx->nb_registered_frames = 0;
1432 if (ctx->surfaces) {
1433 for (i = 0; i < ctx->nb_surfaces; ++i) {
1434 if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
1435 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
1436 av_frame_free(&ctx->surfaces[i].in_ref);
1437 p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
1440 av_freep(&ctx->surfaces);
1441 ctx->nb_surfaces = 0;
1443 if (ctx->nvencoder) {
1444 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1446 res = nvenc_pop_context(avctx);
1450 ctx->nvencoder = NULL;
1452 if (ctx->cu_context_internal)
1453 dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal);
1454 ctx->cu_context = ctx->cu_context_internal = NULL;
1457 if (ctx->d3d11_device) {
1458 ID3D11Device_Release(ctx->d3d11_device);
1459 ctx->d3d11_device = NULL;
1463 nvenc_free_functions(&dl_fn->nvenc_dl);
1464 cuda_free_functions(&dl_fn->cuda_dl);
1466 dl_fn->nvenc_device_count = 0;
1468 av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
1473 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
1475 NvencContext *ctx = avctx->priv_data;
1478 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1479 AVHWFramesContext *frames_ctx;
1480 if (!avctx->hw_frames_ctx) {
1481 av_log(avctx, AV_LOG_ERROR,
1482 "hw_frames_ctx must be set when using GPU frames as input\n");
1483 return AVERROR(EINVAL);
1485 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1486 if (frames_ctx->format != avctx->pix_fmt) {
1487 av_log(avctx, AV_LOG_ERROR,
1488 "hw_frames_ctx must match the GPU frame type\n");
1489 return AVERROR(EINVAL);
1491 ctx->data_pix_fmt = frames_ctx->sw_format;
1493 ctx->data_pix_fmt = avctx->pix_fmt;
1496 if ((ret = nvenc_load_libraries(avctx)) < 0)
1499 if ((ret = nvenc_setup_device(avctx)) < 0)
1502 if ((ret = nvenc_setup_encoder(avctx)) < 0)
1505 if ((ret = nvenc_setup_surfaces(avctx)) < 0)
1508 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1509 if ((ret = nvenc_setup_extradata(avctx)) < 0)
1516 static NvencSurface *get_free_frame(NvencContext *ctx)
1518 NvencSurface *tmp_surf;
1520 if (!(av_fifo_size(ctx->unused_surface_queue) > 0))
1524 av_fifo_generic_read(ctx->unused_surface_queue, &tmp_surf, sizeof(tmp_surf), NULL);
1528 static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *nv_surface,
1529 NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params, const AVFrame *frame)
1531 int dst_linesize[4] = {
1532 lock_buffer_params->pitch,
1533 lock_buffer_params->pitch,
1534 lock_buffer_params->pitch,
1535 lock_buffer_params->pitch
1537 uint8_t *dst_data[4];
1540 if (frame->format == AV_PIX_FMT_YUV420P)
1541 dst_linesize[1] = dst_linesize[2] >>= 1;
1543 ret = av_image_fill_pointers(dst_data, frame->format, nv_surface->height,
1544 lock_buffer_params->bufferDataPtr, dst_linesize);
1548 if (frame->format == AV_PIX_FMT_YUV420P)
1549 FFSWAP(uint8_t*, dst_data[1], dst_data[2]);
1551 av_image_copy(dst_data, dst_linesize,
1552 (const uint8_t**)frame->data, frame->linesize, frame->format,
1553 avctx->width, avctx->height);
1558 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1560 NvencContext *ctx = avctx->priv_data;
1561 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1562 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1563 NVENCSTATUS nv_status;
1567 if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1568 for (i = 0; i < ctx->nb_registered_frames; i++) {
1569 if (!ctx->registered_frames[i].mapped) {
1570 if (ctx->registered_frames[i].regptr) {
1571 nv_status = p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1572 if (nv_status != NV_ENC_SUCCESS)
1573 return nvenc_print_error(avctx, nv_status, "Failed unregistering unused input resource");
1574 ctx->registered_frames[i].ptr = NULL;
1575 ctx->registered_frames[i].regptr = NULL;
1581 return ctx->nb_registered_frames++;
1584 av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1585 return AVERROR(ENOMEM);
1588 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1590 NvencContext *ctx = avctx->priv_data;
1591 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1592 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1594 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frame->hw_frames_ctx->data;
1595 NV_ENC_REGISTER_RESOURCE reg;
1598 for (i = 0; i < ctx->nb_registered_frames; i++) {
1599 if (avctx->pix_fmt == AV_PIX_FMT_CUDA && ctx->registered_frames[i].ptr == frame->data[0])
1601 else if (avctx->pix_fmt == AV_PIX_FMT_D3D11 && ctx->registered_frames[i].ptr == frame->data[0] && ctx->registered_frames[i].ptr_index == (intptr_t)frame->data[1])
1605 idx = nvenc_find_free_reg_resource(avctx);
1609 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1610 reg.width = frames_ctx->width;
1611 reg.height = frames_ctx->height;
1612 reg.pitch = frame->linesize[0];
1613 reg.resourceToRegister = frame->data[0];
1615 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1616 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1618 else if (avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1619 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX;
1620 reg.subResourceIndex = (intptr_t)frame->data[1];
1623 reg.bufferFormat = nvenc_map_buffer_format(frames_ctx->sw_format);
1624 if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1625 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1626 av_get_pix_fmt_name(frames_ctx->sw_format));
1627 return AVERROR(EINVAL);
1630 ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, ®);
1631 if (ret != NV_ENC_SUCCESS) {
1632 nvenc_print_error(avctx, ret, "Error registering an input resource");
1633 return AVERROR_UNKNOWN;
1636 ctx->registered_frames[idx].ptr = frame->data[0];
1637 ctx->registered_frames[idx].ptr_index = reg.subResourceIndex;
1638 ctx->registered_frames[idx].regptr = reg.registeredResource;
1642 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1643 NvencSurface *nvenc_frame)
1645 NvencContext *ctx = avctx->priv_data;
1646 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1647 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1650 NVENCSTATUS nv_status;
1652 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1653 int reg_idx = nvenc_register_frame(avctx, frame);
1655 av_log(avctx, AV_LOG_ERROR, "Could not register an input HW frame\n");
1659 res = av_frame_ref(nvenc_frame->in_ref, frame);
1663 if (!ctx->registered_frames[reg_idx].mapped) {
1664 ctx->registered_frames[reg_idx].in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1665 ctx->registered_frames[reg_idx].in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1666 nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &ctx->registered_frames[reg_idx].in_map);
1667 if (nv_status != NV_ENC_SUCCESS) {
1668 av_frame_unref(nvenc_frame->in_ref);
1669 return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
1673 ctx->registered_frames[reg_idx].mapped += 1;
1675 nvenc_frame->reg_idx = reg_idx;
1676 nvenc_frame->input_surface = ctx->registered_frames[reg_idx].in_map.mappedResource;
1677 nvenc_frame->format = ctx->registered_frames[reg_idx].in_map.mappedBufferFmt;
1678 nvenc_frame->pitch = frame->linesize[0];
1682 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1684 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1685 lockBufferParams.inputBuffer = nvenc_frame->input_surface;
1687 nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
1688 if (nv_status != NV_ENC_SUCCESS) {
1689 return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
1692 nvenc_frame->pitch = lockBufferParams.pitch;
1693 res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
1695 nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
1696 if (nv_status != NV_ENC_SUCCESS) {
1697 return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
1704 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1705 NV_ENC_PIC_PARAMS *params)
1707 NvencContext *ctx = avctx->priv_data;
1709 switch (avctx->codec->id) {
1710 case AV_CODEC_ID_H264:
1711 params->codecPicParams.h264PicParams.sliceMode =
1712 ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1713 params->codecPicParams.h264PicParams.sliceModeData =
1714 ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1716 case AV_CODEC_ID_HEVC:
1717 params->codecPicParams.hevcPicParams.sliceMode =
1718 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1719 params->codecPicParams.hevcPicParams.sliceModeData =
1720 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1725 static inline void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
1727 av_fifo_generic_write(queue, ×tamp, sizeof(timestamp), NULL);
1730 static inline int64_t timestamp_queue_dequeue(AVFifoBuffer* queue)
1732 int64_t timestamp = AV_NOPTS_VALUE;
1733 if (av_fifo_size(queue) > 0)
1734 av_fifo_generic_read(queue, ×tamp, sizeof(timestamp), NULL);
1739 static int nvenc_set_timestamp(AVCodecContext *avctx,
1740 NV_ENC_LOCK_BITSTREAM *params,
1743 NvencContext *ctx = avctx->priv_data;
1745 pkt->pts = params->outputTimeStamp;
1747 /* generate the first dts by linearly extrapolating the
1748 * first two pts values to the past */
1749 if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
1750 ctx->initial_pts[1] != AV_NOPTS_VALUE) {
1751 int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
1754 if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
1755 (ts0 > 0 && ts1 < INT64_MIN + ts0))
1756 return AVERROR(ERANGE);
1759 if ((delta < 0 && ts0 > INT64_MAX + delta) ||
1760 (delta > 0 && ts0 < INT64_MIN + delta))
1761 return AVERROR(ERANGE);
1762 pkt->dts = ts0 - delta;
1764 ctx->first_packet_output = 1;
1768 pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
1773 static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
1775 NvencContext *ctx = avctx->priv_data;
1776 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1777 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1779 uint32_t slice_mode_data;
1780 uint32_t *slice_offsets = NULL;
1781 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1782 NVENCSTATUS nv_status;
1785 enum AVPictureType pict_type;
1787 switch (avctx->codec->id) {
1788 case AV_CODEC_ID_H264:
1789 slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1791 case AV_CODEC_ID_H265:
1792 slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1795 av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
1796 res = AVERROR(EINVAL);
1799 slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
1801 if (!slice_offsets) {
1802 res = AVERROR(ENOMEM);
1806 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1808 lock_params.doNotWait = 0;
1809 lock_params.outputBitstream = tmpoutsurf->output_surface;
1810 lock_params.sliceOffsets = slice_offsets;
1812 nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
1813 if (nv_status != NV_ENC_SUCCESS) {
1814 res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
1818 if (res = ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes,0)) {
1819 p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1823 memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1825 nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1826 if (nv_status != NV_ENC_SUCCESS) {
1827 res = nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
1832 if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1833 ctx->registered_frames[tmpoutsurf->reg_idx].mapped -= 1;
1834 if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped == 0) {
1835 nv_status = p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[tmpoutsurf->reg_idx].in_map.mappedResource);
1836 if (nv_status != NV_ENC_SUCCESS) {
1837 res = nvenc_print_error(avctx, nv_status, "Failed unmapping input resource");
1840 nv_status = p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[tmpoutsurf->reg_idx].regptr);
1841 if (nv_status != NV_ENC_SUCCESS) {
1842 res = nvenc_print_error(avctx, nv_status, "Failed unregistering input resource");
1845 ctx->registered_frames[tmpoutsurf->reg_idx].ptr = NULL;
1846 ctx->registered_frames[tmpoutsurf->reg_idx].regptr = NULL;
1847 } else if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped < 0) {
1852 av_frame_unref(tmpoutsurf->in_ref);
1854 tmpoutsurf->input_surface = NULL;
1857 switch (lock_params.pictureType) {
1858 case NV_ENC_PIC_TYPE_IDR:
1859 pkt->flags |= AV_PKT_FLAG_KEY;
1860 case NV_ENC_PIC_TYPE_I:
1861 pict_type = AV_PICTURE_TYPE_I;
1863 case NV_ENC_PIC_TYPE_P:
1864 pict_type = AV_PICTURE_TYPE_P;
1866 case NV_ENC_PIC_TYPE_B:
1867 pict_type = AV_PICTURE_TYPE_B;
1869 case NV_ENC_PIC_TYPE_BI:
1870 pict_type = AV_PICTURE_TYPE_BI;
1873 av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
1874 av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
1875 res = AVERROR_EXTERNAL;
1879 #if FF_API_CODED_FRAME
1880 FF_DISABLE_DEPRECATION_WARNINGS
1881 avctx->coded_frame->pict_type = pict_type;
1882 FF_ENABLE_DEPRECATION_WARNINGS
1885 ff_side_data_set_encoder_stats(pkt,
1886 (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
1888 res = nvenc_set_timestamp(avctx, &lock_params, pkt);
1892 av_free(slice_offsets);
1897 timestamp_queue_dequeue(ctx->timestamp_list);
1900 av_free(slice_offsets);
1905 static int output_ready(AVCodecContext *avctx, int flush)
1907 NvencContext *ctx = avctx->priv_data;
1908 int nb_ready, nb_pending;
1910 /* when B-frames are enabled, we wait for two initial timestamps to
1911 * calculate the first dts */
1912 if (!flush && avctx->max_b_frames > 0 &&
1913 (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
1916 nb_ready = av_fifo_size(ctx->output_surface_ready_queue) / sizeof(NvencSurface*);
1917 nb_pending = av_fifo_size(ctx->output_surface_queue) / sizeof(NvencSurface*);
1919 return nb_ready > 0;
1920 return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
1923 int ff_nvenc_send_frame(AVCodecContext *avctx, const AVFrame *frame)
1925 NVENCSTATUS nv_status;
1926 NvencSurface *tmp_out_surf, *in_surf;
1929 NvencContext *ctx = avctx->priv_data;
1930 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1931 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1933 NV_ENC_PIC_PARAMS pic_params = { 0 };
1934 pic_params.version = NV_ENC_PIC_PARAMS_VER;
1936 if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
1937 return AVERROR(EINVAL);
1939 if (ctx->encoder_flushing)
1943 in_surf = get_free_frame(ctx);
1945 return AVERROR(EAGAIN);
1947 res = nvenc_push_context(avctx);
1951 res = nvenc_upload_frame(avctx, frame, in_surf);
1953 res2 = nvenc_pop_context(avctx);
1960 pic_params.inputBuffer = in_surf->input_surface;
1961 pic_params.bufferFmt = in_surf->format;
1962 pic_params.inputWidth = in_surf->width;
1963 pic_params.inputHeight = in_surf->height;
1964 pic_params.inputPitch = in_surf->pitch;
1965 pic_params.outputBitstream = in_surf->output_surface;
1967 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1968 if (frame->top_field_first)
1969 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
1971 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
1973 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1976 if (ctx->forced_idr >= 0 && frame->pict_type == AV_PICTURE_TYPE_I) {
1977 pic_params.encodePicFlags =
1978 ctx->forced_idr ? NV_ENC_PIC_FLAG_FORCEIDR : NV_ENC_PIC_FLAG_FORCEINTRA;
1980 pic_params.encodePicFlags = 0;
1983 pic_params.inputTimeStamp = frame->pts;
1985 nvenc_codec_specific_pic_params(avctx, &pic_params);
1987 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1988 ctx->encoder_flushing = 1;
1991 res = nvenc_push_context(avctx);
1995 nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
1997 res = nvenc_pop_context(avctx);
2001 if (nv_status != NV_ENC_SUCCESS &&
2002 nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
2003 return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
2006 av_fifo_generic_write(ctx->output_surface_queue, &in_surf, sizeof(in_surf), NULL);
2007 timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
2009 if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
2010 ctx->initial_pts[0] = frame->pts;
2011 else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
2012 ctx->initial_pts[1] = frame->pts;
2015 /* all the pending buffers are now ready for output */
2016 if (nv_status == NV_ENC_SUCCESS) {
2017 while (av_fifo_size(ctx->output_surface_queue) > 0) {
2018 av_fifo_generic_read(ctx->output_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2019 av_fifo_generic_write(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2026 int ff_nvenc_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
2028 NvencSurface *tmp_out_surf;
2031 NvencContext *ctx = avctx->priv_data;
2033 if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
2034 return AVERROR(EINVAL);
2036 if (output_ready(avctx, ctx->encoder_flushing)) {
2037 av_fifo_generic_read(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2039 res = nvenc_push_context(avctx);
2043 res = process_output_surface(avctx, pkt, tmp_out_surf);
2045 res2 = nvenc_pop_context(avctx);
2052 av_fifo_generic_write(ctx->unused_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2053 } else if (ctx->encoder_flushing) {
2056 return AVERROR(EAGAIN);
2062 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
2063 const AVFrame *frame, int *got_packet)
2065 NvencContext *ctx = avctx->priv_data;
2068 if (!ctx->encoder_flushing) {
2069 res = ff_nvenc_send_frame(avctx, frame);
2074 res = ff_nvenc_receive_packet(avctx, pkt);
2075 if (res == AVERROR(EAGAIN) || res == AVERROR_EOF) {
2077 } else if (res < 0) {