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;
74 { NV_ENC_SUCCESS, 0, "success" },
75 { NV_ENC_ERR_NO_ENCODE_DEVICE, AVERROR(ENOENT), "no encode device" },
76 { NV_ENC_ERR_UNSUPPORTED_DEVICE, AVERROR(ENOSYS), "unsupported device" },
77 { NV_ENC_ERR_INVALID_ENCODERDEVICE, AVERROR(EINVAL), "invalid encoder device" },
78 { NV_ENC_ERR_INVALID_DEVICE, AVERROR(EINVAL), "invalid device" },
79 { NV_ENC_ERR_DEVICE_NOT_EXIST, AVERROR(EIO), "device does not exist" },
80 { NV_ENC_ERR_INVALID_PTR, AVERROR(EFAULT), "invalid ptr" },
81 { NV_ENC_ERR_INVALID_EVENT, AVERROR(EINVAL), "invalid event" },
82 { NV_ENC_ERR_INVALID_PARAM, AVERROR(EINVAL), "invalid param" },
83 { NV_ENC_ERR_INVALID_CALL, AVERROR(EINVAL), "invalid call" },
84 { NV_ENC_ERR_OUT_OF_MEMORY, AVERROR(ENOMEM), "out of memory" },
85 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED, AVERROR(EINVAL), "encoder not initialized" },
86 { NV_ENC_ERR_UNSUPPORTED_PARAM, AVERROR(ENOSYS), "unsupported param" },
87 { NV_ENC_ERR_LOCK_BUSY, AVERROR(EAGAIN), "lock busy" },
88 { NV_ENC_ERR_NOT_ENOUGH_BUFFER, AVERROR(ENOBUFS), "not enough buffer" },
89 { NV_ENC_ERR_INVALID_VERSION, AVERROR(EINVAL), "invalid version" },
90 { NV_ENC_ERR_MAP_FAILED, AVERROR(EIO), "map failed" },
91 { NV_ENC_ERR_NEED_MORE_INPUT, AVERROR(EAGAIN), "need more input" },
92 { NV_ENC_ERR_ENCODER_BUSY, AVERROR(EAGAIN), "encoder busy" },
93 { NV_ENC_ERR_EVENT_NOT_REGISTERD, AVERROR(EBADF), "event not registered" },
94 { NV_ENC_ERR_GENERIC, AVERROR_UNKNOWN, "generic error" },
95 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY, AVERROR(EINVAL), "incompatible client key" },
96 { NV_ENC_ERR_UNIMPLEMENTED, AVERROR(ENOSYS), "unimplemented" },
97 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO), "resource register failed" },
98 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED, AVERROR(EBADF), "resource not registered" },
99 { NV_ENC_ERR_RESOURCE_NOT_MAPPED, AVERROR(EBADF), "resource not mapped" },
102 static int nvenc_map_error(NVENCSTATUS err, const char **desc)
105 for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
106 if (nvenc_errors[i].nverr == err) {
108 *desc = nvenc_errors[i].desc;
109 return nvenc_errors[i].averr;
113 *desc = "unknown error";
114 return AVERROR_UNKNOWN;
117 static int nvenc_print_error(void *log_ctx, NVENCSTATUS err,
118 const char *error_string)
122 ret = nvenc_map_error(err, &desc);
123 av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
127 static void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
129 av_fifo_generic_write(queue, ×tamp, sizeof(timestamp), NULL);
132 static int64_t timestamp_queue_dequeue(AVFifoBuffer* queue)
134 int64_t timestamp = AV_NOPTS_VALUE;
135 if (av_fifo_size(queue) > 0)
136 av_fifo_generic_read(queue, ×tamp, sizeof(timestamp), NULL);
141 #define CHECK_LOAD_FUNC(t, f, s) \
143 (f) = (t)LOAD_FUNC(dl_fn->cuda_lib, s); \
145 av_log(avctx, AV_LOG_FATAL, "Failed loading %s from CUDA library\n", s); \
150 static av_cold int nvenc_dyload_cuda(AVCodecContext *avctx)
152 NvencContext *ctx = avctx->priv_data;
153 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
156 dl_fn->cu_init = cuInit;
157 dl_fn->cu_device_get_count = cuDeviceGetCount;
158 dl_fn->cu_device_get = cuDeviceGet;
159 dl_fn->cu_device_get_name = cuDeviceGetName;
160 dl_fn->cu_device_compute_capability = cuDeviceComputeCapability;
161 dl_fn->cu_ctx_create = cuCtxCreate_v2;
162 dl_fn->cu_ctx_pop_current = cuCtxPopCurrent_v2;
163 dl_fn->cu_ctx_destroy = cuCtxDestroy_v2;
171 dl_fn->cuda_lib = LoadLibrary(TEXT("nvcuda.dll"));
173 dl_fn->cuda_lib = dlopen("libcuda.so", RTLD_LAZY);
176 if (!dl_fn->cuda_lib) {
177 av_log(avctx, AV_LOG_FATAL, "Failed loading CUDA library\n");
181 CHECK_LOAD_FUNC(PCUINIT, dl_fn->cu_init, "cuInit");
182 CHECK_LOAD_FUNC(PCUDEVICEGETCOUNT, dl_fn->cu_device_get_count, "cuDeviceGetCount");
183 CHECK_LOAD_FUNC(PCUDEVICEGET, dl_fn->cu_device_get, "cuDeviceGet");
184 CHECK_LOAD_FUNC(PCUDEVICEGETNAME, dl_fn->cu_device_get_name, "cuDeviceGetName");
185 CHECK_LOAD_FUNC(PCUDEVICECOMPUTECAPABILITY, dl_fn->cu_device_compute_capability, "cuDeviceComputeCapability");
186 CHECK_LOAD_FUNC(PCUCTXCREATE, dl_fn->cu_ctx_create, "cuCtxCreate_v2");
187 CHECK_LOAD_FUNC(PCUCTXPOPCURRENT, dl_fn->cu_ctx_pop_current, "cuCtxPopCurrent_v2");
188 CHECK_LOAD_FUNC(PCUCTXDESTROY, dl_fn->cu_ctx_destroy, "cuCtxDestroy_v2");
195 DL_CLOSE_FUNC(dl_fn->cuda_lib);
197 dl_fn->cuda_lib = NULL;
203 static av_cold int check_cuda_errors(AVCodecContext *avctx, CUresult err, const char *func)
205 if (err != CUDA_SUCCESS) {
206 av_log(avctx, AV_LOG_FATAL, ">> %s - failed with error code 0x%x\n", func, err);
211 #define check_cuda_errors(f) if (!check_cuda_errors(avctx, f, #f)) goto error
213 static av_cold int nvenc_check_cuda(AVCodecContext *avctx)
215 int device_count = 0;
216 CUdevice cu_device = 0;
218 int smminor = 0, smmajor = 0;
219 int i, smver, target_smver;
221 NvencContext *ctx = avctx->priv_data;
222 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
224 switch (avctx->codec->id) {
225 case AV_CODEC_ID_H264:
226 target_smver = ctx->data_pix_fmt == AV_PIX_FMT_YUV444P ? 0x52 : 0x30;
228 case AV_CODEC_ID_H265:
232 av_log(avctx, AV_LOG_FATAL, "Unknown codec name\n");
236 if (ctx->preset >= PRESET_LOSSLESS_DEFAULT)
239 if (!nvenc_dyload_cuda(avctx))
242 if (dl_fn->nvenc_device_count > 0)
245 check_cuda_errors(dl_fn->cu_init(0));
247 check_cuda_errors(dl_fn->cu_device_get_count(&device_count));
250 av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
254 av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", device_count);
256 dl_fn->nvenc_device_count = 0;
258 for (i = 0; i < device_count; ++i) {
259 check_cuda_errors(dl_fn->cu_device_get(&cu_device, i));
260 check_cuda_errors(dl_fn->cu_device_get_name(gpu_name, sizeof(gpu_name), cu_device));
261 check_cuda_errors(dl_fn->cu_device_compute_capability(&smmajor, &smminor, cu_device));
263 smver = (smmajor << 4) | smminor;
265 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");
267 if (smver >= target_smver)
268 dl_fn->nvenc_devices[dl_fn->nvenc_device_count++] = cu_device;
271 if (!dl_fn->nvenc_device_count) {
272 av_log(avctx, AV_LOG_FATAL, "No NVENC capable devices found\n");
280 dl_fn->nvenc_device_count = 0;
285 static av_cold int nvenc_dyload_nvenc(AVCodecContext *avctx)
287 PNVENCODEAPICREATEINSTANCE nvEncodeAPICreateInstance = 0;
288 NVENCSTATUS nvstatus;
290 NvencContext *ctx = avctx->priv_data;
291 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
293 if (!nvenc_check_cuda(avctx))
296 if (dl_fn->nvenc_lib)
300 if (sizeof(void*) == 8) {
301 dl_fn->nvenc_lib = LoadLibrary(TEXT("nvEncodeAPI64.dll"));
303 dl_fn->nvenc_lib = LoadLibrary(TEXT("nvEncodeAPI.dll"));
306 dl_fn->nvenc_lib = dlopen("libnvidia-encode.so.1", RTLD_LAZY);
309 if (!dl_fn->nvenc_lib) {
310 av_log(avctx, AV_LOG_FATAL, "Failed loading the nvenc library\n");
314 nvEncodeAPICreateInstance = (PNVENCODEAPICREATEINSTANCE)LOAD_FUNC(dl_fn->nvenc_lib, "NvEncodeAPICreateInstance");
316 if (!nvEncodeAPICreateInstance) {
317 av_log(avctx, AV_LOG_FATAL, "Failed to load nvenc entrypoint\n");
321 dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
323 nvstatus = nvEncodeAPICreateInstance(&dl_fn->nvenc_funcs);
325 if (nvstatus != NV_ENC_SUCCESS) {
326 nvenc_print_error(avctx, nvstatus, "Failed to create nvenc instance");
330 av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
335 if (dl_fn->nvenc_lib)
336 DL_CLOSE_FUNC(dl_fn->nvenc_lib);
338 dl_fn->nvenc_lib = NULL;
343 static av_cold void nvenc_unload_nvenc(AVCodecContext *avctx)
345 NvencContext *ctx = avctx->priv_data;
346 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
348 DL_CLOSE_FUNC(dl_fn->nvenc_lib);
349 dl_fn->nvenc_lib = NULL;
351 dl_fn->nvenc_device_count = 0;
354 DL_CLOSE_FUNC(dl_fn->cuda_lib);
355 dl_fn->cuda_lib = NULL;
358 dl_fn->cu_init = NULL;
359 dl_fn->cu_device_get_count = NULL;
360 dl_fn->cu_device_get = NULL;
361 dl_fn->cu_device_get_name = NULL;
362 dl_fn->cu_device_compute_capability = NULL;
363 dl_fn->cu_ctx_create = NULL;
364 dl_fn->cu_ctx_pop_current = NULL;
365 dl_fn->cu_ctx_destroy = NULL;
367 av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
370 static av_cold int nvenc_setup_device(AVCodecContext *avctx)
372 NvencContext *ctx = avctx->priv_data;
373 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
376 CUcontext cu_context_curr;
378 switch (avctx->codec->id) {
379 case AV_CODEC_ID_H264:
380 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
382 case AV_CODEC_ID_HEVC:
383 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
389 ctx->data_pix_fmt = avctx->pix_fmt;
392 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
393 AVHWFramesContext *frames_ctx;
394 AVCUDADeviceContext *device_hwctx;
396 if (!avctx->hw_frames_ctx) {
397 av_log(avctx, AV_LOG_ERROR, "hw_frames_ctx must be set when using GPU frames as input\n");
398 return AVERROR(EINVAL);
401 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
402 device_hwctx = frames_ctx->device_ctx->hwctx;
403 ctx->cu_context = device_hwctx->cuda_ctx;
404 ctx->data_pix_fmt = frames_ctx->sw_format;
409 if (ctx->gpu >= dl_fn->nvenc_device_count) {
410 av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->gpu, dl_fn->nvenc_device_count);
411 return AVERROR(EINVAL);
414 ctx->cu_context = NULL;
415 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
417 if (cu_res != CUDA_SUCCESS) {
418 av_log(avctx, AV_LOG_FATAL, "Failed creating CUDA context for NVENC: 0x%x\n", (int)cu_res);
419 return AVERROR_EXTERNAL;
422 cu_res = dl_fn->cu_ctx_pop_current(&cu_context_curr);
424 if (cu_res != CUDA_SUCCESS) {
425 av_log(avctx, AV_LOG_FATAL, "Failed popping CUDA context: 0x%x\n", (int)cu_res);
426 return AVERROR_EXTERNAL;
429 ctx->cu_context = ctx->cu_context_internal;
434 static av_cold int nvenc_open_session(AVCodecContext *avctx)
436 NvencContext *ctx = avctx->priv_data;
437 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
438 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
440 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS encode_session_params = { 0 };
441 NVENCSTATUS nv_status;
443 encode_session_params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
444 encode_session_params.apiVersion = NVENCAPI_VERSION;
445 encode_session_params.device = ctx->cu_context;
446 encode_session_params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
448 nv_status = p_nvenc->nvEncOpenEncodeSessionEx(&encode_session_params, &ctx->nvencoder);
449 if (nv_status != NV_ENC_SUCCESS) {
450 ctx->nvencoder = NULL;
451 return nvenc_print_error(avctx, nv_status, "OpenEncodeSessionEx failed");
457 typedef struct GUIDTuple {
462 static void nvenc_map_preset(NvencContext *ctx)
464 GUIDTuple presets[] = {
465 { NV_ENC_PRESET_DEFAULT_GUID },
466 { NV_ENC_PRESET_HQ_GUID, NVENC_TWO_PASSES }, /* slow */
467 { NV_ENC_PRESET_HQ_GUID, NVENC_ONE_PASS }, /* medium */
468 { NV_ENC_PRESET_HP_GUID, NVENC_ONE_PASS }, /* fast */
469 { NV_ENC_PRESET_HP_GUID },
470 { NV_ENC_PRESET_HQ_GUID },
471 { NV_ENC_PRESET_BD_GUID },
472 { NV_ENC_PRESET_LOW_LATENCY_DEFAULT_GUID, NVENC_LOWLATENCY },
473 { NV_ENC_PRESET_LOW_LATENCY_HQ_GUID, NVENC_LOWLATENCY },
474 { NV_ENC_PRESET_LOW_LATENCY_HP_GUID, NVENC_LOWLATENCY },
475 { NV_ENC_PRESET_LOSSLESS_DEFAULT_GUID, NVENC_LOSSLESS },
476 { NV_ENC_PRESET_LOSSLESS_HP_GUID, NVENC_LOSSLESS },
479 GUIDTuple *t = &presets[ctx->preset];
481 ctx->init_encode_params.presetGUID = t->guid;
482 ctx->flags = t->flags;
485 static av_cold void set_constqp(AVCodecContext *avctx)
487 NvencContext *ctx = avctx->priv_data;
489 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
490 ctx->encode_config.rcParams.constQP.qpInterB = avctx->global_quality;
491 ctx->encode_config.rcParams.constQP.qpInterP = avctx->global_quality;
492 ctx->encode_config.rcParams.constQP.qpIntra = avctx->global_quality;
495 static av_cold void set_vbr(AVCodecContext *avctx)
497 NvencContext *ctx = avctx->priv_data;
499 ctx->encode_config.rcParams.enableMinQP = 1;
500 ctx->encode_config.rcParams.enableMaxQP = 1;
502 ctx->encode_config.rcParams.minQP.qpInterB = avctx->qmin;
503 ctx->encode_config.rcParams.minQP.qpInterP = avctx->qmin;
504 ctx->encode_config.rcParams.minQP.qpIntra = avctx->qmin;
506 ctx->encode_config.rcParams.maxQP.qpInterB = avctx->qmax;
507 ctx->encode_config.rcParams.maxQP.qpInterP = avctx->qmax;
508 ctx->encode_config.rcParams.maxQP.qpIntra = avctx->qmax;
511 static av_cold void set_lossless(AVCodecContext *avctx)
513 NvencContext *ctx = avctx->priv_data;
515 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
516 ctx->encode_config.rcParams.constQP.qpInterB = 0;
517 ctx->encode_config.rcParams.constQP.qpInterP = 0;
518 ctx->encode_config.rcParams.constQP.qpIntra = 0;
521 static av_cold void nvenc_setup_rate_control(AVCodecContext *avctx)
523 NvencContext *ctx = avctx->priv_data;
527 if (avctx->bit_rate > 0) {
528 ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
529 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
530 ctx->encode_config.rcParams.maxBitRate = ctx->encode_config.rcParams.averageBitRate;
533 if (avctx->rc_max_rate > 0)
534 ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
536 if (ctx->flags & NVENC_LOSSLESS) {
541 } else if (ctx->cbr) {
543 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CBR;
545 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_2_PASS_QUALITY;
547 if (avctx->codec->id == AV_CODEC_ID_H264) {
548 ctx->encode_config.encodeCodecConfig.h264Config.adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
549 ctx->encode_config.encodeCodecConfig.h264Config.fmoMode = NV_ENC_H264_FMO_DISABLE;
553 if (avctx->codec->id == AV_CODEC_ID_H264) {
554 ctx->encode_config.encodeCodecConfig.h264Config.outputBufferingPeriodSEI = 1;
555 ctx->encode_config.encodeCodecConfig.h264Config.outputPictureTimingSEI = 1;
556 } else if (avctx->codec->id == AV_CODEC_ID_H265) {
557 ctx->encode_config.encodeCodecConfig.hevcConfig.outputBufferingPeriodSEI = 1;
558 ctx->encode_config.encodeCodecConfig.hevcConfig.outputPictureTimingSEI = 1;
560 } else if (avctx->global_quality > 0) {
566 if (avctx->qmin >= 0 && avctx->qmax >= 0) {
569 qp_inter_p = (avctx->qmax + 3 * avctx->qmin) / 4; // biased towards Qmin
572 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_2_PASS_VBR;
573 if (avctx->codec->id == AV_CODEC_ID_H264) {
574 ctx->encode_config.encodeCodecConfig.h264Config.adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
575 ctx->encode_config.encodeCodecConfig.h264Config.fmoMode = NV_ENC_H264_FMO_DISABLE;
578 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR_MINQP;
581 qp_inter_p = 26; // default to 26
584 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_2_PASS_VBR;
586 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
590 ctx->encode_config.rcParams.enableInitialRCQP = 1;
591 ctx->encode_config.rcParams.initialRCQP.qpInterP = qp_inter_p;
593 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
594 ctx->encode_config.rcParams.initialRCQP.qpIntra = av_clip(
595 qp_inter_p * fabs(avctx->i_quant_factor) + avctx->i_quant_offset, 0, 51);
596 ctx->encode_config.rcParams.initialRCQP.qpInterB = av_clip(
597 qp_inter_p * fabs(avctx->b_quant_factor) + avctx->b_quant_offset, 0, 51);
599 ctx->encode_config.rcParams.initialRCQP.qpIntra = qp_inter_p;
600 ctx->encode_config.rcParams.initialRCQP.qpInterB = qp_inter_p;
604 if (avctx->rc_buffer_size > 0) {
605 ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
606 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
607 ctx->encode_config.rcParams.vbvBufferSize = 2 * ctx->encode_config.rcParams.averageBitRate;
611 static av_cold int nvenc_setup_h264_config(AVCodecContext *avctx)
613 NvencContext *ctx = avctx->priv_data;
614 NV_ENC_CONFIG *cc = &ctx->encode_config;
615 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
616 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
618 vui->colourMatrix = avctx->colorspace;
619 vui->colourPrimaries = avctx->color_primaries;
620 vui->transferCharacteristics = avctx->color_trc;
621 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
622 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
624 vui->colourDescriptionPresentFlag =
625 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
627 vui->videoSignalTypePresentFlag =
628 (vui->colourDescriptionPresentFlag
629 || vui->videoFormat != 5
630 || vui->videoFullRangeFlag != 0);
633 h264->sliceModeData = 1;
635 h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
636 h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
640 if (ctx->flags & NVENC_LOSSLESS) {
641 h264->qpPrimeYZeroTransformBypassFlag = 1;
643 switch(ctx->profile) {
644 case NV_ENC_H264_PROFILE_BASELINE:
645 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
646 avctx->profile = FF_PROFILE_H264_BASELINE;
648 case NV_ENC_H264_PROFILE_MAIN:
649 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
650 avctx->profile = FF_PROFILE_H264_MAIN;
652 case NV_ENC_H264_PROFILE_HIGH:
653 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
654 avctx->profile = FF_PROFILE_H264_HIGH;
656 case NV_ENC_H264_PROFILE_HIGH_444P:
657 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
658 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
663 // force setting profile as high444p if input is AV_PIX_FMT_YUV444P
664 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P) {
665 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
666 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
669 h264->chromaFormatIDC = avctx->profile == FF_PROFILE_H264_HIGH_444_PREDICTIVE ? 3 : 1;
671 h264->level = ctx->level;
676 static av_cold int nvenc_setup_hevc_config(AVCodecContext *avctx)
678 NvencContext *ctx = avctx->priv_data;
679 NV_ENC_CONFIG *cc = &ctx->encode_config;
680 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
681 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
683 vui->colourMatrix = avctx->colorspace;
684 vui->colourPrimaries = avctx->color_primaries;
685 vui->transferCharacteristics = avctx->color_trc;
686 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
687 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
689 vui->colourDescriptionPresentFlag =
690 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
692 vui->videoSignalTypePresentFlag =
693 (vui->colourDescriptionPresentFlag
694 || vui->videoFormat != 5
695 || vui->videoFullRangeFlag != 0);
698 hevc->sliceModeData = 1;
700 hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
701 hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
705 /* No other profile is supported in the current SDK version 5 */
706 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
707 avctx->profile = FF_PROFILE_HEVC_MAIN;
709 hevc->level = ctx->level;
711 hevc->tier = ctx->tier;
716 static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx)
718 switch (avctx->codec->id) {
719 case AV_CODEC_ID_H264:
720 return nvenc_setup_h264_config(avctx);
721 case AV_CODEC_ID_HEVC:
722 return nvenc_setup_hevc_config(avctx);
723 /* Earlier switch/case will return if unknown codec is passed. */
729 static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
731 NvencContext *ctx = avctx->priv_data;
732 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
733 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
735 NV_ENC_PRESET_CONFIG preset_config = { 0 };
736 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
737 AVCPBProperties *cpb_props;
742 ctx->last_dts = AV_NOPTS_VALUE;
744 ctx->encode_config.version = NV_ENC_CONFIG_VER;
745 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
747 ctx->init_encode_params.encodeHeight = avctx->height;
748 ctx->init_encode_params.encodeWidth = avctx->width;
750 ctx->init_encode_params.encodeConfig = &ctx->encode_config;
752 nvenc_map_preset(ctx);
754 if (ctx->flags & NVENC_ONE_PASS)
756 if (ctx->flags & NVENC_TWO_PASSES)
759 if (ctx->twopass < 0) {
760 ctx->twopass = (ctx->flags & NVENC_LOWLATENCY) != 0;
763 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
764 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
766 nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder,
767 ctx->init_encode_params.encodeGUID,
768 ctx->init_encode_params.presetGUID,
770 if (nv_status != NV_ENC_SUCCESS)
771 return nvenc_print_error(avctx, nv_status, "Cannot get the preset configuration");
773 memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
775 ctx->encode_config.version = NV_ENC_CONFIG_VER;
777 if (avctx->sample_aspect_ratio.num && avctx->sample_aspect_ratio.den &&
778 (avctx->sample_aspect_ratio.num != 1 || avctx->sample_aspect_ratio.num != 1)) {
780 avctx->width * avctx->sample_aspect_ratio.num,
781 avctx->height * avctx->sample_aspect_ratio.den,
783 ctx->init_encode_params.darHeight = dh;
784 ctx->init_encode_params.darWidth = dw;
786 ctx->init_encode_params.darHeight = avctx->height;
787 ctx->init_encode_params.darWidth = avctx->width;
790 // De-compensate for hardware, dubiously, trying to compensate for
791 // playback at 704 pixel width.
792 if (avctx->width == 720 &&
793 (avctx->height == 480 || avctx->height == 576)) {
795 ctx->init_encode_params.darWidth * 44,
796 ctx->init_encode_params.darHeight * 45,
798 ctx->init_encode_params.darHeight = dh;
799 ctx->init_encode_params.darWidth = dw;
802 ctx->init_encode_params.frameRateNum = avctx->time_base.den;
803 ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
805 num_mbs = ((avctx->width + 15) >> 4) * ((avctx->height + 15) >> 4);
806 ctx->max_surface_count = (num_mbs >= 8160) ? 32 : 48;
808 if (ctx->buffer_delay >= ctx->max_surface_count)
809 ctx->buffer_delay = ctx->max_surface_count - 1;
811 ctx->init_encode_params.enableEncodeAsync = 0;
812 ctx->init_encode_params.enablePTD = 1;
814 if (avctx->refs >= 0) {
815 /* 0 means "let the hardware decide" */
816 switch (avctx->codec->id) {
817 case AV_CODEC_ID_H264:
818 ctx->encode_config.encodeCodecConfig.h264Config.maxNumRefFrames = avctx->refs;
820 case AV_CODEC_ID_H265:
821 ctx->encode_config.encodeCodecConfig.hevcConfig.maxNumRefFramesInDPB = avctx->refs;
823 /* Earlier switch/case will return if unknown codec is passed. */
827 if (avctx->gop_size > 0) {
828 if (avctx->max_b_frames >= 0) {
829 /* 0 is intra-only, 1 is I/P only, 2 is one B Frame, 3 two B frames, and so on. */
830 ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
833 ctx->encode_config.gopLength = avctx->gop_size;
834 switch (avctx->codec->id) {
835 case AV_CODEC_ID_H264:
836 ctx->encode_config.encodeCodecConfig.h264Config.idrPeriod = avctx->gop_size;
838 case AV_CODEC_ID_H265:
839 ctx->encode_config.encodeCodecConfig.hevcConfig.idrPeriod = avctx->gop_size;
841 /* Earlier switch/case will return if unknown codec is passed. */
843 } else if (avctx->gop_size == 0) {
844 ctx->encode_config.frameIntervalP = 0;
845 ctx->encode_config.gopLength = 1;
846 switch (avctx->codec->id) {
847 case AV_CODEC_ID_H264:
848 ctx->encode_config.encodeCodecConfig.h264Config.idrPeriod = 1;
850 case AV_CODEC_ID_H265:
851 ctx->encode_config.encodeCodecConfig.hevcConfig.idrPeriod = 1;
853 /* Earlier switch/case will return if unknown codec is passed. */
857 /* when there're b frames, set dts offset */
858 if (ctx->encode_config.frameIntervalP >= 2)
861 nvenc_setup_rate_control(avctx);
863 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
864 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
866 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
869 res = nvenc_setup_codec_config(avctx);
873 nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
874 if (nv_status != NV_ENC_SUCCESS) {
875 return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
878 if (ctx->encode_config.frameIntervalP > 1)
879 avctx->has_b_frames = 2;
881 if (ctx->encode_config.rcParams.averageBitRate > 0)
882 avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
884 cpb_props = ff_add_cpb_side_data(avctx);
886 return AVERROR(ENOMEM);
887 cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
888 cpb_props->avg_bitrate = avctx->bit_rate;
889 cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
894 static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
896 NvencContext *ctx = avctx->priv_data;
897 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
898 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
900 NVENCSTATUS nv_status;
901 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
902 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
904 switch (ctx->data_pix_fmt) {
905 case AV_PIX_FMT_YUV420P:
906 ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_YV12_PL;
909 case AV_PIX_FMT_NV12:
910 ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_NV12_PL;
913 case AV_PIX_FMT_YUV444P:
914 ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_YUV444_PL;
918 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format\n");
919 return AVERROR(EINVAL);
922 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
923 ctx->surfaces[idx].in_ref = av_frame_alloc();
924 if (!ctx->surfaces[idx].in_ref)
925 return AVERROR(ENOMEM);
927 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
928 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
929 allocSurf.width = (avctx->width + 31) & ~31;
930 allocSurf.height = (avctx->height + 31) & ~31;
931 allocSurf.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
932 allocSurf.bufferFmt = ctx->surfaces[idx].format;
934 nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
935 if (nv_status != NV_ENC_SUCCESS) {
936 return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
939 ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
940 ctx->surfaces[idx].width = allocSurf.width;
941 ctx->surfaces[idx].height = allocSurf.height;
944 ctx->surfaces[idx].lockCount = 0;
946 /* 1MB is large enough to hold most output frames. NVENC increases this automaticaly if it's not enough. */
947 allocOut.size = 1024 * 1024;
949 allocOut.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
951 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
952 if (nv_status != NV_ENC_SUCCESS) {
953 int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
954 if (avctx->pix_fmt != AV_PIX_FMT_CUDA)
955 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
956 av_frame_free(&ctx->surfaces[idx].in_ref);
960 ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
961 ctx->surfaces[idx].size = allocOut.size;
966 static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx, int* surfaceCount)
969 NvencContext *ctx = avctx->priv_data;
971 ctx->surfaces = av_malloc(ctx->max_surface_count * sizeof(*ctx->surfaces));
973 if (!ctx->surfaces) {
974 return AVERROR(ENOMEM);
977 ctx->timestamp_list = av_fifo_alloc(ctx->max_surface_count * sizeof(int64_t));
978 if (!ctx->timestamp_list)
979 return AVERROR(ENOMEM);
980 ctx->output_surface_queue = av_fifo_alloc(ctx->max_surface_count * sizeof(NvencSurface*));
981 if (!ctx->output_surface_queue)
982 return AVERROR(ENOMEM);
983 ctx->output_surface_ready_queue = av_fifo_alloc(ctx->max_surface_count * sizeof(NvencSurface*));
984 if (!ctx->output_surface_ready_queue)
985 return AVERROR(ENOMEM);
987 for (*surfaceCount = 0; *surfaceCount < ctx->max_surface_count; ++*surfaceCount) {
988 res = nvenc_alloc_surface(avctx, *surfaceCount);
996 static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
998 NvencContext *ctx = avctx->priv_data;
999 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1000 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1002 NVENCSTATUS nv_status;
1003 uint32_t outSize = 0;
1004 char tmpHeader[256];
1005 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1006 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1008 payload.spsppsBuffer = tmpHeader;
1009 payload.inBufferSize = sizeof(tmpHeader);
1010 payload.outSPSPPSPayloadSize = &outSize;
1012 nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
1013 if (nv_status != NV_ENC_SUCCESS) {
1014 return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
1017 avctx->extradata_size = outSize;
1018 avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
1020 if (!avctx->extradata) {
1021 return AVERROR(ENOMEM);
1024 memcpy(avctx->extradata, tmpHeader, outSize);
1029 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
1031 NvencContext *ctx = avctx->priv_data;
1032 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1033 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1037 int surfaceCount = 0;
1039 if (!nvenc_dyload_nvenc(avctx))
1040 return AVERROR_EXTERNAL;
1042 res = nvenc_setup_device(avctx);
1046 res = nvenc_open_session(avctx);
1050 res = nvenc_setup_encoder(avctx);
1054 res = nvenc_setup_surfaces(avctx, &surfaceCount);
1058 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1059 res = nvenc_setup_extradata(avctx);
1067 av_fifo_freep(&ctx->timestamp_list);
1068 av_fifo_freep(&ctx->output_surface_ready_queue);
1069 av_fifo_freep(&ctx->output_surface_queue);
1071 for (i = 0; i < surfaceCount; ++i) {
1072 if (avctx->pix_fmt != AV_PIX_FMT_CUDA)
1073 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
1074 av_frame_free(&ctx->surfaces[i].in_ref);
1075 p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
1077 av_freep(&ctx->surfaces);
1080 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1081 ctx->nvencoder = NULL;
1083 if (ctx->cu_context_internal)
1084 dl_fn->cu_ctx_destroy(ctx->cu_context_internal);
1085 ctx->cu_context = ctx->cu_context_internal = NULL;
1087 nvenc_unload_nvenc(avctx);
1092 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
1094 NvencContext *ctx = avctx->priv_data;
1095 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1096 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1099 av_fifo_freep(&ctx->timestamp_list);
1100 av_fifo_freep(&ctx->output_surface_ready_queue);
1101 av_fifo_freep(&ctx->output_surface_queue);
1103 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1104 for (i = 0; i < ctx->max_surface_count; ++i) {
1105 if (ctx->surfaces[i].input_surface) {
1106 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->surfaces[i].in_map.mappedResource);
1109 for (i = 0; i < ctx->nb_registered_frames; i++) {
1110 if (ctx->registered_frames[i].regptr)
1111 p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1113 ctx->nb_registered_frames = 0;
1116 for (i = 0; i < ctx->max_surface_count; ++i) {
1117 if (avctx->pix_fmt != AV_PIX_FMT_CUDA)
1118 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
1119 av_frame_free(&ctx->surfaces[i].in_ref);
1120 p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
1122 av_freep(&ctx->surfaces);
1123 ctx->max_surface_count = 0;
1125 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1126 ctx->nvencoder = NULL;
1128 if (ctx->cu_context_internal)
1129 dl_fn->cu_ctx_destroy(ctx->cu_context_internal);
1130 ctx->cu_context = ctx->cu_context_internal = NULL;
1132 nvenc_unload_nvenc(avctx);
1137 static NvencSurface *get_free_frame(NvencContext *ctx)
1141 for (i = 0; i < ctx->max_surface_count; ++i) {
1142 if (!ctx->surfaces[i].lockCount) {
1143 ctx->surfaces[i].lockCount = 1;
1144 return &ctx->surfaces[i];
1151 static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *inSurf,
1152 NV_ENC_LOCK_INPUT_BUFFER *lockBufferParams, const AVFrame *frame)
1154 uint8_t *buf = lockBufferParams->bufferDataPtr;
1155 int off = inSurf->height * lockBufferParams->pitch;
1157 if (frame->format == AV_PIX_FMT_YUV420P) {
1158 av_image_copy_plane(buf, lockBufferParams->pitch,
1159 frame->data[0], frame->linesize[0],
1160 avctx->width, avctx->height);
1164 av_image_copy_plane(buf, lockBufferParams->pitch >> 1,
1165 frame->data[2], frame->linesize[2],
1166 avctx->width >> 1, avctx->height >> 1);
1170 av_image_copy_plane(buf, lockBufferParams->pitch >> 1,
1171 frame->data[1], frame->linesize[1],
1172 avctx->width >> 1, avctx->height >> 1);
1173 } else if (frame->format == AV_PIX_FMT_NV12) {
1174 av_image_copy_plane(buf, lockBufferParams->pitch,
1175 frame->data[0], frame->linesize[0],
1176 avctx->width, avctx->height);
1180 av_image_copy_plane(buf, lockBufferParams->pitch,
1181 frame->data[1], frame->linesize[1],
1182 avctx->width, avctx->height >> 1);
1183 } else if (frame->format == AV_PIX_FMT_YUV444P) {
1184 av_image_copy_plane(buf, lockBufferParams->pitch,
1185 frame->data[0], frame->linesize[0],
1186 avctx->width, avctx->height);
1190 av_image_copy_plane(buf, lockBufferParams->pitch,
1191 frame->data[1], frame->linesize[1],
1192 avctx->width, avctx->height);
1196 av_image_copy_plane(buf, lockBufferParams->pitch,
1197 frame->data[2], frame->linesize[2],
1198 avctx->width, avctx->height);
1200 av_log(avctx, AV_LOG_FATAL, "Invalid pixel format!\n");
1201 return AVERROR(EINVAL);
1207 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1209 NvencContext *ctx = avctx->priv_data;
1210 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1211 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1215 if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1216 for (i = 0; i < ctx->nb_registered_frames; i++) {
1217 if (!ctx->registered_frames[i].mapped) {
1218 if (ctx->registered_frames[i].regptr) {
1219 p_nvenc->nvEncUnregisterResource(ctx->nvencoder,
1220 ctx->registered_frames[i].regptr);
1221 ctx->registered_frames[i].regptr = NULL;
1227 return ctx->nb_registered_frames++;
1230 av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1231 return AVERROR(ENOMEM);
1234 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1236 NvencContext *ctx = avctx->priv_data;
1237 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1238 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1240 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1241 NV_ENC_REGISTER_RESOURCE reg;
1244 for (i = 0; i < ctx->nb_registered_frames; i++) {
1245 if (ctx->registered_frames[i].ptr == (CUdeviceptr)frame->data[0])
1249 idx = nvenc_find_free_reg_resource(avctx);
1253 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1254 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1255 reg.width = frames_ctx->width;
1256 reg.height = frames_ctx->height;
1257 reg.bufferFormat = ctx->surfaces[0].format;
1258 reg.pitch = frame->linesize[0];
1259 reg.resourceToRegister = frame->data[0];
1261 ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, ®);
1262 if (ret != NV_ENC_SUCCESS) {
1263 nvenc_print_error(avctx, ret, "Error registering an input resource");
1264 return AVERROR_UNKNOWN;
1267 ctx->registered_frames[idx].ptr = (CUdeviceptr)frame->data[0];
1268 ctx->registered_frames[idx].regptr = reg.registeredResource;
1272 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1273 NvencSurface *nvenc_frame)
1275 NvencContext *ctx = avctx->priv_data;
1276 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1277 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1280 NVENCSTATUS nv_status;
1282 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1283 int reg_idx = nvenc_register_frame(avctx, frame);
1285 av_log(avctx, AV_LOG_ERROR, "Could not register an input CUDA frame\n");
1289 res = av_frame_ref(nvenc_frame->in_ref, frame);
1293 nvenc_frame->in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1294 nvenc_frame->in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1295 nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &nvenc_frame->in_map);
1296 if (nv_status != NV_ENC_SUCCESS) {
1297 av_frame_unref(nvenc_frame->in_ref);
1298 return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
1301 ctx->registered_frames[reg_idx].mapped = 1;
1302 nvenc_frame->reg_idx = reg_idx;
1303 nvenc_frame->input_surface = nvenc_frame->in_map.mappedResource;
1306 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1308 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1309 lockBufferParams.inputBuffer = nvenc_frame->input_surface;
1311 nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
1312 if (nv_status != NV_ENC_SUCCESS) {
1313 return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
1316 res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
1318 nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
1319 if (nv_status != NV_ENC_SUCCESS) {
1320 return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
1327 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1328 NV_ENC_PIC_PARAMS *params)
1330 NvencContext *ctx = avctx->priv_data;
1332 switch (avctx->codec->id) {
1333 case AV_CODEC_ID_H264:
1334 params->codecPicParams.h264PicParams.sliceMode = ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1335 params->codecPicParams.h264PicParams.sliceModeData = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1337 case AV_CODEC_ID_H265:
1338 params->codecPicParams.hevcPicParams.sliceMode = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1339 params->codecPicParams.hevcPicParams.sliceModeData = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1344 static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
1346 NvencContext *ctx = avctx->priv_data;
1347 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1348 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1350 uint32_t slice_mode_data;
1351 uint32_t *slice_offsets;
1352 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1353 NVENCSTATUS nv_status;
1356 enum AVPictureType pict_type;
1358 switch (avctx->codec->id) {
1359 case AV_CODEC_ID_H264:
1360 slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1362 case AV_CODEC_ID_H265:
1363 slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1366 av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
1367 res = AVERROR(EINVAL);
1370 slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
1373 return AVERROR(ENOMEM);
1375 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1377 lock_params.doNotWait = 0;
1378 lock_params.outputBitstream = tmpoutsurf->output_surface;
1379 lock_params.sliceOffsets = slice_offsets;
1381 nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
1382 if (nv_status != NV_ENC_SUCCESS) {
1383 res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
1387 if (res = ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes,0)) {
1388 p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1392 memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1394 nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1395 if (nv_status != NV_ENC_SUCCESS)
1396 nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
1399 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1400 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, tmpoutsurf->in_map.mappedResource);
1401 av_frame_unref(tmpoutsurf->in_ref);
1402 ctx->registered_frames[tmpoutsurf->reg_idx].mapped = 0;
1404 tmpoutsurf->input_surface = NULL;
1407 switch (lock_params.pictureType) {
1408 case NV_ENC_PIC_TYPE_IDR:
1409 pkt->flags |= AV_PKT_FLAG_KEY;
1410 case NV_ENC_PIC_TYPE_I:
1411 pict_type = AV_PICTURE_TYPE_I;
1413 case NV_ENC_PIC_TYPE_P:
1414 pict_type = AV_PICTURE_TYPE_P;
1416 case NV_ENC_PIC_TYPE_B:
1417 pict_type = AV_PICTURE_TYPE_B;
1419 case NV_ENC_PIC_TYPE_BI:
1420 pict_type = AV_PICTURE_TYPE_BI;
1423 av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
1424 av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
1425 res = AVERROR_EXTERNAL;
1429 #if FF_API_CODED_FRAME
1430 FF_DISABLE_DEPRECATION_WARNINGS
1431 avctx->coded_frame->pict_type = pict_type;
1432 FF_ENABLE_DEPRECATION_WARNINGS
1435 ff_side_data_set_encoder_stats(pkt,
1436 (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
1438 pkt->pts = lock_params.outputTimeStamp;
1439 pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
1441 /* when there're b frame(s), set dts offset */
1442 if (ctx->encode_config.frameIntervalP >= 2)
1445 if (pkt->dts > pkt->pts)
1446 pkt->dts = pkt->pts;
1448 if (ctx->last_dts != AV_NOPTS_VALUE && pkt->dts <= ctx->last_dts)
1449 pkt->dts = ctx->last_dts + 1;
1451 ctx->last_dts = pkt->dts;
1453 av_free(slice_offsets);
1459 av_free(slice_offsets);
1460 timestamp_queue_dequeue(ctx->timestamp_list);
1465 static int output_ready(NvencContext *ctx, int flush)
1467 int nb_ready, nb_pending;
1469 nb_ready = av_fifo_size(ctx->output_surface_ready_queue) / sizeof(NvencSurface*);
1470 nb_pending = av_fifo_size(ctx->output_surface_queue) / sizeof(NvencSurface*);
1471 return nb_ready > 0 && (flush || nb_ready + nb_pending >= ctx->buffer_delay);
1474 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1475 const AVFrame *frame, int *got_packet)
1477 NVENCSTATUS nv_status;
1478 NvencSurface *tmpoutsurf, *inSurf;
1481 NvencContext *ctx = avctx->priv_data;
1482 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1483 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1485 NV_ENC_PIC_PARAMS pic_params = { 0 };
1486 pic_params.version = NV_ENC_PIC_PARAMS_VER;
1489 inSurf = get_free_frame(ctx);
1492 res = nvenc_upload_frame(avctx, frame, inSurf);
1494 inSurf->lockCount = 0;
1498 pic_params.inputBuffer = inSurf->input_surface;
1499 pic_params.bufferFmt = inSurf->format;
1500 pic_params.inputWidth = avctx->width;
1501 pic_params.inputHeight = avctx->height;
1502 pic_params.outputBitstream = inSurf->output_surface;
1503 pic_params.completionEvent = 0;
1505 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1506 if (frame->top_field_first) {
1507 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
1509 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
1512 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1515 pic_params.encodePicFlags = 0;
1516 pic_params.inputTimeStamp = frame->pts;
1517 pic_params.inputDuration = 0;
1519 nvenc_codec_specific_pic_params(avctx, &pic_params);
1521 timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
1523 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1526 nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
1528 if (frame && nv_status == NV_ENC_ERR_NEED_MORE_INPUT)
1529 av_fifo_generic_write(ctx->output_surface_queue, &inSurf, sizeof(inSurf), NULL);
1531 if (nv_status != NV_ENC_SUCCESS && nv_status != NV_ENC_ERR_NEED_MORE_INPUT) {
1532 return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
1535 if (nv_status != NV_ENC_ERR_NEED_MORE_INPUT) {
1536 while (av_fifo_size(ctx->output_surface_queue) > 0) {
1537 av_fifo_generic_read(ctx->output_surface_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
1538 av_fifo_generic_write(ctx->output_surface_ready_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
1542 av_fifo_generic_write(ctx->output_surface_ready_queue, &inSurf, sizeof(inSurf), NULL);
1545 if (output_ready(ctx, !frame)) {
1546 av_fifo_generic_read(ctx->output_surface_ready_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
1548 res = process_output_surface(avctx, pkt, tmpoutsurf);
1553 av_assert0(tmpoutsurf->lockCount);
1554 tmpoutsurf->lockCount--;