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
28 #include <nvEncodeAPI.h>
30 #include "libavutil/fifo.h"
31 #include "libavutil/internal.h"
32 #include "libavutil/imgutils.h"
33 #include "libavutil/avassert.h"
34 #include "libavutil/opt.h"
35 #include "libavutil/mem.h"
36 #include "libavutil/hwcontext.h"
44 #include "libavutil/hwcontext_cuda.h"
48 #define CUDAAPI __stdcall
53 typedef enum cudaError_enum {
57 typedef void* CUcontext;
58 typedef void* CUdeviceptr;
62 #define LOAD_FUNC(l, s) GetProcAddress(l, s)
63 #define DL_CLOSE_FUNC(l) FreeLibrary(l)
65 #define LOAD_FUNC(l, s) dlsym(l, s)
66 #define DL_CLOSE_FUNC(l) dlclose(l)
69 typedef CUresult(CUDAAPI *PCUINIT)(unsigned int Flags);
70 typedef CUresult(CUDAAPI *PCUDEVICEGETCOUNT)(int *count);
71 typedef CUresult(CUDAAPI *PCUDEVICEGET)(CUdevice *device, int ordinal);
72 typedef CUresult(CUDAAPI *PCUDEVICEGETNAME)(char *name, int len, CUdevice dev);
73 typedef CUresult(CUDAAPI *PCUDEVICECOMPUTECAPABILITY)(int *major, int *minor, CUdevice dev);
74 typedef CUresult(CUDAAPI *PCUCTXCREATE)(CUcontext *pctx, unsigned int flags, CUdevice dev);
75 typedef CUresult(CUDAAPI *PCUCTXPOPCURRENT)(CUcontext *pctx);
76 typedef CUresult(CUDAAPI *PCUCTXDESTROY)(CUcontext ctx);
78 typedef NVENCSTATUS (NVENCAPI* PNVENCODEAPICREATEINSTANCE)(NV_ENCODE_API_FUNCTION_LIST *functionList);
80 #define MAX_REGISTERED_FRAMES 64
81 typedef struct NvencSurface
83 NV_ENC_INPUT_PTR input_surface;
85 NV_ENC_MAP_INPUT_RESOURCE in_map;
92 NV_ENC_BUFFER_FORMAT format;
94 NV_ENC_OUTPUT_PTR output_surface;
98 typedef struct NvencData
102 NvencSurface *surface;
106 typedef struct NvencDynLoadFunctions
109 PCUDEVICEGETCOUNT cu_device_get_count;
110 PCUDEVICEGET cu_device_get;
111 PCUDEVICEGETNAME cu_device_get_name;
112 PCUDEVICECOMPUTECAPABILITY cu_device_compute_capability;
113 PCUCTXCREATE cu_ctx_create;
114 PCUCTXPOPCURRENT cu_ctx_pop_current;
115 PCUCTXDESTROY cu_ctx_destroy;
117 NV_ENCODE_API_FUNCTION_LIST nvenc_funcs;
118 int nvenc_device_count;
119 CUdevice nvenc_devices[16];
133 } NvencDynLoadFunctions;
135 typedef struct NvencValuePair
141 typedef struct NvencContext
145 NvencDynLoadFunctions nvenc_dload_funcs;
147 NV_ENC_INITIALIZE_PARAMS init_encode_params;
148 NV_ENC_CONFIG encode_config;
149 CUcontext cu_context;
150 CUcontext cu_context_internal;
152 int max_surface_count;
153 NvencSurface *surfaces;
155 AVFifoBuffer *output_surface_queue;
156 AVFifoBuffer *output_surface_ready_queue;
157 AVFifoBuffer *timestamp_list;
162 NV_ENC_REGISTERED_PTR regptr;
164 } registered_frames[MAX_REGISTERED_FRAMES];
165 int nb_registered_frames;
167 /* the actual data pixel format, different from
168 * AVCodecContext.pix_fmt when using hwaccel frames on input */
169 enum AVPixelFormat data_pix_fmt;
183 static const NvencValuePair nvenc_h264_level_pairs[] = {
184 { "auto", NV_ENC_LEVEL_AUTOSELECT },
185 { "1" , NV_ENC_LEVEL_H264_1 },
186 { "1.0" , NV_ENC_LEVEL_H264_1 },
187 { "1b" , NV_ENC_LEVEL_H264_1b },
188 { "1.0b", NV_ENC_LEVEL_H264_1b },
189 { "1.1" , NV_ENC_LEVEL_H264_11 },
190 { "1.2" , NV_ENC_LEVEL_H264_12 },
191 { "1.3" , NV_ENC_LEVEL_H264_13 },
192 { "2" , NV_ENC_LEVEL_H264_2 },
193 { "2.0" , NV_ENC_LEVEL_H264_2 },
194 { "2.1" , NV_ENC_LEVEL_H264_21 },
195 { "2.2" , NV_ENC_LEVEL_H264_22 },
196 { "3" , NV_ENC_LEVEL_H264_3 },
197 { "3.0" , NV_ENC_LEVEL_H264_3 },
198 { "3.1" , NV_ENC_LEVEL_H264_31 },
199 { "3.2" , NV_ENC_LEVEL_H264_32 },
200 { "4" , NV_ENC_LEVEL_H264_4 },
201 { "4.0" , NV_ENC_LEVEL_H264_4 },
202 { "4.1" , NV_ENC_LEVEL_H264_41 },
203 { "4.2" , NV_ENC_LEVEL_H264_42 },
204 { "5" , NV_ENC_LEVEL_H264_5 },
205 { "5.0" , NV_ENC_LEVEL_H264_5 },
206 { "5.1" , NV_ENC_LEVEL_H264_51 },
210 static const NvencValuePair nvenc_hevc_level_pairs[] = {
211 { "auto", NV_ENC_LEVEL_AUTOSELECT },
212 { "1" , NV_ENC_LEVEL_HEVC_1 },
213 { "1.0" , NV_ENC_LEVEL_HEVC_1 },
214 { "2" , NV_ENC_LEVEL_HEVC_2 },
215 { "2.0" , NV_ENC_LEVEL_HEVC_2 },
216 { "2.1" , NV_ENC_LEVEL_HEVC_21 },
217 { "3" , NV_ENC_LEVEL_HEVC_3 },
218 { "3.0" , NV_ENC_LEVEL_HEVC_3 },
219 { "3.1" , NV_ENC_LEVEL_HEVC_31 },
220 { "4" , NV_ENC_LEVEL_HEVC_4 },
221 { "4.0" , NV_ENC_LEVEL_HEVC_4 },
222 { "4.1" , NV_ENC_LEVEL_HEVC_41 },
223 { "5" , NV_ENC_LEVEL_HEVC_5 },
224 { "5.0" , NV_ENC_LEVEL_HEVC_5 },
225 { "5.1" , NV_ENC_LEVEL_HEVC_51 },
226 { "5.2" , NV_ENC_LEVEL_HEVC_52 },
227 { "6" , NV_ENC_LEVEL_HEVC_6 },
228 { "6.0" , NV_ENC_LEVEL_HEVC_6 },
229 { "6.1" , NV_ENC_LEVEL_HEVC_61 },
230 { "6.2" , NV_ENC_LEVEL_HEVC_62 },
234 static const struct {
239 { NV_ENC_SUCCESS, 0, "success" },
240 { NV_ENC_ERR_NO_ENCODE_DEVICE, AVERROR(ENOENT), "no encode device" },
241 { NV_ENC_ERR_UNSUPPORTED_DEVICE, AVERROR(ENOSYS), "unsupported device" },
242 { NV_ENC_ERR_INVALID_ENCODERDEVICE, AVERROR(EINVAL), "invalid encoder device" },
243 { NV_ENC_ERR_INVALID_DEVICE, AVERROR(EINVAL), "invalid device" },
244 { NV_ENC_ERR_DEVICE_NOT_EXIST, AVERROR(EIO), "device does not exist" },
245 { NV_ENC_ERR_INVALID_PTR, AVERROR(EFAULT), "invalid ptr" },
246 { NV_ENC_ERR_INVALID_EVENT, AVERROR(EINVAL), "invalid event" },
247 { NV_ENC_ERR_INVALID_PARAM, AVERROR(EINVAL), "invalid param" },
248 { NV_ENC_ERR_INVALID_CALL, AVERROR(EINVAL), "invalid call" },
249 { NV_ENC_ERR_OUT_OF_MEMORY, AVERROR(ENOMEM), "out of memory" },
250 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED, AVERROR(EINVAL), "encoder not initialized" },
251 { NV_ENC_ERR_UNSUPPORTED_PARAM, AVERROR(ENOSYS), "unsupported param" },
252 { NV_ENC_ERR_LOCK_BUSY, AVERROR(EAGAIN), "lock busy" },
253 { NV_ENC_ERR_NOT_ENOUGH_BUFFER, AVERROR(ENOBUFS), "not enough buffer" },
254 { NV_ENC_ERR_INVALID_VERSION, AVERROR(EINVAL), "invalid version" },
255 { NV_ENC_ERR_MAP_FAILED, AVERROR(EIO), "map failed" },
256 { NV_ENC_ERR_NEED_MORE_INPUT, AVERROR(EAGAIN), "need more input" },
257 { NV_ENC_ERR_ENCODER_BUSY, AVERROR(EAGAIN), "encoder busy" },
258 { NV_ENC_ERR_EVENT_NOT_REGISTERD, AVERROR(EBADF), "event not registered" },
259 { NV_ENC_ERR_GENERIC, AVERROR_UNKNOWN, "generic error" },
260 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY, AVERROR(EINVAL), "incompatible client key" },
261 { NV_ENC_ERR_UNIMPLEMENTED, AVERROR(ENOSYS), "unimplemented" },
262 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO), "resource register failed" },
263 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED, AVERROR(EBADF), "resource not registered" },
264 { NV_ENC_ERR_RESOURCE_NOT_MAPPED, AVERROR(EBADF), "resource not mapped" },
267 static int nvenc_map_error(NVENCSTATUS err, const char **desc)
270 for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
271 if (nvenc_errors[i].nverr == err) {
273 *desc = nvenc_errors[i].desc;
274 return nvenc_errors[i].averr;
278 *desc = "unknown error";
279 return AVERROR_UNKNOWN;
282 static int nvenc_print_error(void *log_ctx, NVENCSTATUS err,
283 const char *error_string)
287 ret = nvenc_map_error(err, &desc);
288 av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
292 static int input_string_to_uint32(AVCodecContext *avctx, const NvencValuePair *pair, const char *input, uint32_t *output)
294 for (; pair->str; ++pair) {
295 if (!strcmp(input, pair->str)) {
301 return AVERROR(EINVAL);
304 static void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
306 av_fifo_generic_write(queue, ×tamp, sizeof(timestamp), NULL);
309 static int64_t timestamp_queue_dequeue(AVFifoBuffer* queue)
311 int64_t timestamp = AV_NOPTS_VALUE;
312 if (av_fifo_size(queue) > 0)
313 av_fifo_generic_read(queue, ×tamp, sizeof(timestamp), NULL);
318 #define CHECK_LOAD_FUNC(t, f, s) \
320 (f) = (t)LOAD_FUNC(dl_fn->cuda_lib, s); \
322 av_log(avctx, AV_LOG_FATAL, "Failed loading %s from CUDA library\n", s); \
327 static av_cold int nvenc_dyload_cuda(AVCodecContext *avctx)
329 NvencContext *ctx = avctx->priv_data;
330 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
333 dl_fn->cu_init = cuInit;
334 dl_fn->cu_device_get_count = cuDeviceGetCount;
335 dl_fn->cu_device_get = cuDeviceGet;
336 dl_fn->cu_device_get_name = cuDeviceGetName;
337 dl_fn->cu_device_compute_capability = cuDeviceComputeCapability;
338 dl_fn->cu_ctx_create = cuCtxCreate_v2;
339 dl_fn->cu_ctx_pop_current = cuCtxPopCurrent_v2;
340 dl_fn->cu_ctx_destroy = cuCtxDestroy_v2;
348 dl_fn->cuda_lib = LoadLibrary(TEXT("nvcuda.dll"));
350 dl_fn->cuda_lib = dlopen("libcuda.so", RTLD_LAZY);
353 if (!dl_fn->cuda_lib) {
354 av_log(avctx, AV_LOG_FATAL, "Failed loading CUDA library\n");
358 CHECK_LOAD_FUNC(PCUINIT, dl_fn->cu_init, "cuInit");
359 CHECK_LOAD_FUNC(PCUDEVICEGETCOUNT, dl_fn->cu_device_get_count, "cuDeviceGetCount");
360 CHECK_LOAD_FUNC(PCUDEVICEGET, dl_fn->cu_device_get, "cuDeviceGet");
361 CHECK_LOAD_FUNC(PCUDEVICEGETNAME, dl_fn->cu_device_get_name, "cuDeviceGetName");
362 CHECK_LOAD_FUNC(PCUDEVICECOMPUTECAPABILITY, dl_fn->cu_device_compute_capability, "cuDeviceComputeCapability");
363 CHECK_LOAD_FUNC(PCUCTXCREATE, dl_fn->cu_ctx_create, "cuCtxCreate_v2");
364 CHECK_LOAD_FUNC(PCUCTXPOPCURRENT, dl_fn->cu_ctx_pop_current, "cuCtxPopCurrent_v2");
365 CHECK_LOAD_FUNC(PCUCTXDESTROY, dl_fn->cu_ctx_destroy, "cuCtxDestroy_v2");
372 DL_CLOSE_FUNC(dl_fn->cuda_lib);
374 dl_fn->cuda_lib = NULL;
380 static av_cold int check_cuda_errors(AVCodecContext *avctx, CUresult err, const char *func)
382 if (err != CUDA_SUCCESS) {
383 av_log(avctx, AV_LOG_FATAL, ">> %s - failed with error code 0x%x\n", func, err);
388 #define check_cuda_errors(f) if (!check_cuda_errors(avctx, f, #f)) goto error
390 static av_cold int nvenc_check_cuda(AVCodecContext *avctx)
392 int device_count = 0;
393 CUdevice cu_device = 0;
395 int smminor = 0, smmajor = 0;
396 int i, smver, target_smver;
398 NvencContext *ctx = avctx->priv_data;
399 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
401 switch (avctx->codec->id) {
402 case AV_CODEC_ID_H264:
403 target_smver = ctx->data_pix_fmt == AV_PIX_FMT_YUV444P ? 0x52 : 0x30;
405 case AV_CODEC_ID_H265:
409 av_log(avctx, AV_LOG_FATAL, "Unknown codec name\n");
413 if (!strncmp(ctx->preset, "lossless", 8))
416 if (!nvenc_dyload_cuda(avctx))
419 if (dl_fn->nvenc_device_count > 0)
422 check_cuda_errors(dl_fn->cu_init(0));
424 check_cuda_errors(dl_fn->cu_device_get_count(&device_count));
427 av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
431 av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", device_count);
433 dl_fn->nvenc_device_count = 0;
435 for (i = 0; i < device_count; ++i) {
436 check_cuda_errors(dl_fn->cu_device_get(&cu_device, i));
437 check_cuda_errors(dl_fn->cu_device_get_name(gpu_name, sizeof(gpu_name), cu_device));
438 check_cuda_errors(dl_fn->cu_device_compute_capability(&smmajor, &smminor, cu_device));
440 smver = (smmajor << 4) | smminor;
442 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");
444 if (smver >= target_smver)
445 dl_fn->nvenc_devices[dl_fn->nvenc_device_count++] = cu_device;
448 if (!dl_fn->nvenc_device_count) {
449 av_log(avctx, AV_LOG_FATAL, "No NVENC capable devices found\n");
457 dl_fn->nvenc_device_count = 0;
462 static av_cold int nvenc_dyload_nvenc(AVCodecContext *avctx)
464 PNVENCODEAPICREATEINSTANCE nvEncodeAPICreateInstance = 0;
465 NVENCSTATUS nvstatus;
467 NvencContext *ctx = avctx->priv_data;
468 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
470 if (!nvenc_check_cuda(avctx))
473 if (dl_fn->nvenc_lib)
477 if (sizeof(void*) == 8) {
478 dl_fn->nvenc_lib = LoadLibrary(TEXT("nvEncodeAPI64.dll"));
480 dl_fn->nvenc_lib = LoadLibrary(TEXT("nvEncodeAPI.dll"));
483 dl_fn->nvenc_lib = dlopen("libnvidia-encode.so.1", RTLD_LAZY);
486 if (!dl_fn->nvenc_lib) {
487 av_log(avctx, AV_LOG_FATAL, "Failed loading the nvenc library\n");
491 nvEncodeAPICreateInstance = (PNVENCODEAPICREATEINSTANCE)LOAD_FUNC(dl_fn->nvenc_lib, "NvEncodeAPICreateInstance");
493 if (!nvEncodeAPICreateInstance) {
494 av_log(avctx, AV_LOG_FATAL, "Failed to load nvenc entrypoint\n");
498 dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
500 nvstatus = nvEncodeAPICreateInstance(&dl_fn->nvenc_funcs);
502 if (nvstatus != NV_ENC_SUCCESS) {
503 nvenc_print_error(avctx, nvstatus, "Failed to create nvenc instance");
507 av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
512 if (dl_fn->nvenc_lib)
513 DL_CLOSE_FUNC(dl_fn->nvenc_lib);
515 dl_fn->nvenc_lib = NULL;
520 static av_cold void nvenc_unload_nvenc(AVCodecContext *avctx)
522 NvencContext *ctx = avctx->priv_data;
523 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
525 DL_CLOSE_FUNC(dl_fn->nvenc_lib);
526 dl_fn->nvenc_lib = NULL;
528 dl_fn->nvenc_device_count = 0;
531 DL_CLOSE_FUNC(dl_fn->cuda_lib);
532 dl_fn->cuda_lib = NULL;
535 dl_fn->cu_init = NULL;
536 dl_fn->cu_device_get_count = NULL;
537 dl_fn->cu_device_get = NULL;
538 dl_fn->cu_device_get_name = NULL;
539 dl_fn->cu_device_compute_capability = NULL;
540 dl_fn->cu_ctx_create = NULL;
541 dl_fn->cu_ctx_pop_current = NULL;
542 dl_fn->cu_ctx_destroy = NULL;
544 av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
547 static av_cold int nvenc_setup_device(AVCodecContext *avctx)
549 NvencContext *ctx = avctx->priv_data;
550 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
553 CUcontext cu_context_curr;
555 ctx->data_pix_fmt = avctx->pix_fmt;
558 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
559 AVHWFramesContext *frames_ctx;
560 AVCUDADeviceContext *device_hwctx;
562 if (!avctx->hw_frames_ctx) {
563 av_log(avctx, AV_LOG_ERROR, "hw_frames_ctx must be set when using GPU frames as input\n");
564 return AVERROR(EINVAL);
567 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
568 device_hwctx = frames_ctx->device_ctx->hwctx;
569 ctx->cu_context = device_hwctx->cuda_ctx;
570 ctx->data_pix_fmt = frames_ctx->sw_format;
575 if (ctx->gpu >= dl_fn->nvenc_device_count) {
576 av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->gpu, dl_fn->nvenc_device_count);
577 return AVERROR(EINVAL);
580 ctx->cu_context = NULL;
581 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
583 if (cu_res != CUDA_SUCCESS) {
584 av_log(avctx, AV_LOG_FATAL, "Failed creating CUDA context for NVENC: 0x%x\n", (int)cu_res);
585 return AVERROR_EXTERNAL;
588 cu_res = dl_fn->cu_ctx_pop_current(&cu_context_curr);
590 if (cu_res != CUDA_SUCCESS) {
591 av_log(avctx, AV_LOG_FATAL, "Failed popping CUDA context: 0x%x\n", (int)cu_res);
592 return AVERROR_EXTERNAL;
595 ctx->cu_context = ctx->cu_context_internal;
600 static av_cold int nvenc_open_session(AVCodecContext *avctx)
602 NvencContext *ctx = avctx->priv_data;
603 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
604 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
606 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS encode_session_params = { 0 };
607 NVENCSTATUS nv_status;
609 encode_session_params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
610 encode_session_params.apiVersion = NVENCAPI_VERSION;
611 encode_session_params.device = ctx->cu_context;
612 encode_session_params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
614 nv_status = p_nvenc->nvEncOpenEncodeSessionEx(&encode_session_params, &ctx->nvencoder);
615 if (nv_status != NV_ENC_SUCCESS) {
616 ctx->nvencoder = NULL;
617 return nvenc_print_error(avctx, nv_status, "OpenEncodeSessionEx failed");
623 static av_cold void set_constqp(AVCodecContext *avctx)
625 NvencContext *ctx = avctx->priv_data;
627 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
628 ctx->encode_config.rcParams.constQP.qpInterB = avctx->global_quality;
629 ctx->encode_config.rcParams.constQP.qpInterP = avctx->global_quality;
630 ctx->encode_config.rcParams.constQP.qpIntra = avctx->global_quality;
633 static av_cold void set_vbr(AVCodecContext *avctx)
635 NvencContext *ctx = avctx->priv_data;
637 ctx->encode_config.rcParams.enableMinQP = 1;
638 ctx->encode_config.rcParams.enableMaxQP = 1;
640 ctx->encode_config.rcParams.minQP.qpInterB = avctx->qmin;
641 ctx->encode_config.rcParams.minQP.qpInterP = avctx->qmin;
642 ctx->encode_config.rcParams.minQP.qpIntra = avctx->qmin;
644 ctx->encode_config.rcParams.maxQP.qpInterB = avctx->qmax;
645 ctx->encode_config.rcParams.maxQP.qpInterP = avctx->qmax;
646 ctx->encode_config.rcParams.maxQP.qpIntra = avctx->qmax;
649 static av_cold void set_lossless(AVCodecContext *avctx)
651 NvencContext *ctx = avctx->priv_data;
653 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
654 ctx->encode_config.rcParams.constQP.qpInterB = 0;
655 ctx->encode_config.rcParams.constQP.qpInterP = 0;
656 ctx->encode_config.rcParams.constQP.qpIntra = 0;
659 static av_cold void nvenc_setup_rate_control(AVCodecContext *avctx, int lossless)
661 NvencContext *ctx = avctx->priv_data;
665 if (avctx->bit_rate > 0) {
666 ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
667 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
668 ctx->encode_config.rcParams.maxBitRate = ctx->encode_config.rcParams.averageBitRate;
671 if (avctx->rc_max_rate > 0)
672 ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
675 if (avctx->codec->id == AV_CODEC_ID_H264)
676 ctx->encode_config.encodeCodecConfig.h264Config.qpPrimeYZeroTransformBypassFlag = 1;
682 } else if (ctx->cbr) {
684 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CBR;
686 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_2_PASS_QUALITY;
688 if (avctx->codec->id == AV_CODEC_ID_H264) {
689 ctx->encode_config.encodeCodecConfig.h264Config.adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
690 ctx->encode_config.encodeCodecConfig.h264Config.fmoMode = NV_ENC_H264_FMO_DISABLE;
694 if (avctx->codec->id == AV_CODEC_ID_H264) {
695 ctx->encode_config.encodeCodecConfig.h264Config.outputBufferingPeriodSEI = 1;
696 ctx->encode_config.encodeCodecConfig.h264Config.outputPictureTimingSEI = 1;
697 } else if (avctx->codec->id == AV_CODEC_ID_H265) {
698 ctx->encode_config.encodeCodecConfig.hevcConfig.outputBufferingPeriodSEI = 1;
699 ctx->encode_config.encodeCodecConfig.hevcConfig.outputPictureTimingSEI = 1;
701 } else if (avctx->global_quality > 0) {
707 if (avctx->qmin >= 0 && avctx->qmax >= 0) {
710 qp_inter_p = (avctx->qmax + 3 * avctx->qmin) / 4; // biased towards Qmin
713 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_2_PASS_VBR;
714 if (avctx->codec->id == AV_CODEC_ID_H264) {
715 ctx->encode_config.encodeCodecConfig.h264Config.adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
716 ctx->encode_config.encodeCodecConfig.h264Config.fmoMode = NV_ENC_H264_FMO_DISABLE;
719 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR_MINQP;
722 qp_inter_p = 26; // default to 26
725 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_2_PASS_VBR;
727 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
731 ctx->encode_config.rcParams.enableInitialRCQP = 1;
732 ctx->encode_config.rcParams.initialRCQP.qpInterP = qp_inter_p;
734 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
735 ctx->encode_config.rcParams.initialRCQP.qpIntra = av_clip(
736 qp_inter_p * fabs(avctx->i_quant_factor) + avctx->i_quant_offset, 0, 51);
737 ctx->encode_config.rcParams.initialRCQP.qpInterB = av_clip(
738 qp_inter_p * fabs(avctx->b_quant_factor) + avctx->b_quant_offset, 0, 51);
740 ctx->encode_config.rcParams.initialRCQP.qpIntra = qp_inter_p;
741 ctx->encode_config.rcParams.initialRCQP.qpInterB = qp_inter_p;
745 if (avctx->rc_buffer_size > 0) {
746 ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
747 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
748 ctx->encode_config.rcParams.vbvBufferSize = 2 * ctx->encode_config.rcParams.averageBitRate;
752 static av_cold int nvenc_setup_h264_config(AVCodecContext *avctx, int lossless)
754 NvencContext *ctx = avctx->priv_data;
757 ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.colourMatrix = avctx->colorspace;
758 ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.colourPrimaries = avctx->color_primaries;
759 ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.transferCharacteristics = avctx->color_trc;
760 ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
761 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
763 ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.colourDescriptionPresentFlag =
764 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
766 ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.videoSignalTypePresentFlag =
767 (ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.colourDescriptionPresentFlag
768 || ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.videoFormat != 5
769 || ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.videoFullRangeFlag != 0);
771 ctx->encode_config.encodeCodecConfig.h264Config.sliceMode = 3;
772 ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData = 1;
774 ctx->encode_config.encodeCodecConfig.h264Config.disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
775 ctx->encode_config.encodeCodecConfig.h264Config.repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
777 ctx->encode_config.encodeCodecConfig.h264Config.outputAUD = 1;
779 if (!ctx->profile && !lossless) {
780 switch (avctx->profile) {
781 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
782 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
784 case FF_PROFILE_H264_BASELINE:
785 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
787 case FF_PROFILE_H264_MAIN:
788 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
790 case FF_PROFILE_H264_HIGH:
791 case FF_PROFILE_UNKNOWN:
792 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
795 av_log(avctx, AV_LOG_WARNING, "Unsupported profile requested, falling back to high\n");
796 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
799 } else if (!lossless) {
800 if (!strcmp(ctx->profile, "high")) {
801 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
802 avctx->profile = FF_PROFILE_H264_HIGH;
803 } else if (!strcmp(ctx->profile, "main")) {
804 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
805 avctx->profile = FF_PROFILE_H264_MAIN;
806 } else if (!strcmp(ctx->profile, "baseline")) {
807 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
808 avctx->profile = FF_PROFILE_H264_BASELINE;
809 } else if (!strcmp(ctx->profile, "high444p")) {
810 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
811 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
813 av_log(avctx, AV_LOG_FATAL, "Profile \"%s\" is unknown! Supported profiles: high, main, baseline\n", ctx->profile);
814 return AVERROR(EINVAL);
818 // force setting profile as high444p if input is AV_PIX_FMT_YUV444P
819 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P) {
820 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
821 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
824 ctx->encode_config.encodeCodecConfig.h264Config.chromaFormatIDC = avctx->profile == FF_PROFILE_H264_HIGH_444_PREDICTIVE ? 3 : 1;
827 res = input_string_to_uint32(avctx, nvenc_h264_level_pairs, ctx->level, &ctx->encode_config.encodeCodecConfig.h264Config.level);
830 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);
834 ctx->encode_config.encodeCodecConfig.h264Config.level = NV_ENC_LEVEL_AUTOSELECT;
840 static av_cold int nvenc_setup_hevc_config(AVCodecContext *avctx)
842 NvencContext *ctx = avctx->priv_data;
845 ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.colourMatrix = avctx->colorspace;
846 ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.colourPrimaries = avctx->color_primaries;
847 ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.transferCharacteristics = avctx->color_trc;
848 ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
849 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
851 ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.colourDescriptionPresentFlag =
852 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
854 ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.videoSignalTypePresentFlag =
855 (ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.colourDescriptionPresentFlag
856 || ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.videoFormat != 5
857 || ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.videoFullRangeFlag != 0);
859 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode = 3;
860 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData = 1;
862 ctx->encode_config.encodeCodecConfig.hevcConfig.disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
863 ctx->encode_config.encodeCodecConfig.hevcConfig.repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
865 ctx->encode_config.encodeCodecConfig.hevcConfig.outputAUD = 1;
867 /* No other profile is supported in the current SDK version 5 */
868 ctx->encode_config.profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
869 avctx->profile = FF_PROFILE_HEVC_MAIN;
872 res = input_string_to_uint32(avctx, nvenc_hevc_level_pairs, ctx->level, &ctx->encode_config.encodeCodecConfig.hevcConfig.level);
875 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);
879 ctx->encode_config.encodeCodecConfig.hevcConfig.level = NV_ENC_LEVEL_AUTOSELECT;
883 if (!strcmp(ctx->tier, "main")) {
884 ctx->encode_config.encodeCodecConfig.hevcConfig.tier = NV_ENC_TIER_HEVC_MAIN;
885 } else if (!strcmp(ctx->tier, "high")) {
886 ctx->encode_config.encodeCodecConfig.hevcConfig.tier = NV_ENC_TIER_HEVC_HIGH;
888 av_log(avctx, AV_LOG_FATAL, "Tier \"%s\" is unknown! Supported tiers: main, high\n", ctx->tier);
889 return AVERROR(EINVAL);
896 static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx, int lossless)
898 switch (avctx->codec->id) {
899 case AV_CODEC_ID_H264:
900 return nvenc_setup_h264_config(avctx, lossless);
901 case AV_CODEC_ID_H265:
902 return nvenc_setup_hevc_config(avctx);
903 /* Earlier switch/case will return if unknown codec is passed. */
909 static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
911 NvencContext *ctx = avctx->priv_data;
912 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
913 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
915 NV_ENC_PRESET_CONFIG preset_config = { 0 };
916 GUID encoder_preset = NV_ENC_PRESET_HQ_GUID;
918 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
919 AVCPBProperties *cpb_props;
926 ctx->last_dts = AV_NOPTS_VALUE;
928 ctx->encode_config.version = NV_ENC_CONFIG_VER;
929 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
930 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
931 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
934 if (!strcmp(ctx->preset, "slow")) {
935 encoder_preset = NV_ENC_PRESET_HQ_GUID;
937 } else if (!strcmp(ctx->preset, "medium")) {
938 encoder_preset = NV_ENC_PRESET_HQ_GUID;
940 } else if (!strcmp(ctx->preset, "fast")) {
941 encoder_preset = NV_ENC_PRESET_HP_GUID;
943 } else if (!strcmp(ctx->preset, "hq")) {
944 encoder_preset = NV_ENC_PRESET_HQ_GUID;
945 } else if (!strcmp(ctx->preset, "hp")) {
946 encoder_preset = NV_ENC_PRESET_HP_GUID;
947 } else if (!strcmp(ctx->preset, "bd")) {
948 encoder_preset = NV_ENC_PRESET_BD_GUID;
949 } else if (!strcmp(ctx->preset, "ll")) {
950 encoder_preset = NV_ENC_PRESET_LOW_LATENCY_DEFAULT_GUID;
952 } else if (!strcmp(ctx->preset, "llhp")) {
953 encoder_preset = NV_ENC_PRESET_LOW_LATENCY_HP_GUID;
955 } else if (!strcmp(ctx->preset, "llhq")) {
956 encoder_preset = NV_ENC_PRESET_LOW_LATENCY_HQ_GUID;
958 } else if (!strcmp(ctx->preset, "lossless")) {
959 encoder_preset = NV_ENC_PRESET_LOSSLESS_DEFAULT_GUID;
961 } else if (!strcmp(ctx->preset, "losslesshp")) {
962 encoder_preset = NV_ENC_PRESET_LOSSLESS_HP_GUID;
964 } else if (!strcmp(ctx->preset, "default")) {
965 encoder_preset = NV_ENC_PRESET_DEFAULT_GUID;
967 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);
968 return AVERROR(EINVAL);
972 if (ctx->twopass < 0) {
976 switch (avctx->codec->id) {
977 case AV_CODEC_ID_H264:
978 codec = NV_ENC_CODEC_H264_GUID;
980 case AV_CODEC_ID_H265:
981 codec = NV_ENC_CODEC_HEVC_GUID;
984 av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
985 return AVERROR(EINVAL);
988 nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder, codec, encoder_preset, &preset_config);
989 if (nv_status != NV_ENC_SUCCESS) {
990 return nvenc_print_error(avctx, nv_status, "GetEncodePresetConfig failed");
993 ctx->init_encode_params.encodeGUID = codec;
994 ctx->init_encode_params.encodeHeight = avctx->height;
995 ctx->init_encode_params.encodeWidth = avctx->width;
997 if (avctx->sample_aspect_ratio.num && avctx->sample_aspect_ratio.den &&
998 (avctx->sample_aspect_ratio.num != 1 || avctx->sample_aspect_ratio.num != 1)) {
1000 avctx->width * avctx->sample_aspect_ratio.num,
1001 avctx->height * avctx->sample_aspect_ratio.den,
1003 ctx->init_encode_params.darHeight = dh;
1004 ctx->init_encode_params.darWidth = dw;
1006 ctx->init_encode_params.darHeight = avctx->height;
1007 ctx->init_encode_params.darWidth = avctx->width;
1010 // De-compensate for hardware, dubiously, trying to compensate for
1011 // playback at 704 pixel width.
1012 if (avctx->width == 720 &&
1013 (avctx->height == 480 || avctx->height == 576)) {
1015 ctx->init_encode_params.darWidth * 44,
1016 ctx->init_encode_params.darHeight * 45,
1018 ctx->init_encode_params.darHeight = dh;
1019 ctx->init_encode_params.darWidth = dw;
1022 ctx->init_encode_params.frameRateNum = avctx->time_base.den;
1023 ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
1025 num_mbs = ((avctx->width + 15) >> 4) * ((avctx->height + 15) >> 4);
1026 ctx->max_surface_count = (num_mbs >= 8160) ? 32 : 48;
1028 if (ctx->buffer_delay >= ctx->max_surface_count)
1029 ctx->buffer_delay = ctx->max_surface_count - 1;
1031 ctx->init_encode_params.enableEncodeAsync = 0;
1032 ctx->init_encode_params.enablePTD = 1;
1034 ctx->init_encode_params.presetGUID = encoder_preset;
1036 ctx->init_encode_params.encodeConfig = &ctx->encode_config;
1037 memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
1038 ctx->encode_config.version = NV_ENC_CONFIG_VER;
1040 if (avctx->refs >= 0) {
1041 /* 0 means "let the hardware decide" */
1042 switch (avctx->codec->id) {
1043 case AV_CODEC_ID_H264:
1044 ctx->encode_config.encodeCodecConfig.h264Config.maxNumRefFrames = avctx->refs;
1046 case AV_CODEC_ID_H265:
1047 ctx->encode_config.encodeCodecConfig.hevcConfig.maxNumRefFramesInDPB = avctx->refs;
1049 /* Earlier switch/case will return if unknown codec is passed. */
1053 if (avctx->gop_size > 0) {
1054 if (avctx->max_b_frames >= 0) {
1055 /* 0 is intra-only, 1 is I/P only, 2 is one B Frame, 3 two B frames, and so on. */
1056 ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
1059 ctx->encode_config.gopLength = avctx->gop_size;
1060 switch (avctx->codec->id) {
1061 case AV_CODEC_ID_H264:
1062 ctx->encode_config.encodeCodecConfig.h264Config.idrPeriod = avctx->gop_size;
1064 case AV_CODEC_ID_H265:
1065 ctx->encode_config.encodeCodecConfig.hevcConfig.idrPeriod = avctx->gop_size;
1067 /* Earlier switch/case will return if unknown codec is passed. */
1069 } else if (avctx->gop_size == 0) {
1070 ctx->encode_config.frameIntervalP = 0;
1071 ctx->encode_config.gopLength = 1;
1072 switch (avctx->codec->id) {
1073 case AV_CODEC_ID_H264:
1074 ctx->encode_config.encodeCodecConfig.h264Config.idrPeriod = 1;
1076 case AV_CODEC_ID_H265:
1077 ctx->encode_config.encodeCodecConfig.hevcConfig.idrPeriod = 1;
1079 /* Earlier switch/case will return if unknown codec is passed. */
1083 /* when there're b frames, set dts offset */
1084 if (ctx->encode_config.frameIntervalP >= 2)
1087 nvenc_setup_rate_control(avctx, lossless);
1089 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1090 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
1092 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
1095 res = nvenc_setup_codec_config(avctx, lossless);
1099 nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
1100 if (nv_status != NV_ENC_SUCCESS) {
1101 return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
1104 if (ctx->encode_config.frameIntervalP > 1)
1105 avctx->has_b_frames = 2;
1107 if (ctx->encode_config.rcParams.averageBitRate > 0)
1108 avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
1110 cpb_props = ff_add_cpb_side_data(avctx);
1112 return AVERROR(ENOMEM);
1113 cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
1114 cpb_props->avg_bitrate = avctx->bit_rate;
1115 cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
1120 static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
1122 NvencContext *ctx = avctx->priv_data;
1123 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1124 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1126 NVENCSTATUS nv_status;
1127 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
1128 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1130 switch (ctx->data_pix_fmt) {
1131 case AV_PIX_FMT_YUV420P:
1132 ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_YV12_PL;
1135 case AV_PIX_FMT_NV12:
1136 ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_NV12_PL;
1139 case AV_PIX_FMT_YUV444P:
1140 ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_YUV444_PL;
1144 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format\n");
1145 return AVERROR(EINVAL);
1148 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1149 ctx->surfaces[idx].in_ref = av_frame_alloc();
1150 if (!ctx->surfaces[idx].in_ref)
1151 return AVERROR(ENOMEM);
1153 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1154 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1155 allocSurf.width = (avctx->width + 31) & ~31;
1156 allocSurf.height = (avctx->height + 31) & ~31;
1157 allocSurf.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
1158 allocSurf.bufferFmt = ctx->surfaces[idx].format;
1160 nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
1161 if (nv_status != NV_ENC_SUCCESS) {
1162 return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
1165 ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
1166 ctx->surfaces[idx].width = allocSurf.width;
1167 ctx->surfaces[idx].height = allocSurf.height;
1170 ctx->surfaces[idx].lockCount = 0;
1172 /* 1MB is large enough to hold most output frames. NVENC increases this automaticaly if it's not enough. */
1173 allocOut.size = 1024 * 1024;
1175 allocOut.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
1177 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
1178 if (nv_status != NV_ENC_SUCCESS) {
1179 int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
1180 if (avctx->pix_fmt != AV_PIX_FMT_CUDA)
1181 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
1182 av_frame_free(&ctx->surfaces[idx].in_ref);
1186 ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1187 ctx->surfaces[idx].size = allocOut.size;
1192 static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx, int* surfaceCount)
1195 NvencContext *ctx = avctx->priv_data;
1197 ctx->surfaces = av_malloc(ctx->max_surface_count * sizeof(*ctx->surfaces));
1199 if (!ctx->surfaces) {
1200 return AVERROR(ENOMEM);
1203 ctx->timestamp_list = av_fifo_alloc(ctx->max_surface_count * sizeof(int64_t));
1204 if (!ctx->timestamp_list)
1205 return AVERROR(ENOMEM);
1206 ctx->output_surface_queue = av_fifo_alloc(ctx->max_surface_count * sizeof(NvencSurface*));
1207 if (!ctx->output_surface_queue)
1208 return AVERROR(ENOMEM);
1209 ctx->output_surface_ready_queue = av_fifo_alloc(ctx->max_surface_count * sizeof(NvencSurface*));
1210 if (!ctx->output_surface_ready_queue)
1211 return AVERROR(ENOMEM);
1213 for (*surfaceCount = 0; *surfaceCount < ctx->max_surface_count; ++*surfaceCount) {
1214 res = nvenc_alloc_surface(avctx, *surfaceCount);
1222 static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
1224 NvencContext *ctx = avctx->priv_data;
1225 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1226 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1228 NVENCSTATUS nv_status;
1229 uint32_t outSize = 0;
1230 char tmpHeader[256];
1231 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1232 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1234 payload.spsppsBuffer = tmpHeader;
1235 payload.inBufferSize = sizeof(tmpHeader);
1236 payload.outSPSPPSPayloadSize = &outSize;
1238 nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
1239 if (nv_status != NV_ENC_SUCCESS) {
1240 return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
1243 avctx->extradata_size = outSize;
1244 avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
1246 if (!avctx->extradata) {
1247 return AVERROR(ENOMEM);
1250 memcpy(avctx->extradata, tmpHeader, outSize);
1255 static av_cold int nvenc_encode_init(AVCodecContext *avctx)
1257 NvencContext *ctx = avctx->priv_data;
1258 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1259 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1263 int surfaceCount = 0;
1265 if (!nvenc_dyload_nvenc(avctx))
1266 return AVERROR_EXTERNAL;
1268 res = nvenc_setup_device(avctx);
1272 res = nvenc_open_session(avctx);
1276 res = nvenc_setup_encoder(avctx);
1280 res = nvenc_setup_surfaces(avctx, &surfaceCount);
1284 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1285 res = nvenc_setup_extradata(avctx);
1293 av_fifo_freep(&ctx->timestamp_list);
1294 av_fifo_freep(&ctx->output_surface_ready_queue);
1295 av_fifo_freep(&ctx->output_surface_queue);
1297 for (i = 0; i < surfaceCount; ++i) {
1298 if (avctx->pix_fmt != AV_PIX_FMT_CUDA)
1299 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
1300 av_frame_free(&ctx->surfaces[i].in_ref);
1301 p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
1303 av_freep(&ctx->surfaces);
1306 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1307 ctx->nvencoder = NULL;
1309 if (ctx->cu_context_internal)
1310 dl_fn->cu_ctx_destroy(ctx->cu_context_internal);
1311 ctx->cu_context = ctx->cu_context_internal = NULL;
1313 nvenc_unload_nvenc(avctx);
1318 static av_cold int nvenc_encode_close(AVCodecContext *avctx)
1320 NvencContext *ctx = avctx->priv_data;
1321 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1322 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1325 av_fifo_freep(&ctx->timestamp_list);
1326 av_fifo_freep(&ctx->output_surface_ready_queue);
1327 av_fifo_freep(&ctx->output_surface_queue);
1329 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1330 for (i = 0; i < ctx->max_surface_count; ++i) {
1331 if (ctx->surfaces[i].input_surface) {
1332 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->surfaces[i].in_map.mappedResource);
1335 for (i = 0; i < ctx->nb_registered_frames; i++) {
1336 if (ctx->registered_frames[i].regptr)
1337 p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1339 ctx->nb_registered_frames = 0;
1342 for (i = 0; i < ctx->max_surface_count; ++i) {
1343 if (avctx->pix_fmt != AV_PIX_FMT_CUDA)
1344 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
1345 av_frame_free(&ctx->surfaces[i].in_ref);
1346 p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
1348 av_freep(&ctx->surfaces);
1349 ctx->max_surface_count = 0;
1351 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1352 ctx->nvencoder = NULL;
1354 if (ctx->cu_context_internal)
1355 dl_fn->cu_ctx_destroy(ctx->cu_context_internal);
1356 ctx->cu_context = ctx->cu_context_internal = NULL;
1358 nvenc_unload_nvenc(avctx);
1363 static NvencSurface *get_free_frame(NvencContext *ctx)
1367 for (i = 0; i < ctx->max_surface_count; ++i) {
1368 if (!ctx->surfaces[i].lockCount) {
1369 ctx->surfaces[i].lockCount = 1;
1370 return &ctx->surfaces[i];
1377 static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *inSurf,
1378 NV_ENC_LOCK_INPUT_BUFFER *lockBufferParams, const AVFrame *frame)
1380 uint8_t *buf = lockBufferParams->bufferDataPtr;
1381 int off = inSurf->height * lockBufferParams->pitch;
1383 if (frame->format == AV_PIX_FMT_YUV420P) {
1384 av_image_copy_plane(buf, lockBufferParams->pitch,
1385 frame->data[0], frame->linesize[0],
1386 avctx->width, avctx->height);
1390 av_image_copy_plane(buf, lockBufferParams->pitch >> 1,
1391 frame->data[2], frame->linesize[2],
1392 avctx->width >> 1, avctx->height >> 1);
1396 av_image_copy_plane(buf, lockBufferParams->pitch >> 1,
1397 frame->data[1], frame->linesize[1],
1398 avctx->width >> 1, avctx->height >> 1);
1399 } else if (frame->format == AV_PIX_FMT_NV12) {
1400 av_image_copy_plane(buf, lockBufferParams->pitch,
1401 frame->data[0], frame->linesize[0],
1402 avctx->width, avctx->height);
1406 av_image_copy_plane(buf, lockBufferParams->pitch,
1407 frame->data[1], frame->linesize[1],
1408 avctx->width, avctx->height >> 1);
1409 } else if (frame->format == AV_PIX_FMT_YUV444P) {
1410 av_image_copy_plane(buf, lockBufferParams->pitch,
1411 frame->data[0], frame->linesize[0],
1412 avctx->width, avctx->height);
1416 av_image_copy_plane(buf, lockBufferParams->pitch,
1417 frame->data[1], frame->linesize[1],
1418 avctx->width, avctx->height);
1422 av_image_copy_plane(buf, lockBufferParams->pitch,
1423 frame->data[2], frame->linesize[2],
1424 avctx->width, avctx->height);
1426 av_log(avctx, AV_LOG_FATAL, "Invalid pixel format!\n");
1427 return AVERROR(EINVAL);
1433 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1435 NvencContext *ctx = avctx->priv_data;
1436 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1437 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1441 if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1442 for (i = 0; i < ctx->nb_registered_frames; i++) {
1443 if (!ctx->registered_frames[i].mapped) {
1444 if (ctx->registered_frames[i].regptr) {
1445 p_nvenc->nvEncUnregisterResource(ctx->nvencoder,
1446 ctx->registered_frames[i].regptr);
1447 ctx->registered_frames[i].regptr = NULL;
1453 return ctx->nb_registered_frames++;
1456 av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1457 return AVERROR(ENOMEM);
1460 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1462 NvencContext *ctx = avctx->priv_data;
1463 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1464 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1466 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1467 NV_ENC_REGISTER_RESOURCE reg;
1470 for (i = 0; i < ctx->nb_registered_frames; i++) {
1471 if (ctx->registered_frames[i].ptr == (CUdeviceptr)frame->data[0])
1475 idx = nvenc_find_free_reg_resource(avctx);
1479 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1480 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1481 reg.width = frames_ctx->width;
1482 reg.height = frames_ctx->height;
1483 reg.bufferFormat = ctx->surfaces[0].format;
1484 reg.pitch = frame->linesize[0];
1485 reg.resourceToRegister = frame->data[0];
1487 ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, ®);
1488 if (ret != NV_ENC_SUCCESS) {
1489 nvenc_print_error(avctx, ret, "Error registering an input resource");
1490 return AVERROR_UNKNOWN;
1493 ctx->registered_frames[idx].ptr = (CUdeviceptr)frame->data[0];
1494 ctx->registered_frames[idx].regptr = reg.registeredResource;
1498 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1499 NvencSurface *nvenc_frame)
1501 NvencContext *ctx = avctx->priv_data;
1502 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1503 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1506 NVENCSTATUS nv_status;
1508 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1509 int reg_idx = nvenc_register_frame(avctx, frame);
1511 av_log(avctx, AV_LOG_ERROR, "Could not register an input CUDA frame\n");
1515 res = av_frame_ref(nvenc_frame->in_ref, frame);
1519 nvenc_frame->in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1520 nvenc_frame->in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1521 nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &nvenc_frame->in_map);
1522 if (nv_status != NV_ENC_SUCCESS) {
1523 av_frame_unref(nvenc_frame->in_ref);
1524 return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
1527 ctx->registered_frames[reg_idx].mapped = 1;
1528 nvenc_frame->reg_idx = reg_idx;
1529 nvenc_frame->input_surface = nvenc_frame->in_map.mappedResource;
1532 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1534 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1535 lockBufferParams.inputBuffer = nvenc_frame->input_surface;
1537 nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
1538 if (nv_status != NV_ENC_SUCCESS) {
1539 return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
1542 res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
1544 nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
1545 if (nv_status != NV_ENC_SUCCESS) {
1546 return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
1553 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1554 NV_ENC_PIC_PARAMS *params)
1556 NvencContext *ctx = avctx->priv_data;
1558 switch (avctx->codec->id) {
1559 case AV_CODEC_ID_H264:
1560 params->codecPicParams.h264PicParams.sliceMode = ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1561 params->codecPicParams.h264PicParams.sliceModeData = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1563 case AV_CODEC_ID_H265:
1564 params->codecPicParams.hevcPicParams.sliceMode = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1565 params->codecPicParams.hevcPicParams.sliceModeData = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1570 static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
1572 NvencContext *ctx = avctx->priv_data;
1573 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1574 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1576 uint32_t slice_mode_data;
1577 uint32_t *slice_offsets;
1578 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1579 NVENCSTATUS nv_status;
1582 enum AVPictureType pict_type;
1584 switch (avctx->codec->id) {
1585 case AV_CODEC_ID_H264:
1586 slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1588 case AV_CODEC_ID_H265:
1589 slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1592 av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
1593 res = AVERROR(EINVAL);
1596 slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
1599 return AVERROR(ENOMEM);
1601 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1603 lock_params.doNotWait = 0;
1604 lock_params.outputBitstream = tmpoutsurf->output_surface;
1605 lock_params.sliceOffsets = slice_offsets;
1607 nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
1608 if (nv_status != NV_ENC_SUCCESS) {
1609 res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
1613 if (res = ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes,0)) {
1614 p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1618 memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1620 nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1621 if (nv_status != NV_ENC_SUCCESS)
1622 nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
1625 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1626 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, tmpoutsurf->in_map.mappedResource);
1627 av_frame_unref(tmpoutsurf->in_ref);
1628 ctx->registered_frames[tmpoutsurf->reg_idx].mapped = 0;
1630 tmpoutsurf->input_surface = NULL;
1633 switch (lock_params.pictureType) {
1634 case NV_ENC_PIC_TYPE_IDR:
1635 pkt->flags |= AV_PKT_FLAG_KEY;
1636 case NV_ENC_PIC_TYPE_I:
1637 pict_type = AV_PICTURE_TYPE_I;
1639 case NV_ENC_PIC_TYPE_P:
1640 pict_type = AV_PICTURE_TYPE_P;
1642 case NV_ENC_PIC_TYPE_B:
1643 pict_type = AV_PICTURE_TYPE_B;
1645 case NV_ENC_PIC_TYPE_BI:
1646 pict_type = AV_PICTURE_TYPE_BI;
1649 av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
1650 av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
1651 res = AVERROR_EXTERNAL;
1655 #if FF_API_CODED_FRAME
1656 FF_DISABLE_DEPRECATION_WARNINGS
1657 avctx->coded_frame->pict_type = pict_type;
1658 FF_ENABLE_DEPRECATION_WARNINGS
1661 ff_side_data_set_encoder_stats(pkt,
1662 (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
1664 pkt->pts = lock_params.outputTimeStamp;
1665 pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
1667 /* when there're b frame(s), set dts offset */
1668 if (ctx->encode_config.frameIntervalP >= 2)
1671 if (pkt->dts > pkt->pts)
1672 pkt->dts = pkt->pts;
1674 if (ctx->last_dts != AV_NOPTS_VALUE && pkt->dts <= ctx->last_dts)
1675 pkt->dts = ctx->last_dts + 1;
1677 ctx->last_dts = pkt->dts;
1679 av_free(slice_offsets);
1685 av_free(slice_offsets);
1686 timestamp_queue_dequeue(ctx->timestamp_list);
1691 static int output_ready(NvencContext *ctx, int flush)
1693 int nb_ready, nb_pending;
1695 nb_ready = av_fifo_size(ctx->output_surface_ready_queue) / sizeof(NvencSurface*);
1696 nb_pending = av_fifo_size(ctx->output_surface_queue) / sizeof(NvencSurface*);
1697 return nb_ready > 0 && (flush || nb_ready + nb_pending >= ctx->buffer_delay);
1700 static int nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1701 const AVFrame *frame, int *got_packet)
1703 NVENCSTATUS nv_status;
1704 NvencSurface *tmpoutsurf, *inSurf;
1707 NvencContext *ctx = avctx->priv_data;
1708 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1709 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1711 NV_ENC_PIC_PARAMS pic_params = { 0 };
1712 pic_params.version = NV_ENC_PIC_PARAMS_VER;
1715 inSurf = get_free_frame(ctx);
1718 res = nvenc_upload_frame(avctx, frame, inSurf);
1720 inSurf->lockCount = 0;
1724 pic_params.inputBuffer = inSurf->input_surface;
1725 pic_params.bufferFmt = inSurf->format;
1726 pic_params.inputWidth = avctx->width;
1727 pic_params.inputHeight = avctx->height;
1728 pic_params.outputBitstream = inSurf->output_surface;
1729 pic_params.completionEvent = 0;
1731 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1732 if (frame->top_field_first) {
1733 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
1735 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
1738 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1741 pic_params.encodePicFlags = 0;
1742 pic_params.inputTimeStamp = frame->pts;
1743 pic_params.inputDuration = 0;
1745 nvenc_codec_specific_pic_params(avctx, &pic_params);
1747 timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
1749 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1752 nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
1754 if (frame && nv_status == NV_ENC_ERR_NEED_MORE_INPUT)
1755 av_fifo_generic_write(ctx->output_surface_queue, &inSurf, sizeof(inSurf), NULL);
1757 if (nv_status != NV_ENC_SUCCESS && nv_status != NV_ENC_ERR_NEED_MORE_INPUT) {
1758 return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
1761 if (nv_status != NV_ENC_ERR_NEED_MORE_INPUT) {
1762 while (av_fifo_size(ctx->output_surface_queue) > 0) {
1763 av_fifo_generic_read(ctx->output_surface_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
1764 av_fifo_generic_write(ctx->output_surface_ready_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
1768 av_fifo_generic_write(ctx->output_surface_ready_queue, &inSurf, sizeof(inSurf), NULL);
1771 if (output_ready(ctx, !frame)) {
1772 av_fifo_generic_read(ctx->output_surface_ready_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
1774 res = process_output_surface(avctx, pkt, tmpoutsurf);
1779 av_assert0(tmpoutsurf->lockCount);
1780 tmpoutsurf->lockCount--;
1790 static const enum AVPixelFormat pix_fmts_nvenc[] = {
1800 #define OFFSET(x) offsetof(NvencContext, x)
1801 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
1802 static const AVOption options[] = {
1803 { "preset", "Set the encoding preset (one of slow = hq 2pass, medium = hq, fast = hp, hq, hp, bd, ll, llhq, llhp, lossless, losslesshp, default)", OFFSET(preset), AV_OPT_TYPE_STRING, { .str = "medium" }, 0, 0, VE },
1804 { "profile", "Set the encoding profile (high, main, baseline or high444p)", OFFSET(profile), AV_OPT_TYPE_STRING, { .str = "main" }, 0, 0, VE },
1805 { "level", "Set the encoding level restriction (auto, 1.0, 1.0b, 1.1, 1.2, ..., 4.2, 5.0, 5.1)", OFFSET(level), AV_OPT_TYPE_STRING, { .str = "auto" }, 0, 0, VE },
1806 { "tier", "Set the encoding tier (main or high)", OFFSET(tier), AV_OPT_TYPE_STRING, { .str = "main" }, 0, 0, VE },
1807 { "cbr", "Use cbr encoding mode", OFFSET(cbr), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
1808 { "2pass", "Use 2pass encoding mode", OFFSET(twopass), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, VE },
1809 { "gpu", "Selects which NVENC capable GPU to use. First GPU is 0, second is 1, and so on.", OFFSET(gpu), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, VE },
1810 { "delay", "Delays frame output by the given amount of frames.", OFFSET(buffer_delay), AV_OPT_TYPE_INT, { .i64 = INT_MAX }, 0, INT_MAX, VE },
1814 static const AVCodecDefault nvenc_defaults[] = {
1826 #if CONFIG_NVENC_ENCODER
1827 static const AVClass nvenc_class = {
1828 .class_name = "nvenc",
1829 .item_name = av_default_item_name,
1831 .version = LIBAVUTIL_VERSION_INT,
1834 AVCodec ff_nvenc_encoder = {
1836 .long_name = NULL_IF_CONFIG_SMALL("NVIDIA NVENC h264 encoder"),
1837 .type = AVMEDIA_TYPE_VIDEO,
1838 .id = AV_CODEC_ID_H264,
1839 .priv_data_size = sizeof(NvencContext),
1840 .init = nvenc_encode_init,
1841 .encode2 = nvenc_encode_frame,
1842 .close = nvenc_encode_close,
1843 .capabilities = AV_CODEC_CAP_DELAY,
1844 .priv_class = &nvenc_class,
1845 .defaults = nvenc_defaults,
1846 .pix_fmts = pix_fmts_nvenc,
1850 /* Add an alias for nvenc_h264 */
1851 #if CONFIG_NVENC_H264_ENCODER
1852 static const AVClass nvenc_h264_class = {
1853 .class_name = "nvenc_h264",
1854 .item_name = av_default_item_name,
1856 .version = LIBAVUTIL_VERSION_INT,
1859 AVCodec ff_nvenc_h264_encoder = {
1860 .name = "nvenc_h264",
1861 .long_name = NULL_IF_CONFIG_SMALL("NVIDIA NVENC h264 encoder"),
1862 .type = AVMEDIA_TYPE_VIDEO,
1863 .id = AV_CODEC_ID_H264,
1864 .priv_data_size = sizeof(NvencContext),
1865 .init = nvenc_encode_init,
1866 .encode2 = nvenc_encode_frame,
1867 .close = nvenc_encode_close,
1868 .capabilities = AV_CODEC_CAP_DELAY,
1869 .priv_class = &nvenc_h264_class,
1870 .defaults = nvenc_defaults,
1871 .pix_fmts = pix_fmts_nvenc,
1875 #if CONFIG_NVENC_HEVC_ENCODER
1876 static const AVClass nvenc_hevc_class = {
1877 .class_name = "nvenc_hevc",
1878 .item_name = av_default_item_name,
1880 .version = LIBAVUTIL_VERSION_INT,
1883 AVCodec ff_nvenc_hevc_encoder = {
1884 .name = "nvenc_hevc",
1885 .long_name = NULL_IF_CONFIG_SMALL("NVIDIA NVENC hevc encoder"),
1886 .type = AVMEDIA_TYPE_VIDEO,
1887 .id = AV_CODEC_ID_H265,
1888 .priv_data_size = sizeof(NvencContext),
1889 .init = nvenc_encode_init,
1890 .encode2 = nvenc_encode_frame,
1891 .close = nvenc_encode_close,
1892 .capabilities = AV_CODEC_CAP_DELAY,
1893 .priv_class = &nvenc_hevc_class,
1894 .defaults = nvenc_defaults,
1895 .pix_fmts = pix_fmts_nvenc,