2 * H.264 hardware encoding using nvidia nvenc
3 * Copyright (c) 2014 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
30 #include "libavutil/imgutils.h"
31 #include "libavutil/avassert.h"
32 #include "libavutil/mem.h"
33 #include "libavutil/hwcontext.h"
40 #include "libavutil/hwcontext_cuda.h"
44 #define LOAD_FUNC(l, s) GetProcAddress(l, s)
45 #define DL_CLOSE_FUNC(l) FreeLibrary(l)
47 #define LOAD_FUNC(l, s) dlsym(l, s)
48 #define DL_CLOSE_FUNC(l) dlclose(l)
51 const enum AVPixelFormat ff_nvenc_pix_fmts[] = {
61 typedef struct NvencData
65 NvencSurface *surface;
69 typedef struct NvencValuePair
75 static const NvencValuePair nvenc_h264_level_pairs[] = {
76 { "auto", NV_ENC_LEVEL_AUTOSELECT },
77 { "1" , NV_ENC_LEVEL_H264_1 },
78 { "1.0" , NV_ENC_LEVEL_H264_1 },
79 { "1b" , NV_ENC_LEVEL_H264_1b },
80 { "1.0b", NV_ENC_LEVEL_H264_1b },
81 { "1.1" , NV_ENC_LEVEL_H264_11 },
82 { "1.2" , NV_ENC_LEVEL_H264_12 },
83 { "1.3" , NV_ENC_LEVEL_H264_13 },
84 { "2" , NV_ENC_LEVEL_H264_2 },
85 { "2.0" , NV_ENC_LEVEL_H264_2 },
86 { "2.1" , NV_ENC_LEVEL_H264_21 },
87 { "2.2" , NV_ENC_LEVEL_H264_22 },
88 { "3" , NV_ENC_LEVEL_H264_3 },
89 { "3.0" , NV_ENC_LEVEL_H264_3 },
90 { "3.1" , NV_ENC_LEVEL_H264_31 },
91 { "3.2" , NV_ENC_LEVEL_H264_32 },
92 { "4" , NV_ENC_LEVEL_H264_4 },
93 { "4.0" , NV_ENC_LEVEL_H264_4 },
94 { "4.1" , NV_ENC_LEVEL_H264_41 },
95 { "4.2" , NV_ENC_LEVEL_H264_42 },
96 { "5" , NV_ENC_LEVEL_H264_5 },
97 { "5.0" , NV_ENC_LEVEL_H264_5 },
98 { "5.1" , NV_ENC_LEVEL_H264_51 },
102 static const NvencValuePair nvenc_hevc_level_pairs[] = {
103 { "auto", NV_ENC_LEVEL_AUTOSELECT },
104 { "1" , NV_ENC_LEVEL_HEVC_1 },
105 { "1.0" , NV_ENC_LEVEL_HEVC_1 },
106 { "2" , NV_ENC_LEVEL_HEVC_2 },
107 { "2.0" , NV_ENC_LEVEL_HEVC_2 },
108 { "2.1" , NV_ENC_LEVEL_HEVC_21 },
109 { "3" , NV_ENC_LEVEL_HEVC_3 },
110 { "3.0" , NV_ENC_LEVEL_HEVC_3 },
111 { "3.1" , NV_ENC_LEVEL_HEVC_31 },
112 { "4" , NV_ENC_LEVEL_HEVC_4 },
113 { "4.0" , NV_ENC_LEVEL_HEVC_4 },
114 { "4.1" , NV_ENC_LEVEL_HEVC_41 },
115 { "5" , NV_ENC_LEVEL_HEVC_5 },
116 { "5.0" , NV_ENC_LEVEL_HEVC_5 },
117 { "5.1" , NV_ENC_LEVEL_HEVC_51 },
118 { "5.2" , NV_ENC_LEVEL_HEVC_52 },
119 { "6" , NV_ENC_LEVEL_HEVC_6 },
120 { "6.0" , NV_ENC_LEVEL_HEVC_6 },
121 { "6.1" , NV_ENC_LEVEL_HEVC_61 },
122 { "6.2" , NV_ENC_LEVEL_HEVC_62 },
126 static const struct {
131 { NV_ENC_SUCCESS, 0, "success" },
132 { NV_ENC_ERR_NO_ENCODE_DEVICE, AVERROR(ENOENT), "no encode device" },
133 { NV_ENC_ERR_UNSUPPORTED_DEVICE, AVERROR(ENOSYS), "unsupported device" },
134 { NV_ENC_ERR_INVALID_ENCODERDEVICE, AVERROR(EINVAL), "invalid encoder device" },
135 { NV_ENC_ERR_INVALID_DEVICE, AVERROR(EINVAL), "invalid device" },
136 { NV_ENC_ERR_DEVICE_NOT_EXIST, AVERROR(EIO), "device does not exist" },
137 { NV_ENC_ERR_INVALID_PTR, AVERROR(EFAULT), "invalid ptr" },
138 { NV_ENC_ERR_INVALID_EVENT, AVERROR(EINVAL), "invalid event" },
139 { NV_ENC_ERR_INVALID_PARAM, AVERROR(EINVAL), "invalid param" },
140 { NV_ENC_ERR_INVALID_CALL, AVERROR(EINVAL), "invalid call" },
141 { NV_ENC_ERR_OUT_OF_MEMORY, AVERROR(ENOMEM), "out of memory" },
142 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED, AVERROR(EINVAL), "encoder not initialized" },
143 { NV_ENC_ERR_UNSUPPORTED_PARAM, AVERROR(ENOSYS), "unsupported param" },
144 { NV_ENC_ERR_LOCK_BUSY, AVERROR(EAGAIN), "lock busy" },
145 { NV_ENC_ERR_NOT_ENOUGH_BUFFER, AVERROR(ENOBUFS), "not enough buffer" },
146 { NV_ENC_ERR_INVALID_VERSION, AVERROR(EINVAL), "invalid version" },
147 { NV_ENC_ERR_MAP_FAILED, AVERROR(EIO), "map failed" },
148 { NV_ENC_ERR_NEED_MORE_INPUT, AVERROR(EAGAIN), "need more input" },
149 { NV_ENC_ERR_ENCODER_BUSY, AVERROR(EAGAIN), "encoder busy" },
150 { NV_ENC_ERR_EVENT_NOT_REGISTERD, AVERROR(EBADF), "event not registered" },
151 { NV_ENC_ERR_GENERIC, AVERROR_UNKNOWN, "generic error" },
152 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY, AVERROR(EINVAL), "incompatible client key" },
153 { NV_ENC_ERR_UNIMPLEMENTED, AVERROR(ENOSYS), "unimplemented" },
154 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO), "resource register failed" },
155 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED, AVERROR(EBADF), "resource not registered" },
156 { NV_ENC_ERR_RESOURCE_NOT_MAPPED, AVERROR(EBADF), "resource not mapped" },
159 static int nvenc_map_error(NVENCSTATUS err, const char **desc)
162 for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
163 if (nvenc_errors[i].nverr == err) {
165 *desc = nvenc_errors[i].desc;
166 return nvenc_errors[i].averr;
170 *desc = "unknown error";
171 return AVERROR_UNKNOWN;
174 static int nvenc_print_error(void *log_ctx, NVENCSTATUS err,
175 const char *error_string)
179 ret = nvenc_map_error(err, &desc);
180 av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
184 static int input_string_to_uint32(AVCodecContext *avctx, const NvencValuePair *pair, const char *input, uint32_t *output)
186 for (; pair->str; ++pair) {
187 if (!strcmp(input, pair->str)) {
193 return AVERROR(EINVAL);
196 static void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
198 av_fifo_generic_write(queue, ×tamp, sizeof(timestamp), NULL);
201 static int64_t timestamp_queue_dequeue(AVFifoBuffer* queue)
203 int64_t timestamp = AV_NOPTS_VALUE;
204 if (av_fifo_size(queue) > 0)
205 av_fifo_generic_read(queue, ×tamp, sizeof(timestamp), NULL);
210 #define CHECK_LOAD_FUNC(t, f, s) \
212 (f) = (t)LOAD_FUNC(dl_fn->cuda_lib, s); \
214 av_log(avctx, AV_LOG_FATAL, "Failed loading %s from CUDA library\n", s); \
219 static av_cold int nvenc_dyload_cuda(AVCodecContext *avctx)
221 NvencContext *ctx = avctx->priv_data;
222 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
225 dl_fn->cu_init = cuInit;
226 dl_fn->cu_device_get_count = cuDeviceGetCount;
227 dl_fn->cu_device_get = cuDeviceGet;
228 dl_fn->cu_device_get_name = cuDeviceGetName;
229 dl_fn->cu_device_compute_capability = cuDeviceComputeCapability;
230 dl_fn->cu_ctx_create = cuCtxCreate_v2;
231 dl_fn->cu_ctx_pop_current = cuCtxPopCurrent_v2;
232 dl_fn->cu_ctx_destroy = cuCtxDestroy_v2;
240 dl_fn->cuda_lib = LoadLibrary(TEXT("nvcuda.dll"));
242 dl_fn->cuda_lib = dlopen("libcuda.so", RTLD_LAZY);
245 if (!dl_fn->cuda_lib) {
246 av_log(avctx, AV_LOG_FATAL, "Failed loading CUDA library\n");
250 CHECK_LOAD_FUNC(PCUINIT, dl_fn->cu_init, "cuInit");
251 CHECK_LOAD_FUNC(PCUDEVICEGETCOUNT, dl_fn->cu_device_get_count, "cuDeviceGetCount");
252 CHECK_LOAD_FUNC(PCUDEVICEGET, dl_fn->cu_device_get, "cuDeviceGet");
253 CHECK_LOAD_FUNC(PCUDEVICEGETNAME, dl_fn->cu_device_get_name, "cuDeviceGetName");
254 CHECK_LOAD_FUNC(PCUDEVICECOMPUTECAPABILITY, dl_fn->cu_device_compute_capability, "cuDeviceComputeCapability");
255 CHECK_LOAD_FUNC(PCUCTXCREATE, dl_fn->cu_ctx_create, "cuCtxCreate_v2");
256 CHECK_LOAD_FUNC(PCUCTXPOPCURRENT, dl_fn->cu_ctx_pop_current, "cuCtxPopCurrent_v2");
257 CHECK_LOAD_FUNC(PCUCTXDESTROY, dl_fn->cu_ctx_destroy, "cuCtxDestroy_v2");
264 DL_CLOSE_FUNC(dl_fn->cuda_lib);
266 dl_fn->cuda_lib = NULL;
272 static av_cold int check_cuda_errors(AVCodecContext *avctx, CUresult err, const char *func)
274 if (err != CUDA_SUCCESS) {
275 av_log(avctx, AV_LOG_FATAL, ">> %s - failed with error code 0x%x\n", func, err);
280 #define check_cuda_errors(f) if (!check_cuda_errors(avctx, f, #f)) goto error
282 static av_cold int nvenc_check_cuda(AVCodecContext *avctx)
284 int device_count = 0;
285 CUdevice cu_device = 0;
287 int smminor = 0, smmajor = 0;
288 int i, smver, target_smver;
290 NvencContext *ctx = avctx->priv_data;
291 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
293 switch (avctx->codec->id) {
294 case AV_CODEC_ID_H264:
295 target_smver = ctx->data_pix_fmt == AV_PIX_FMT_YUV444P ? 0x52 : 0x30;
297 case AV_CODEC_ID_H265:
301 av_log(avctx, AV_LOG_FATAL, "Unknown codec name\n");
305 if (!strncmp(ctx->preset, "lossless", 8))
308 if (!nvenc_dyload_cuda(avctx))
311 if (dl_fn->nvenc_device_count > 0)
314 check_cuda_errors(dl_fn->cu_init(0));
316 check_cuda_errors(dl_fn->cu_device_get_count(&device_count));
319 av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
323 av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", device_count);
325 dl_fn->nvenc_device_count = 0;
327 for (i = 0; i < device_count; ++i) {
328 check_cuda_errors(dl_fn->cu_device_get(&cu_device, i));
329 check_cuda_errors(dl_fn->cu_device_get_name(gpu_name, sizeof(gpu_name), cu_device));
330 check_cuda_errors(dl_fn->cu_device_compute_capability(&smmajor, &smminor, cu_device));
332 smver = (smmajor << 4) | smminor;
334 av_log(avctx, AV_LOG_VERBOSE, "[ GPU #%d - < %s > has Compute SM %d.%d, NVENC %s ]\n", i, gpu_name, smmajor, smminor, (smver >= target_smver) ? "Available" : "Not Available");
336 if (smver >= target_smver)
337 dl_fn->nvenc_devices[dl_fn->nvenc_device_count++] = cu_device;
340 if (!dl_fn->nvenc_device_count) {
341 av_log(avctx, AV_LOG_FATAL, "No NVENC capable devices found\n");
349 dl_fn->nvenc_device_count = 0;
354 static av_cold int nvenc_dyload_nvenc(AVCodecContext *avctx)
356 PNVENCODEAPICREATEINSTANCE nvEncodeAPICreateInstance = 0;
357 NVENCSTATUS nvstatus;
359 NvencContext *ctx = avctx->priv_data;
360 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
362 if (!nvenc_check_cuda(avctx))
365 if (dl_fn->nvenc_lib)
369 if (sizeof(void*) == 8) {
370 dl_fn->nvenc_lib = LoadLibrary(TEXT("nvEncodeAPI64.dll"));
372 dl_fn->nvenc_lib = LoadLibrary(TEXT("nvEncodeAPI.dll"));
375 dl_fn->nvenc_lib = dlopen("libnvidia-encode.so.1", RTLD_LAZY);
378 if (!dl_fn->nvenc_lib) {
379 av_log(avctx, AV_LOG_FATAL, "Failed loading the nvenc library\n");
383 nvEncodeAPICreateInstance = (PNVENCODEAPICREATEINSTANCE)LOAD_FUNC(dl_fn->nvenc_lib, "NvEncodeAPICreateInstance");
385 if (!nvEncodeAPICreateInstance) {
386 av_log(avctx, AV_LOG_FATAL, "Failed to load nvenc entrypoint\n");
390 dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
392 nvstatus = nvEncodeAPICreateInstance(&dl_fn->nvenc_funcs);
394 if (nvstatus != NV_ENC_SUCCESS) {
395 nvenc_print_error(avctx, nvstatus, "Failed to create nvenc instance");
399 av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
404 if (dl_fn->nvenc_lib)
405 DL_CLOSE_FUNC(dl_fn->nvenc_lib);
407 dl_fn->nvenc_lib = NULL;
412 static av_cold void nvenc_unload_nvenc(AVCodecContext *avctx)
414 NvencContext *ctx = avctx->priv_data;
415 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
417 DL_CLOSE_FUNC(dl_fn->nvenc_lib);
418 dl_fn->nvenc_lib = NULL;
420 dl_fn->nvenc_device_count = 0;
423 DL_CLOSE_FUNC(dl_fn->cuda_lib);
424 dl_fn->cuda_lib = NULL;
427 dl_fn->cu_init = NULL;
428 dl_fn->cu_device_get_count = NULL;
429 dl_fn->cu_device_get = NULL;
430 dl_fn->cu_device_get_name = NULL;
431 dl_fn->cu_device_compute_capability = NULL;
432 dl_fn->cu_ctx_create = NULL;
433 dl_fn->cu_ctx_pop_current = NULL;
434 dl_fn->cu_ctx_destroy = NULL;
436 av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
439 static av_cold int nvenc_setup_device(AVCodecContext *avctx)
441 NvencContext *ctx = avctx->priv_data;
442 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
445 CUcontext cu_context_curr;
447 ctx->data_pix_fmt = avctx->pix_fmt;
450 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
451 AVHWFramesContext *frames_ctx;
452 AVCUDADeviceContext *device_hwctx;
454 if (!avctx->hw_frames_ctx) {
455 av_log(avctx, AV_LOG_ERROR, "hw_frames_ctx must be set when using GPU frames as input\n");
456 return AVERROR(EINVAL);
459 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
460 device_hwctx = frames_ctx->device_ctx->hwctx;
461 ctx->cu_context = device_hwctx->cuda_ctx;
462 ctx->data_pix_fmt = frames_ctx->sw_format;
467 if (ctx->gpu >= dl_fn->nvenc_device_count) {
468 av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->gpu, dl_fn->nvenc_device_count);
469 return AVERROR(EINVAL);
472 ctx->cu_context = NULL;
473 cu_res = dl_fn->cu_ctx_create(&ctx->cu_context_internal, 4, dl_fn->nvenc_devices[ctx->gpu]); // CU_CTX_SCHED_BLOCKING_SYNC=4, avoid CPU spins
475 if (cu_res != CUDA_SUCCESS) {
476 av_log(avctx, AV_LOG_FATAL, "Failed creating CUDA context for NVENC: 0x%x\n", (int)cu_res);
477 return AVERROR_EXTERNAL;
480 cu_res = dl_fn->cu_ctx_pop_current(&cu_context_curr);
482 if (cu_res != CUDA_SUCCESS) {
483 av_log(avctx, AV_LOG_FATAL, "Failed popping CUDA context: 0x%x\n", (int)cu_res);
484 return AVERROR_EXTERNAL;
487 ctx->cu_context = ctx->cu_context_internal;
492 static av_cold int nvenc_open_session(AVCodecContext *avctx)
494 NvencContext *ctx = avctx->priv_data;
495 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
496 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
498 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS encode_session_params = { 0 };
499 NVENCSTATUS nv_status;
501 encode_session_params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
502 encode_session_params.apiVersion = NVENCAPI_VERSION;
503 encode_session_params.device = ctx->cu_context;
504 encode_session_params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
506 nv_status = p_nvenc->nvEncOpenEncodeSessionEx(&encode_session_params, &ctx->nvencoder);
507 if (nv_status != NV_ENC_SUCCESS) {
508 ctx->nvencoder = NULL;
509 return nvenc_print_error(avctx, nv_status, "OpenEncodeSessionEx failed");
515 static av_cold void set_constqp(AVCodecContext *avctx)
517 NvencContext *ctx = avctx->priv_data;
519 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
520 ctx->encode_config.rcParams.constQP.qpInterB = avctx->global_quality;
521 ctx->encode_config.rcParams.constQP.qpInterP = avctx->global_quality;
522 ctx->encode_config.rcParams.constQP.qpIntra = avctx->global_quality;
525 static av_cold void set_vbr(AVCodecContext *avctx)
527 NvencContext *ctx = avctx->priv_data;
529 ctx->encode_config.rcParams.enableMinQP = 1;
530 ctx->encode_config.rcParams.enableMaxQP = 1;
532 ctx->encode_config.rcParams.minQP.qpInterB = avctx->qmin;
533 ctx->encode_config.rcParams.minQP.qpInterP = avctx->qmin;
534 ctx->encode_config.rcParams.minQP.qpIntra = avctx->qmin;
536 ctx->encode_config.rcParams.maxQP.qpInterB = avctx->qmax;
537 ctx->encode_config.rcParams.maxQP.qpInterP = avctx->qmax;
538 ctx->encode_config.rcParams.maxQP.qpIntra = avctx->qmax;
541 static av_cold void set_lossless(AVCodecContext *avctx)
543 NvencContext *ctx = avctx->priv_data;
545 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
546 ctx->encode_config.rcParams.constQP.qpInterB = 0;
547 ctx->encode_config.rcParams.constQP.qpInterP = 0;
548 ctx->encode_config.rcParams.constQP.qpIntra = 0;
551 static av_cold void nvenc_setup_rate_control(AVCodecContext *avctx, int lossless)
553 NvencContext *ctx = avctx->priv_data;
557 if (avctx->bit_rate > 0) {
558 ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
559 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
560 ctx->encode_config.rcParams.maxBitRate = ctx->encode_config.rcParams.averageBitRate;
563 if (avctx->rc_max_rate > 0)
564 ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
567 if (avctx->codec->id == AV_CODEC_ID_H264)
568 ctx->encode_config.encodeCodecConfig.h264Config.qpPrimeYZeroTransformBypassFlag = 1;
574 } else if (ctx->cbr) {
576 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CBR;
578 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_2_PASS_QUALITY;
580 if (avctx->codec->id == AV_CODEC_ID_H264) {
581 ctx->encode_config.encodeCodecConfig.h264Config.adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
582 ctx->encode_config.encodeCodecConfig.h264Config.fmoMode = NV_ENC_H264_FMO_DISABLE;
586 if (avctx->codec->id == AV_CODEC_ID_H264) {
587 ctx->encode_config.encodeCodecConfig.h264Config.outputBufferingPeriodSEI = 1;
588 ctx->encode_config.encodeCodecConfig.h264Config.outputPictureTimingSEI = 1;
589 } else if (avctx->codec->id == AV_CODEC_ID_H265) {
590 ctx->encode_config.encodeCodecConfig.hevcConfig.outputBufferingPeriodSEI = 1;
591 ctx->encode_config.encodeCodecConfig.hevcConfig.outputPictureTimingSEI = 1;
593 } else if (avctx->global_quality > 0) {
599 if (avctx->qmin >= 0 && avctx->qmax >= 0) {
602 qp_inter_p = (avctx->qmax + 3 * avctx->qmin) / 4; // biased towards Qmin
605 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_2_PASS_VBR;
606 if (avctx->codec->id == AV_CODEC_ID_H264) {
607 ctx->encode_config.encodeCodecConfig.h264Config.adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
608 ctx->encode_config.encodeCodecConfig.h264Config.fmoMode = NV_ENC_H264_FMO_DISABLE;
611 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR_MINQP;
614 qp_inter_p = 26; // default to 26
617 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_2_PASS_VBR;
619 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
623 ctx->encode_config.rcParams.enableInitialRCQP = 1;
624 ctx->encode_config.rcParams.initialRCQP.qpInterP = qp_inter_p;
626 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
627 ctx->encode_config.rcParams.initialRCQP.qpIntra = av_clip(
628 qp_inter_p * fabs(avctx->i_quant_factor) + avctx->i_quant_offset, 0, 51);
629 ctx->encode_config.rcParams.initialRCQP.qpInterB = av_clip(
630 qp_inter_p * fabs(avctx->b_quant_factor) + avctx->b_quant_offset, 0, 51);
632 ctx->encode_config.rcParams.initialRCQP.qpIntra = qp_inter_p;
633 ctx->encode_config.rcParams.initialRCQP.qpInterB = qp_inter_p;
637 if (avctx->rc_buffer_size > 0) {
638 ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
639 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
640 ctx->encode_config.rcParams.vbvBufferSize = 2 * ctx->encode_config.rcParams.averageBitRate;
644 static av_cold int nvenc_setup_h264_config(AVCodecContext *avctx, int lossless)
646 NvencContext *ctx = avctx->priv_data;
649 ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.colourMatrix = avctx->colorspace;
650 ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.colourPrimaries = avctx->color_primaries;
651 ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.transferCharacteristics = avctx->color_trc;
652 ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
653 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
655 ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.colourDescriptionPresentFlag =
656 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
658 ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.videoSignalTypePresentFlag =
659 (ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.colourDescriptionPresentFlag
660 || ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.videoFormat != 5
661 || ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.videoFullRangeFlag != 0);
663 ctx->encode_config.encodeCodecConfig.h264Config.sliceMode = 3;
664 ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData = 1;
666 ctx->encode_config.encodeCodecConfig.h264Config.disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
667 ctx->encode_config.encodeCodecConfig.h264Config.repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
669 ctx->encode_config.encodeCodecConfig.h264Config.outputAUD = 1;
671 if (!ctx->profile && !lossless) {
672 switch (avctx->profile) {
673 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
674 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
676 case FF_PROFILE_H264_BASELINE:
677 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
679 case FF_PROFILE_H264_MAIN:
680 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
682 case FF_PROFILE_H264_HIGH:
683 case FF_PROFILE_UNKNOWN:
684 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
687 av_log(avctx, AV_LOG_WARNING, "Unsupported profile requested, falling back to high\n");
688 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
691 } else if (!lossless) {
692 if (!strcmp(ctx->profile, "high")) {
693 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
694 avctx->profile = FF_PROFILE_H264_HIGH;
695 } else if (!strcmp(ctx->profile, "main")) {
696 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
697 avctx->profile = FF_PROFILE_H264_MAIN;
698 } else if (!strcmp(ctx->profile, "baseline")) {
699 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
700 avctx->profile = FF_PROFILE_H264_BASELINE;
701 } else if (!strcmp(ctx->profile, "high444p")) {
702 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
703 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
705 av_log(avctx, AV_LOG_FATAL, "Profile \"%s\" is unknown! Supported profiles: high, main, baseline\n", ctx->profile);
706 return AVERROR(EINVAL);
710 // force setting profile as high444p if input is AV_PIX_FMT_YUV444P
711 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P) {
712 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
713 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
716 ctx->encode_config.encodeCodecConfig.h264Config.chromaFormatIDC = avctx->profile == FF_PROFILE_H264_HIGH_444_PREDICTIVE ? 3 : 1;
719 res = input_string_to_uint32(avctx, nvenc_h264_level_pairs, ctx->level, &ctx->encode_config.encodeCodecConfig.h264Config.level);
722 av_log(avctx, AV_LOG_FATAL, "Level \"%s\" is unknown! Supported levels: auto, 1, 1b, 1.1, 1.2, 1.3, 2, 2.1, 2.2, 3, 3.1, 3.2, 4, 4.1, 4.2, 5, 5.1\n", ctx->level);
726 ctx->encode_config.encodeCodecConfig.h264Config.level = NV_ENC_LEVEL_AUTOSELECT;
732 static av_cold int nvenc_setup_hevc_config(AVCodecContext *avctx)
734 NvencContext *ctx = avctx->priv_data;
737 ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.colourMatrix = avctx->colorspace;
738 ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.colourPrimaries = avctx->color_primaries;
739 ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.transferCharacteristics = avctx->color_trc;
740 ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
741 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
743 ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.colourDescriptionPresentFlag =
744 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
746 ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.videoSignalTypePresentFlag =
747 (ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.colourDescriptionPresentFlag
748 || ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.videoFormat != 5
749 || ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.videoFullRangeFlag != 0);
751 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode = 3;
752 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData = 1;
754 ctx->encode_config.encodeCodecConfig.hevcConfig.disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
755 ctx->encode_config.encodeCodecConfig.hevcConfig.repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
757 ctx->encode_config.encodeCodecConfig.hevcConfig.outputAUD = 1;
759 /* No other profile is supported in the current SDK version 5 */
760 ctx->encode_config.profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
761 avctx->profile = FF_PROFILE_HEVC_MAIN;
764 res = input_string_to_uint32(avctx, nvenc_hevc_level_pairs, ctx->level, &ctx->encode_config.encodeCodecConfig.hevcConfig.level);
767 av_log(avctx, AV_LOG_FATAL, "Level \"%s\" is unknown! Supported levels: auto, 1, 2, 2.1, 3, 3.1, 4, 4.1, 5, 5.1, 5.2, 6, 6.1, 6.2\n", ctx->level);
771 ctx->encode_config.encodeCodecConfig.hevcConfig.level = NV_ENC_LEVEL_AUTOSELECT;
775 if (!strcmp(ctx->tier, "main")) {
776 ctx->encode_config.encodeCodecConfig.hevcConfig.tier = NV_ENC_TIER_HEVC_MAIN;
777 } else if (!strcmp(ctx->tier, "high")) {
778 ctx->encode_config.encodeCodecConfig.hevcConfig.tier = NV_ENC_TIER_HEVC_HIGH;
780 av_log(avctx, AV_LOG_FATAL, "Tier \"%s\" is unknown! Supported tiers: main, high\n", ctx->tier);
781 return AVERROR(EINVAL);
788 static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx, int lossless)
790 switch (avctx->codec->id) {
791 case AV_CODEC_ID_H264:
792 return nvenc_setup_h264_config(avctx, lossless);
793 case AV_CODEC_ID_H265:
794 return nvenc_setup_hevc_config(avctx);
795 /* Earlier switch/case will return if unknown codec is passed. */
801 static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
803 NvencContext *ctx = avctx->priv_data;
804 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
805 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
807 NV_ENC_PRESET_CONFIG preset_config = { 0 };
808 GUID encoder_preset = NV_ENC_PRESET_HQ_GUID;
810 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
811 AVCPBProperties *cpb_props;
818 ctx->last_dts = AV_NOPTS_VALUE;
820 ctx->encode_config.version = NV_ENC_CONFIG_VER;
821 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
822 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
823 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
826 if (!strcmp(ctx->preset, "slow")) {
827 encoder_preset = NV_ENC_PRESET_HQ_GUID;
829 } else if (!strcmp(ctx->preset, "medium")) {
830 encoder_preset = NV_ENC_PRESET_HQ_GUID;
832 } else if (!strcmp(ctx->preset, "fast")) {
833 encoder_preset = NV_ENC_PRESET_HP_GUID;
835 } else if (!strcmp(ctx->preset, "hq")) {
836 encoder_preset = NV_ENC_PRESET_HQ_GUID;
837 } else if (!strcmp(ctx->preset, "hp")) {
838 encoder_preset = NV_ENC_PRESET_HP_GUID;
839 } else if (!strcmp(ctx->preset, "bd")) {
840 encoder_preset = NV_ENC_PRESET_BD_GUID;
841 } else if (!strcmp(ctx->preset, "ll")) {
842 encoder_preset = NV_ENC_PRESET_LOW_LATENCY_DEFAULT_GUID;
844 } else if (!strcmp(ctx->preset, "llhp")) {
845 encoder_preset = NV_ENC_PRESET_LOW_LATENCY_HP_GUID;
847 } else if (!strcmp(ctx->preset, "llhq")) {
848 encoder_preset = NV_ENC_PRESET_LOW_LATENCY_HQ_GUID;
850 } else if (!strcmp(ctx->preset, "lossless")) {
851 encoder_preset = NV_ENC_PRESET_LOSSLESS_DEFAULT_GUID;
853 } else if (!strcmp(ctx->preset, "losslesshp")) {
854 encoder_preset = NV_ENC_PRESET_LOSSLESS_HP_GUID;
856 } else if (!strcmp(ctx->preset, "default")) {
857 encoder_preset = NV_ENC_PRESET_DEFAULT_GUID;
859 av_log(avctx, AV_LOG_FATAL, "Preset \"%s\" is unknown! Supported presets: slow, medium, fast, hp, hq, bd, ll, llhp, llhq, lossless, losslesshp, default\n", ctx->preset);
860 return AVERROR(EINVAL);
864 if (ctx->twopass < 0) {
868 switch (avctx->codec->id) {
869 case AV_CODEC_ID_H264:
870 codec = NV_ENC_CODEC_H264_GUID;
872 case AV_CODEC_ID_H265:
873 codec = NV_ENC_CODEC_HEVC_GUID;
876 av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
877 return AVERROR(EINVAL);
880 nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder, codec, encoder_preset, &preset_config);
881 if (nv_status != NV_ENC_SUCCESS) {
882 return nvenc_print_error(avctx, nv_status, "GetEncodePresetConfig failed");
885 ctx->init_encode_params.encodeGUID = codec;
886 ctx->init_encode_params.encodeHeight = avctx->height;
887 ctx->init_encode_params.encodeWidth = avctx->width;
889 if (avctx->sample_aspect_ratio.num && avctx->sample_aspect_ratio.den &&
890 (avctx->sample_aspect_ratio.num != 1 || avctx->sample_aspect_ratio.num != 1)) {
892 avctx->width * avctx->sample_aspect_ratio.num,
893 avctx->height * avctx->sample_aspect_ratio.den,
895 ctx->init_encode_params.darHeight = dh;
896 ctx->init_encode_params.darWidth = dw;
898 ctx->init_encode_params.darHeight = avctx->height;
899 ctx->init_encode_params.darWidth = avctx->width;
902 // De-compensate for hardware, dubiously, trying to compensate for
903 // playback at 704 pixel width.
904 if (avctx->width == 720 &&
905 (avctx->height == 480 || avctx->height == 576)) {
907 ctx->init_encode_params.darWidth * 44,
908 ctx->init_encode_params.darHeight * 45,
910 ctx->init_encode_params.darHeight = dh;
911 ctx->init_encode_params.darWidth = dw;
914 ctx->init_encode_params.frameRateNum = avctx->time_base.den;
915 ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
917 num_mbs = ((avctx->width + 15) >> 4) * ((avctx->height + 15) >> 4);
918 ctx->max_surface_count = (num_mbs >= 8160) ? 32 : 48;
920 if (ctx->buffer_delay >= ctx->max_surface_count)
921 ctx->buffer_delay = ctx->max_surface_count - 1;
923 ctx->init_encode_params.enableEncodeAsync = 0;
924 ctx->init_encode_params.enablePTD = 1;
926 ctx->init_encode_params.presetGUID = encoder_preset;
928 ctx->init_encode_params.encodeConfig = &ctx->encode_config;
929 memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
930 ctx->encode_config.version = NV_ENC_CONFIG_VER;
932 if (avctx->refs >= 0) {
933 /* 0 means "let the hardware decide" */
934 switch (avctx->codec->id) {
935 case AV_CODEC_ID_H264:
936 ctx->encode_config.encodeCodecConfig.h264Config.maxNumRefFrames = avctx->refs;
938 case AV_CODEC_ID_H265:
939 ctx->encode_config.encodeCodecConfig.hevcConfig.maxNumRefFramesInDPB = avctx->refs;
941 /* Earlier switch/case will return if unknown codec is passed. */
945 if (avctx->gop_size > 0) {
946 if (avctx->max_b_frames >= 0) {
947 /* 0 is intra-only, 1 is I/P only, 2 is one B Frame, 3 two B frames, and so on. */
948 ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
951 ctx->encode_config.gopLength = avctx->gop_size;
952 switch (avctx->codec->id) {
953 case AV_CODEC_ID_H264:
954 ctx->encode_config.encodeCodecConfig.h264Config.idrPeriod = avctx->gop_size;
956 case AV_CODEC_ID_H265:
957 ctx->encode_config.encodeCodecConfig.hevcConfig.idrPeriod = avctx->gop_size;
959 /* Earlier switch/case will return if unknown codec is passed. */
961 } else if (avctx->gop_size == 0) {
962 ctx->encode_config.frameIntervalP = 0;
963 ctx->encode_config.gopLength = 1;
964 switch (avctx->codec->id) {
965 case AV_CODEC_ID_H264:
966 ctx->encode_config.encodeCodecConfig.h264Config.idrPeriod = 1;
968 case AV_CODEC_ID_H265:
969 ctx->encode_config.encodeCodecConfig.hevcConfig.idrPeriod = 1;
971 /* Earlier switch/case will return if unknown codec is passed. */
975 /* when there're b frames, set dts offset */
976 if (ctx->encode_config.frameIntervalP >= 2)
979 nvenc_setup_rate_control(avctx, lossless);
981 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
982 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
984 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
987 res = nvenc_setup_codec_config(avctx, lossless);
991 nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
992 if (nv_status != NV_ENC_SUCCESS) {
993 return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
996 if (ctx->encode_config.frameIntervalP > 1)
997 avctx->has_b_frames = 2;
999 if (ctx->encode_config.rcParams.averageBitRate > 0)
1000 avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
1002 cpb_props = ff_add_cpb_side_data(avctx);
1004 return AVERROR(ENOMEM);
1005 cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
1006 cpb_props->avg_bitrate = avctx->bit_rate;
1007 cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
1012 static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
1014 NvencContext *ctx = avctx->priv_data;
1015 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1016 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1018 NVENCSTATUS nv_status;
1019 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
1020 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1022 switch (ctx->data_pix_fmt) {
1023 case AV_PIX_FMT_YUV420P:
1024 ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_YV12_PL;
1027 case AV_PIX_FMT_NV12:
1028 ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_NV12_PL;
1031 case AV_PIX_FMT_YUV444P:
1032 ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_YUV444_PL;
1036 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format\n");
1037 return AVERROR(EINVAL);
1040 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1041 ctx->surfaces[idx].in_ref = av_frame_alloc();
1042 if (!ctx->surfaces[idx].in_ref)
1043 return AVERROR(ENOMEM);
1045 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1046 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1047 allocSurf.width = (avctx->width + 31) & ~31;
1048 allocSurf.height = (avctx->height + 31) & ~31;
1049 allocSurf.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
1050 allocSurf.bufferFmt = ctx->surfaces[idx].format;
1052 nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
1053 if (nv_status != NV_ENC_SUCCESS) {
1054 return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
1057 ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
1058 ctx->surfaces[idx].width = allocSurf.width;
1059 ctx->surfaces[idx].height = allocSurf.height;
1062 ctx->surfaces[idx].lockCount = 0;
1064 /* 1MB is large enough to hold most output frames. NVENC increases this automaticaly if it's not enough. */
1065 allocOut.size = 1024 * 1024;
1067 allocOut.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
1069 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
1070 if (nv_status != NV_ENC_SUCCESS) {
1071 int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
1072 if (avctx->pix_fmt != AV_PIX_FMT_CUDA)
1073 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
1074 av_frame_free(&ctx->surfaces[idx].in_ref);
1078 ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1079 ctx->surfaces[idx].size = allocOut.size;
1084 static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx, int* surfaceCount)
1087 NvencContext *ctx = avctx->priv_data;
1089 ctx->surfaces = av_malloc(ctx->max_surface_count * sizeof(*ctx->surfaces));
1091 if (!ctx->surfaces) {
1092 return AVERROR(ENOMEM);
1095 ctx->timestamp_list = av_fifo_alloc(ctx->max_surface_count * sizeof(int64_t));
1096 if (!ctx->timestamp_list)
1097 return AVERROR(ENOMEM);
1098 ctx->output_surface_queue = av_fifo_alloc(ctx->max_surface_count * sizeof(NvencSurface*));
1099 if (!ctx->output_surface_queue)
1100 return AVERROR(ENOMEM);
1101 ctx->output_surface_ready_queue = av_fifo_alloc(ctx->max_surface_count * sizeof(NvencSurface*));
1102 if (!ctx->output_surface_ready_queue)
1103 return AVERROR(ENOMEM);
1105 for (*surfaceCount = 0; *surfaceCount < ctx->max_surface_count; ++*surfaceCount) {
1106 res = nvenc_alloc_surface(avctx, *surfaceCount);
1114 static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
1116 NvencContext *ctx = avctx->priv_data;
1117 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1118 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1120 NVENCSTATUS nv_status;
1121 uint32_t outSize = 0;
1122 char tmpHeader[256];
1123 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1124 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1126 payload.spsppsBuffer = tmpHeader;
1127 payload.inBufferSize = sizeof(tmpHeader);
1128 payload.outSPSPPSPayloadSize = &outSize;
1130 nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
1131 if (nv_status != NV_ENC_SUCCESS) {
1132 return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
1135 avctx->extradata_size = outSize;
1136 avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
1138 if (!avctx->extradata) {
1139 return AVERROR(ENOMEM);
1142 memcpy(avctx->extradata, tmpHeader, outSize);
1147 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
1149 NvencContext *ctx = avctx->priv_data;
1150 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1151 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1155 int surfaceCount = 0;
1157 if (!nvenc_dyload_nvenc(avctx))
1158 return AVERROR_EXTERNAL;
1160 res = nvenc_setup_device(avctx);
1164 res = nvenc_open_session(avctx);
1168 res = nvenc_setup_encoder(avctx);
1172 res = nvenc_setup_surfaces(avctx, &surfaceCount);
1176 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1177 res = nvenc_setup_extradata(avctx);
1185 av_fifo_freep(&ctx->timestamp_list);
1186 av_fifo_freep(&ctx->output_surface_ready_queue);
1187 av_fifo_freep(&ctx->output_surface_queue);
1189 for (i = 0; i < surfaceCount; ++i) {
1190 if (avctx->pix_fmt != AV_PIX_FMT_CUDA)
1191 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
1192 av_frame_free(&ctx->surfaces[i].in_ref);
1193 p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
1195 av_freep(&ctx->surfaces);
1198 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1199 ctx->nvencoder = NULL;
1201 if (ctx->cu_context_internal)
1202 dl_fn->cu_ctx_destroy(ctx->cu_context_internal);
1203 ctx->cu_context = ctx->cu_context_internal = NULL;
1205 nvenc_unload_nvenc(avctx);
1210 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
1212 NvencContext *ctx = avctx->priv_data;
1213 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1214 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1217 av_fifo_freep(&ctx->timestamp_list);
1218 av_fifo_freep(&ctx->output_surface_ready_queue);
1219 av_fifo_freep(&ctx->output_surface_queue);
1221 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1222 for (i = 0; i < ctx->max_surface_count; ++i) {
1223 if (ctx->surfaces[i].input_surface) {
1224 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->surfaces[i].in_map.mappedResource);
1227 for (i = 0; i < ctx->nb_registered_frames; i++) {
1228 if (ctx->registered_frames[i].regptr)
1229 p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1231 ctx->nb_registered_frames = 0;
1234 for (i = 0; i < ctx->max_surface_count; ++i) {
1235 if (avctx->pix_fmt != AV_PIX_FMT_CUDA)
1236 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
1237 av_frame_free(&ctx->surfaces[i].in_ref);
1238 p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
1240 av_freep(&ctx->surfaces);
1241 ctx->max_surface_count = 0;
1243 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1244 ctx->nvencoder = NULL;
1246 if (ctx->cu_context_internal)
1247 dl_fn->cu_ctx_destroy(ctx->cu_context_internal);
1248 ctx->cu_context = ctx->cu_context_internal = NULL;
1250 nvenc_unload_nvenc(avctx);
1255 static NvencSurface *get_free_frame(NvencContext *ctx)
1259 for (i = 0; i < ctx->max_surface_count; ++i) {
1260 if (!ctx->surfaces[i].lockCount) {
1261 ctx->surfaces[i].lockCount = 1;
1262 return &ctx->surfaces[i];
1269 static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *inSurf,
1270 NV_ENC_LOCK_INPUT_BUFFER *lockBufferParams, const AVFrame *frame)
1272 uint8_t *buf = lockBufferParams->bufferDataPtr;
1273 int off = inSurf->height * lockBufferParams->pitch;
1275 if (frame->format == AV_PIX_FMT_YUV420P) {
1276 av_image_copy_plane(buf, lockBufferParams->pitch,
1277 frame->data[0], frame->linesize[0],
1278 avctx->width, avctx->height);
1282 av_image_copy_plane(buf, lockBufferParams->pitch >> 1,
1283 frame->data[2], frame->linesize[2],
1284 avctx->width >> 1, avctx->height >> 1);
1288 av_image_copy_plane(buf, lockBufferParams->pitch >> 1,
1289 frame->data[1], frame->linesize[1],
1290 avctx->width >> 1, avctx->height >> 1);
1291 } else if (frame->format == AV_PIX_FMT_NV12) {
1292 av_image_copy_plane(buf, lockBufferParams->pitch,
1293 frame->data[0], frame->linesize[0],
1294 avctx->width, avctx->height);
1298 av_image_copy_plane(buf, lockBufferParams->pitch,
1299 frame->data[1], frame->linesize[1],
1300 avctx->width, avctx->height >> 1);
1301 } else if (frame->format == AV_PIX_FMT_YUV444P) {
1302 av_image_copy_plane(buf, lockBufferParams->pitch,
1303 frame->data[0], frame->linesize[0],
1304 avctx->width, avctx->height);
1308 av_image_copy_plane(buf, lockBufferParams->pitch,
1309 frame->data[1], frame->linesize[1],
1310 avctx->width, avctx->height);
1314 av_image_copy_plane(buf, lockBufferParams->pitch,
1315 frame->data[2], frame->linesize[2],
1316 avctx->width, avctx->height);
1318 av_log(avctx, AV_LOG_FATAL, "Invalid pixel format!\n");
1319 return AVERROR(EINVAL);
1325 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1327 NvencContext *ctx = avctx->priv_data;
1328 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1329 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1333 if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1334 for (i = 0; i < ctx->nb_registered_frames; i++) {
1335 if (!ctx->registered_frames[i].mapped) {
1336 if (ctx->registered_frames[i].regptr) {
1337 p_nvenc->nvEncUnregisterResource(ctx->nvencoder,
1338 ctx->registered_frames[i].regptr);
1339 ctx->registered_frames[i].regptr = NULL;
1345 return ctx->nb_registered_frames++;
1348 av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1349 return AVERROR(ENOMEM);
1352 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1354 NvencContext *ctx = avctx->priv_data;
1355 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1356 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1358 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1359 NV_ENC_REGISTER_RESOURCE reg;
1362 for (i = 0; i < ctx->nb_registered_frames; i++) {
1363 if (ctx->registered_frames[i].ptr == (CUdeviceptr)frame->data[0])
1367 idx = nvenc_find_free_reg_resource(avctx);
1371 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1372 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1373 reg.width = frames_ctx->width;
1374 reg.height = frames_ctx->height;
1375 reg.bufferFormat = ctx->surfaces[0].format;
1376 reg.pitch = frame->linesize[0];
1377 reg.resourceToRegister = frame->data[0];
1379 ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, ®);
1380 if (ret != NV_ENC_SUCCESS) {
1381 nvenc_print_error(avctx, ret, "Error registering an input resource");
1382 return AVERROR_UNKNOWN;
1385 ctx->registered_frames[idx].ptr = (CUdeviceptr)frame->data[0];
1386 ctx->registered_frames[idx].regptr = reg.registeredResource;
1390 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1391 NvencSurface *nvenc_frame)
1393 NvencContext *ctx = avctx->priv_data;
1394 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1395 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1398 NVENCSTATUS nv_status;
1400 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1401 int reg_idx = nvenc_register_frame(avctx, frame);
1403 av_log(avctx, AV_LOG_ERROR, "Could not register an input CUDA frame\n");
1407 res = av_frame_ref(nvenc_frame->in_ref, frame);
1411 nvenc_frame->in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1412 nvenc_frame->in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1413 nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &nvenc_frame->in_map);
1414 if (nv_status != NV_ENC_SUCCESS) {
1415 av_frame_unref(nvenc_frame->in_ref);
1416 return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
1419 ctx->registered_frames[reg_idx].mapped = 1;
1420 nvenc_frame->reg_idx = reg_idx;
1421 nvenc_frame->input_surface = nvenc_frame->in_map.mappedResource;
1424 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1426 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1427 lockBufferParams.inputBuffer = nvenc_frame->input_surface;
1429 nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
1430 if (nv_status != NV_ENC_SUCCESS) {
1431 return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
1434 res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
1436 nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
1437 if (nv_status != NV_ENC_SUCCESS) {
1438 return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
1445 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1446 NV_ENC_PIC_PARAMS *params)
1448 NvencContext *ctx = avctx->priv_data;
1450 switch (avctx->codec->id) {
1451 case AV_CODEC_ID_H264:
1452 params->codecPicParams.h264PicParams.sliceMode = ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1453 params->codecPicParams.h264PicParams.sliceModeData = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1455 case AV_CODEC_ID_H265:
1456 params->codecPicParams.hevcPicParams.sliceMode = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1457 params->codecPicParams.hevcPicParams.sliceModeData = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1462 static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
1464 NvencContext *ctx = avctx->priv_data;
1465 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1466 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1468 uint32_t slice_mode_data;
1469 uint32_t *slice_offsets;
1470 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1471 NVENCSTATUS nv_status;
1474 enum AVPictureType pict_type;
1476 switch (avctx->codec->id) {
1477 case AV_CODEC_ID_H264:
1478 slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1480 case AV_CODEC_ID_H265:
1481 slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1484 av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
1485 res = AVERROR(EINVAL);
1488 slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
1491 return AVERROR(ENOMEM);
1493 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1495 lock_params.doNotWait = 0;
1496 lock_params.outputBitstream = tmpoutsurf->output_surface;
1497 lock_params.sliceOffsets = slice_offsets;
1499 nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
1500 if (nv_status != NV_ENC_SUCCESS) {
1501 res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
1505 if (res = ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes,0)) {
1506 p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1510 memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1512 nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1513 if (nv_status != NV_ENC_SUCCESS)
1514 nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
1517 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1518 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, tmpoutsurf->in_map.mappedResource);
1519 av_frame_unref(tmpoutsurf->in_ref);
1520 ctx->registered_frames[tmpoutsurf->reg_idx].mapped = 0;
1522 tmpoutsurf->input_surface = NULL;
1525 switch (lock_params.pictureType) {
1526 case NV_ENC_PIC_TYPE_IDR:
1527 pkt->flags |= AV_PKT_FLAG_KEY;
1528 case NV_ENC_PIC_TYPE_I:
1529 pict_type = AV_PICTURE_TYPE_I;
1531 case NV_ENC_PIC_TYPE_P:
1532 pict_type = AV_PICTURE_TYPE_P;
1534 case NV_ENC_PIC_TYPE_B:
1535 pict_type = AV_PICTURE_TYPE_B;
1537 case NV_ENC_PIC_TYPE_BI:
1538 pict_type = AV_PICTURE_TYPE_BI;
1541 av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
1542 av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
1543 res = AVERROR_EXTERNAL;
1547 #if FF_API_CODED_FRAME
1548 FF_DISABLE_DEPRECATION_WARNINGS
1549 avctx->coded_frame->pict_type = pict_type;
1550 FF_ENABLE_DEPRECATION_WARNINGS
1553 ff_side_data_set_encoder_stats(pkt,
1554 (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
1556 pkt->pts = lock_params.outputTimeStamp;
1557 pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
1559 /* when there're b frame(s), set dts offset */
1560 if (ctx->encode_config.frameIntervalP >= 2)
1563 if (pkt->dts > pkt->pts)
1564 pkt->dts = pkt->pts;
1566 if (ctx->last_dts != AV_NOPTS_VALUE && pkt->dts <= ctx->last_dts)
1567 pkt->dts = ctx->last_dts + 1;
1569 ctx->last_dts = pkt->dts;
1571 av_free(slice_offsets);
1577 av_free(slice_offsets);
1578 timestamp_queue_dequeue(ctx->timestamp_list);
1583 static int output_ready(NvencContext *ctx, int flush)
1585 int nb_ready, nb_pending;
1587 nb_ready = av_fifo_size(ctx->output_surface_ready_queue) / sizeof(NvencSurface*);
1588 nb_pending = av_fifo_size(ctx->output_surface_queue) / sizeof(NvencSurface*);
1589 return nb_ready > 0 && (flush || nb_ready + nb_pending >= ctx->buffer_delay);
1592 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1593 const AVFrame *frame, int *got_packet)
1595 NVENCSTATUS nv_status;
1596 NvencSurface *tmpoutsurf, *inSurf;
1599 NvencContext *ctx = avctx->priv_data;
1600 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1601 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1603 NV_ENC_PIC_PARAMS pic_params = { 0 };
1604 pic_params.version = NV_ENC_PIC_PARAMS_VER;
1607 inSurf = get_free_frame(ctx);
1610 res = nvenc_upload_frame(avctx, frame, inSurf);
1612 inSurf->lockCount = 0;
1616 pic_params.inputBuffer = inSurf->input_surface;
1617 pic_params.bufferFmt = inSurf->format;
1618 pic_params.inputWidth = avctx->width;
1619 pic_params.inputHeight = avctx->height;
1620 pic_params.outputBitstream = inSurf->output_surface;
1621 pic_params.completionEvent = 0;
1623 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1624 if (frame->top_field_first) {
1625 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
1627 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
1630 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1633 pic_params.encodePicFlags = 0;
1634 pic_params.inputTimeStamp = frame->pts;
1635 pic_params.inputDuration = 0;
1637 nvenc_codec_specific_pic_params(avctx, &pic_params);
1639 timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
1641 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1644 nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
1646 if (frame && nv_status == NV_ENC_ERR_NEED_MORE_INPUT)
1647 av_fifo_generic_write(ctx->output_surface_queue, &inSurf, sizeof(inSurf), NULL);
1649 if (nv_status != NV_ENC_SUCCESS && nv_status != NV_ENC_ERR_NEED_MORE_INPUT) {
1650 return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
1653 if (nv_status != NV_ENC_ERR_NEED_MORE_INPUT) {
1654 while (av_fifo_size(ctx->output_surface_queue) > 0) {
1655 av_fifo_generic_read(ctx->output_surface_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
1656 av_fifo_generic_write(ctx->output_surface_ready_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
1660 av_fifo_generic_write(ctx->output_surface_ready_queue, &inSurf, sizeof(inSurf), NULL);
1663 if (output_ready(ctx, !frame)) {
1664 av_fifo_generic_read(ctx->output_surface_ready_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
1666 res = process_output_surface(avctx, pkt, tmpoutsurf);
1671 av_assert0(tmpoutsurf->lockCount);
1672 tmpoutsurf->lockCount--;