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/internal.h"
31 #include "libavutil/imgutils.h"
32 #include "libavutil/avassert.h"
33 #include "libavutil/opt.h"
34 #include "libavutil/mem.h"
40 #define CUDAAPI __stdcall
46 #define LOAD_FUNC(l, s) GetProcAddress(l, s)
47 #define DL_CLOSE_FUNC(l) FreeLibrary(l)
49 #define LOAD_FUNC(l, s) dlsym(l, s)
50 #define DL_CLOSE_FUNC(l) dlclose(l)
53 typedef enum cudaError_enum {
57 typedef void* CUcontext;
59 typedef CUresult(CUDAAPI *PCUINIT)(unsigned int Flags);
60 typedef CUresult(CUDAAPI *PCUDEVICEGETCOUNT)(int *count);
61 typedef CUresult(CUDAAPI *PCUDEVICEGET)(CUdevice *device, int ordinal);
62 typedef CUresult(CUDAAPI *PCUDEVICEGETNAME)(char *name, int len, CUdevice dev);
63 typedef CUresult(CUDAAPI *PCUDEVICECOMPUTECAPABILITY)(int *major, int *minor, CUdevice dev);
64 typedef CUresult(CUDAAPI *PCUCTXCREATE)(CUcontext *pctx, unsigned int flags, CUdevice dev);
65 typedef CUresult(CUDAAPI *PCUCTXPOPCURRENT)(CUcontext *pctx);
66 typedef CUresult(CUDAAPI *PCUCTXDESTROY)(CUcontext ctx);
68 typedef NVENCSTATUS (NVENCAPI* PNVENCODEAPICREATEINSTANCE)(NV_ENCODE_API_FUNCTION_LIST *functionList);
70 typedef struct NvencInputSurface
72 NV_ENC_INPUT_PTR input_surface;
78 NV_ENC_BUFFER_FORMAT format;
81 typedef struct NvencOutputSurface
83 NV_ENC_OUTPUT_PTR output_surface;
86 NvencInputSurface* input_surface;
91 typedef struct NvencData
95 NvencOutputSurface *surface;
99 typedef struct NvencDataList
108 typedef struct NvencDynLoadFunctions
111 PCUDEVICEGETCOUNT cu_device_get_count;
112 PCUDEVICEGET cu_device_get;
113 PCUDEVICEGETNAME cu_device_get_name;
114 PCUDEVICECOMPUTECAPABILITY cu_device_compute_capability;
115 PCUCTXCREATE cu_ctx_create;
116 PCUCTXPOPCURRENT cu_ctx_pop_current;
117 PCUCTXDESTROY cu_ctx_destroy;
119 NV_ENCODE_API_FUNCTION_LIST nvenc_funcs;
120 int nvenc_device_count;
121 CUdevice nvenc_devices[16];
130 } NvencDynLoadFunctions;
132 typedef struct NvencValuePair
138 typedef struct NvencContext
142 NvencDynLoadFunctions nvenc_dload_funcs;
144 NV_ENC_INITIALIZE_PARAMS init_encode_params;
145 NV_ENC_CONFIG encode_config;
146 CUcontext cu_context;
148 int max_surface_count;
149 NvencInputSurface *input_surfaces;
150 NvencOutputSurface *output_surfaces;
152 NvencDataList output_surface_queue;
153 NvencDataList output_surface_ready_queue;
154 NvencDataList timestamp_list;
169 static const NvencValuePair nvenc_h264_level_pairs[] = {
170 { "auto", NV_ENC_LEVEL_AUTOSELECT },
171 { "1" , NV_ENC_LEVEL_H264_1 },
172 { "1.0" , NV_ENC_LEVEL_H264_1 },
173 { "1b" , NV_ENC_LEVEL_H264_1b },
174 { "1.0b", NV_ENC_LEVEL_H264_1b },
175 { "1.1" , NV_ENC_LEVEL_H264_11 },
176 { "1.2" , NV_ENC_LEVEL_H264_12 },
177 { "1.3" , NV_ENC_LEVEL_H264_13 },
178 { "2" , NV_ENC_LEVEL_H264_2 },
179 { "2.0" , NV_ENC_LEVEL_H264_2 },
180 { "2.1" , NV_ENC_LEVEL_H264_21 },
181 { "2.2" , NV_ENC_LEVEL_H264_22 },
182 { "3" , NV_ENC_LEVEL_H264_3 },
183 { "3.0" , NV_ENC_LEVEL_H264_3 },
184 { "3.1" , NV_ENC_LEVEL_H264_31 },
185 { "3.2" , NV_ENC_LEVEL_H264_32 },
186 { "4" , NV_ENC_LEVEL_H264_4 },
187 { "4.0" , NV_ENC_LEVEL_H264_4 },
188 { "4.1" , NV_ENC_LEVEL_H264_41 },
189 { "4.2" , NV_ENC_LEVEL_H264_42 },
190 { "5" , NV_ENC_LEVEL_H264_5 },
191 { "5.0" , NV_ENC_LEVEL_H264_5 },
192 { "5.1" , NV_ENC_LEVEL_H264_51 },
196 static const NvencValuePair nvenc_hevc_level_pairs[] = {
197 { "auto", NV_ENC_LEVEL_AUTOSELECT },
198 { "1" , NV_ENC_LEVEL_HEVC_1 },
199 { "1.0" , NV_ENC_LEVEL_HEVC_1 },
200 { "2" , NV_ENC_LEVEL_HEVC_2 },
201 { "2.0" , NV_ENC_LEVEL_HEVC_2 },
202 { "2.1" , NV_ENC_LEVEL_HEVC_21 },
203 { "3" , NV_ENC_LEVEL_HEVC_3 },
204 { "3.0" , NV_ENC_LEVEL_HEVC_3 },
205 { "3.1" , NV_ENC_LEVEL_HEVC_31 },
206 { "4" , NV_ENC_LEVEL_HEVC_4 },
207 { "4.0" , NV_ENC_LEVEL_HEVC_4 },
208 { "4.1" , NV_ENC_LEVEL_HEVC_41 },
209 { "5" , NV_ENC_LEVEL_HEVC_5 },
210 { "5.0" , NV_ENC_LEVEL_HEVC_5 },
211 { "5.1" , NV_ENC_LEVEL_HEVC_51 },
212 { "5.2" , NV_ENC_LEVEL_HEVC_52 },
213 { "6" , NV_ENC_LEVEL_HEVC_6 },
214 { "6.0" , NV_ENC_LEVEL_HEVC_6 },
215 { "6.1" , NV_ENC_LEVEL_HEVC_61 },
216 { "6.2" , NV_ENC_LEVEL_HEVC_62 },
220 static int input_string_to_uint32(AVCodecContext *avctx, const NvencValuePair *pair, const char *input, uint32_t *output)
222 for (; pair->str; ++pair) {
223 if (!strcmp(input, pair->str)) {
229 return AVERROR(EINVAL);
232 static NvencData* data_queue_dequeue(NvencDataList* queue)
238 av_assert0(queue->size);
239 av_assert0(queue->data);
244 /* Size always is a multiple of two */
245 mask = queue->size - 1;
246 read_pos = (queue->pos - queue->count) & mask;
249 return &queue->data[read_pos];
252 static int data_queue_enqueue(NvencDataList* queue, NvencData *data)
254 NvencDataList new_queue;
259 /* size always has to be a multiple of two */
264 queue->data = av_malloc(queue->size * sizeof(*(queue->data)));
268 return AVERROR(ENOMEM);
272 if (queue->count == queue->size) {
273 new_queue.size = queue->size << 1;
276 new_queue.data = av_malloc(new_queue.size * sizeof(*(queue->data)));
279 return AVERROR(ENOMEM);
281 while (tmp_data = data_queue_dequeue(queue))
282 data_queue_enqueue(&new_queue, tmp_data);
284 av_free(queue->data);
288 mask = queue->size - 1;
290 queue->data[queue->pos] = *data;
291 queue->pos = (queue->pos + 1) & mask;
297 static int out_surf_queue_enqueue(NvencDataList* queue, NvencOutputSurface* surface)
300 data.u.surface = surface;
302 return data_queue_enqueue(queue, &data);
305 static NvencOutputSurface* out_surf_queue_dequeue(NvencDataList* queue)
307 NvencData* res = data_queue_dequeue(queue);
312 return res->u.surface;
315 static int timestamp_queue_enqueue(NvencDataList* queue, int64_t timestamp)
318 data.u.timestamp = timestamp;
320 return data_queue_enqueue(queue, &data);
323 static int64_t timestamp_queue_dequeue(NvencDataList* queue)
325 NvencData* res = data_queue_dequeue(queue);
328 return AV_NOPTS_VALUE;
330 return res->u.timestamp;
333 #define CHECK_LOAD_FUNC(t, f, s) \
335 (f) = (t)LOAD_FUNC(dl_fn->cuda_lib, s); \
337 av_log(avctx, AV_LOG_FATAL, "Failed loading %s from CUDA library\n", s); \
342 static av_cold int nvenc_dyload_cuda(AVCodecContext *avctx)
344 NvencContext *ctx = avctx->priv_data;
345 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
351 dl_fn->cuda_lib = LoadLibrary(TEXT("nvcuda.dll"));
353 dl_fn->cuda_lib = dlopen("libcuda.so", RTLD_LAZY);
356 if (!dl_fn->cuda_lib) {
357 av_log(avctx, AV_LOG_FATAL, "Failed loading CUDA library\n");
361 CHECK_LOAD_FUNC(PCUINIT, dl_fn->cu_init, "cuInit");
362 CHECK_LOAD_FUNC(PCUDEVICEGETCOUNT, dl_fn->cu_device_get_count, "cuDeviceGetCount");
363 CHECK_LOAD_FUNC(PCUDEVICEGET, dl_fn->cu_device_get, "cuDeviceGet");
364 CHECK_LOAD_FUNC(PCUDEVICEGETNAME, dl_fn->cu_device_get_name, "cuDeviceGetName");
365 CHECK_LOAD_FUNC(PCUDEVICECOMPUTECAPABILITY, dl_fn->cu_device_compute_capability, "cuDeviceComputeCapability");
366 CHECK_LOAD_FUNC(PCUCTXCREATE, dl_fn->cu_ctx_create, "cuCtxCreate_v2");
367 CHECK_LOAD_FUNC(PCUCTXPOPCURRENT, dl_fn->cu_ctx_pop_current, "cuCtxPopCurrent_v2");
368 CHECK_LOAD_FUNC(PCUCTXDESTROY, dl_fn->cu_ctx_destroy, "cuCtxDestroy_v2");
375 DL_CLOSE_FUNC(dl_fn->cuda_lib);
377 dl_fn->cuda_lib = NULL;
382 static av_cold int check_cuda_errors(AVCodecContext *avctx, CUresult err, const char *func)
384 if (err != CUDA_SUCCESS) {
385 av_log(avctx, AV_LOG_FATAL, ">> %s - failed with error code 0x%x\n", func, err);
390 #define check_cuda_errors(f) if (!check_cuda_errors(avctx, f, #f)) goto error
392 static av_cold int nvenc_check_cuda(AVCodecContext *avctx)
394 int device_count = 0;
395 CUdevice cu_device = 0;
397 int smminor = 0, smmajor = 0;
398 int i, smver, target_smver;
400 NvencContext *ctx = avctx->priv_data;
401 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
403 switch (avctx->codec->id) {
404 case AV_CODEC_ID_H264:
405 target_smver = avctx->pix_fmt == AV_PIX_FMT_YUV444P ? 0x52 : 0x30;
407 case AV_CODEC_ID_H265:
411 av_log(avctx, AV_LOG_FATAL, "Unknown codec name\n");
415 if (!nvenc_dyload_cuda(avctx))
418 if (dl_fn->nvenc_device_count > 0)
421 check_cuda_errors(dl_fn->cu_init(0));
423 check_cuda_errors(dl_fn->cu_device_get_count(&device_count));
426 av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
430 av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", device_count);
432 dl_fn->nvenc_device_count = 0;
434 for (i = 0; i < device_count; ++i) {
435 check_cuda_errors(dl_fn->cu_device_get(&cu_device, i));
436 check_cuda_errors(dl_fn->cu_device_get_name(gpu_name, sizeof(gpu_name), cu_device));
437 check_cuda_errors(dl_fn->cu_device_compute_capability(&smmajor, &smminor, cu_device));
439 smver = (smmajor << 4) | smminor;
441 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");
443 if (smver >= target_smver)
444 dl_fn->nvenc_devices[dl_fn->nvenc_device_count++] = cu_device;
447 if (!dl_fn->nvenc_device_count) {
448 av_log(avctx, AV_LOG_FATAL, "No NVENC capable devices found\n");
456 dl_fn->nvenc_device_count = 0;
461 static av_cold int nvenc_dyload_nvenc(AVCodecContext *avctx)
463 PNVENCODEAPICREATEINSTANCE nvEncodeAPICreateInstance = 0;
464 NVENCSTATUS nvstatus;
466 NvencContext *ctx = avctx->priv_data;
467 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
469 if (!nvenc_check_cuda(avctx))
472 if (dl_fn->nvenc_lib)
476 if (sizeof(void*) == 8) {
477 dl_fn->nvenc_lib = LoadLibrary(TEXT("nvEncodeAPI64.dll"));
479 dl_fn->nvenc_lib = LoadLibrary(TEXT("nvEncodeAPI.dll"));
482 dl_fn->nvenc_lib = dlopen("libnvidia-encode.so.1", RTLD_LAZY);
485 if (!dl_fn->nvenc_lib) {
486 av_log(avctx, AV_LOG_FATAL, "Failed loading the nvenc library\n");
490 nvEncodeAPICreateInstance = (PNVENCODEAPICREATEINSTANCE)LOAD_FUNC(dl_fn->nvenc_lib, "NvEncodeAPICreateInstance");
492 if (!nvEncodeAPICreateInstance) {
493 av_log(avctx, AV_LOG_FATAL, "Failed to load nvenc entrypoint\n");
497 dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
499 nvstatus = nvEncodeAPICreateInstance(&dl_fn->nvenc_funcs);
501 if (nvstatus != NV_ENC_SUCCESS) {
502 av_log(avctx, AV_LOG_FATAL, "Failed to create nvenc instance\n");
506 av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
511 if (dl_fn->nvenc_lib)
512 DL_CLOSE_FUNC(dl_fn->nvenc_lib);
514 dl_fn->nvenc_lib = NULL;
519 static av_cold void nvenc_unload_nvenc(AVCodecContext *avctx)
521 NvencContext *ctx = avctx->priv_data;
522 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
524 DL_CLOSE_FUNC(dl_fn->nvenc_lib);
525 dl_fn->nvenc_lib = NULL;
527 dl_fn->nvenc_device_count = 0;
529 DL_CLOSE_FUNC(dl_fn->cuda_lib);
530 dl_fn->cuda_lib = NULL;
532 dl_fn->cu_init = NULL;
533 dl_fn->cu_device_get_count = NULL;
534 dl_fn->cu_device_get = NULL;
535 dl_fn->cu_device_get_name = NULL;
536 dl_fn->cu_device_compute_capability = NULL;
537 dl_fn->cu_ctx_create = NULL;
538 dl_fn->cu_ctx_pop_current = NULL;
539 dl_fn->cu_ctx_destroy = NULL;
541 av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
544 static av_cold int nvenc_encode_init(AVCodecContext *avctx)
546 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS encode_session_params = { 0 };
547 NV_ENC_PRESET_CONFIG preset_config = { 0 };
548 CUcontext cu_context_curr;
550 GUID encoder_preset = NV_ENC_PRESET_HQ_GUID;
552 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
553 int surfaceCount = 0;
561 NvencContext *ctx = avctx->priv_data;
562 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
563 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
565 if (!nvenc_dyload_nvenc(avctx))
566 return AVERROR_EXTERNAL;
568 ctx->last_dts = AV_NOPTS_VALUE;
570 ctx->encode_config.version = NV_ENC_CONFIG_VER;
571 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
572 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
573 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
574 encode_session_params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
575 encode_session_params.apiVersion = NVENCAPI_VERSION;
577 if (ctx->gpu >= dl_fn->nvenc_device_count) {
578 av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->gpu, dl_fn->nvenc_device_count);
579 res = AVERROR(EINVAL);
583 ctx->cu_context = NULL;
584 cu_res = dl_fn->cu_ctx_create(&ctx->cu_context, 4, dl_fn->nvenc_devices[ctx->gpu]); // CU_CTX_SCHED_BLOCKING_SYNC=4, avoid CPU spins
586 if (cu_res != CUDA_SUCCESS) {
587 av_log(avctx, AV_LOG_FATAL, "Failed creating CUDA context for NVENC: 0x%x\n", (int)cu_res);
588 res = AVERROR_EXTERNAL;
592 cu_res = dl_fn->cu_ctx_pop_current(&cu_context_curr);
594 if (cu_res != CUDA_SUCCESS) {
595 av_log(avctx, AV_LOG_FATAL, "Failed popping CUDA context: 0x%x\n", (int)cu_res);
596 res = AVERROR_EXTERNAL;
600 encode_session_params.device = ctx->cu_context;
601 encode_session_params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
603 nv_status = p_nvenc->nvEncOpenEncodeSessionEx(&encode_session_params, &ctx->nvencoder);
604 if (nv_status != NV_ENC_SUCCESS) {
605 ctx->nvencoder = NULL;
606 av_log(avctx, AV_LOG_FATAL, "OpenEncodeSessionEx failed: 0x%x\n", (int)nv_status);
607 res = AVERROR_EXTERNAL;
612 if (!strcmp(ctx->preset, "slow")) {
613 encoder_preset = NV_ENC_PRESET_HQ_GUID;
615 } else if (!strcmp(ctx->preset, "medium")) {
616 encoder_preset = NV_ENC_PRESET_HQ_GUID;
618 } else if (!strcmp(ctx->preset, "fast")) {
619 encoder_preset = NV_ENC_PRESET_HP_GUID;
621 } else if (!strcmp(ctx->preset, "hq")) {
622 encoder_preset = NV_ENC_PRESET_HQ_GUID;
623 } else if (!strcmp(ctx->preset, "hp")) {
624 encoder_preset = NV_ENC_PRESET_HP_GUID;
625 } else if (!strcmp(ctx->preset, "bd")) {
626 encoder_preset = NV_ENC_PRESET_BD_GUID;
627 } else if (!strcmp(ctx->preset, "ll")) {
628 encoder_preset = NV_ENC_PRESET_LOW_LATENCY_DEFAULT_GUID;
630 } else if (!strcmp(ctx->preset, "llhp")) {
631 encoder_preset = NV_ENC_PRESET_LOW_LATENCY_HP_GUID;
633 } else if (!strcmp(ctx->preset, "llhq")) {
634 encoder_preset = NV_ENC_PRESET_LOW_LATENCY_HQ_GUID;
636 } else if (!strcmp(ctx->preset, "lossless")) {
637 encoder_preset = NV_ENC_PRESET_LOSSLESS_DEFAULT_GUID;
639 } else if (!strcmp(ctx->preset, "losslesshp")) {
640 encoder_preset = NV_ENC_PRESET_LOSSLESS_HP_GUID;
642 } else if (!strcmp(ctx->preset, "default")) {
643 encoder_preset = NV_ENC_PRESET_DEFAULT_GUID;
645 av_log(avctx, AV_LOG_FATAL, "Preset \"%s\" is unknown! Supported presets: slow, medium, high, hp, hq, bd, ll, llhp, llhq, lossless, losslesshp, default\n", ctx->preset);
646 res = AVERROR(EINVAL);
651 if (ctx->twopass < 0) {
655 switch (avctx->codec->id) {
656 case AV_CODEC_ID_H264:
657 codec = NV_ENC_CODEC_H264_GUID;
659 case AV_CODEC_ID_H265:
660 codec = NV_ENC_CODEC_HEVC_GUID;
663 av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
664 res = AVERROR(EINVAL);
668 nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder, codec, encoder_preset, &preset_config);
669 if (nv_status != NV_ENC_SUCCESS) {
670 av_log(avctx, AV_LOG_FATAL, "GetEncodePresetConfig failed: 0x%x\n", (int)nv_status);
671 res = AVERROR_EXTERNAL;
675 ctx->init_encode_params.encodeGUID = codec;
676 ctx->init_encode_params.encodeHeight = avctx->height;
677 ctx->init_encode_params.encodeWidth = avctx->width;
679 if (avctx->sample_aspect_ratio.num && avctx->sample_aspect_ratio.den &&
680 (avctx->sample_aspect_ratio.num != 1 || avctx->sample_aspect_ratio.num != 1)) {
682 avctx->width * avctx->sample_aspect_ratio.num,
683 avctx->height * avctx->sample_aspect_ratio.den,
685 ctx->init_encode_params.darHeight = dh;
686 ctx->init_encode_params.darWidth = dw;
688 ctx->init_encode_params.darHeight = avctx->height;
689 ctx->init_encode_params.darWidth = avctx->width;
692 // De-compensate for hardware, dubiously, trying to compensate for
693 // playback at 704 pixel width.
694 if (avctx->width == 720 &&
695 (avctx->height == 480 || avctx->height == 576)) {
697 ctx->init_encode_params.darWidth * 44,
698 ctx->init_encode_params.darHeight * 45,
700 ctx->init_encode_params.darHeight = dh;
701 ctx->init_encode_params.darWidth = dw;
704 ctx->init_encode_params.frameRateNum = avctx->time_base.den;
705 ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
707 num_mbs = ((avctx->width + 15) >> 4) * ((avctx->height + 15) >> 4);
708 ctx->max_surface_count = (num_mbs >= 8160) ? 32 : 48;
710 if (ctx->buffer_delay >= ctx->max_surface_count)
711 ctx->buffer_delay = ctx->max_surface_count - 1;
713 ctx->init_encode_params.enableEncodeAsync = 0;
714 ctx->init_encode_params.enablePTD = 1;
716 ctx->init_encode_params.presetGUID = encoder_preset;
718 ctx->init_encode_params.encodeConfig = &ctx->encode_config;
719 memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
720 ctx->encode_config.version = NV_ENC_CONFIG_VER;
722 if (avctx->refs >= 0) {
723 /* 0 means "let the hardware decide" */
724 switch (avctx->codec->id) {
725 case AV_CODEC_ID_H264:
726 ctx->encode_config.encodeCodecConfig.h264Config.maxNumRefFrames = avctx->refs;
728 case AV_CODEC_ID_H265:
729 ctx->encode_config.encodeCodecConfig.hevcConfig.maxNumRefFramesInDPB = avctx->refs;
731 /* Earlier switch/case will return if unknown codec is passed. */
735 if (avctx->gop_size > 0) {
736 if (avctx->max_b_frames >= 0) {
737 /* 0 is intra-only, 1 is I/P only, 2 is one B Frame, 3 two B frames, and so on. */
738 ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
741 ctx->encode_config.gopLength = avctx->gop_size;
742 switch (avctx->codec->id) {
743 case AV_CODEC_ID_H264:
744 ctx->encode_config.encodeCodecConfig.h264Config.idrPeriod = avctx->gop_size;
745 ctx->encode_config.encodeCodecConfig.h264Config.hierarchicalPFrames = 1;
746 ctx->encode_config.encodeCodecConfig.h264Config.hierarchicalBFrames = 1;
748 case AV_CODEC_ID_H265:
749 ctx->encode_config.encodeCodecConfig.hevcConfig.idrPeriod = avctx->gop_size;
751 /* Earlier switch/case will return if unknown codec is passed. */
753 } else if (avctx->gop_size == 0) {
754 ctx->encode_config.frameIntervalP = 0;
755 ctx->encode_config.gopLength = 1;
756 switch (avctx->codec->id) {
757 case AV_CODEC_ID_H264:
758 ctx->encode_config.encodeCodecConfig.h264Config.idrPeriod = 1;
760 case AV_CODEC_ID_H265:
761 ctx->encode_config.encodeCodecConfig.hevcConfig.idrPeriod = 1;
763 /* Earlier switch/case will return if unknown codec is passed. */
767 /* when there're b frames, set dts offset */
768 if (ctx->encode_config.frameIntervalP >= 2)
771 if (avctx->bit_rate > 0)
772 ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
774 if (avctx->rc_max_rate > 0)
775 ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
778 if (avctx->codec->id == AV_CODEC_ID_H264)
779 ctx->encode_config.encodeCodecConfig.h264Config.qpPrimeYZeroTransformBypassFlag = 1;
781 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
782 ctx->encode_config.rcParams.constQP.qpInterB = 0;
783 ctx->encode_config.rcParams.constQP.qpInterP = 0;
784 ctx->encode_config.rcParams.constQP.qpIntra = 0;
788 } else if (ctx->cbr) {
790 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CBR;
792 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_2_PASS_QUALITY;
794 if (avctx->codec->id == AV_CODEC_ID_H264) {
795 ctx->encode_config.encodeCodecConfig.h264Config.adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
796 ctx->encode_config.encodeCodecConfig.h264Config.fmoMode = NV_ENC_H264_FMO_DISABLE;
799 } else if (avctx->global_quality > 0) {
800 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
801 ctx->encode_config.rcParams.constQP.qpInterB = avctx->global_quality;
802 ctx->encode_config.rcParams.constQP.qpInterP = avctx->global_quality;
803 ctx->encode_config.rcParams.constQP.qpIntra = avctx->global_quality;
808 if (avctx->qmin >= 0 && avctx->qmax >= 0) {
809 ctx->encode_config.rcParams.enableMinQP = 1;
810 ctx->encode_config.rcParams.enableMaxQP = 1;
812 ctx->encode_config.rcParams.minQP.qpInterB = avctx->qmin;
813 ctx->encode_config.rcParams.minQP.qpInterP = avctx->qmin;
814 ctx->encode_config.rcParams.minQP.qpIntra = avctx->qmin;
816 ctx->encode_config.rcParams.maxQP.qpInterB = avctx->qmax;
817 ctx->encode_config.rcParams.maxQP.qpInterP = avctx->qmax;
818 ctx->encode_config.rcParams.maxQP.qpIntra = avctx->qmax;
820 qp_inter_p = (avctx->qmax + 3 * avctx->qmin) / 4; // biased towards Qmin
823 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_2_PASS_VBR;
824 if (avctx->codec->id == AV_CODEC_ID_H264) {
825 ctx->encode_config.encodeCodecConfig.h264Config.adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
826 ctx->encode_config.encodeCodecConfig.h264Config.fmoMode = NV_ENC_H264_FMO_DISABLE;
829 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR_MINQP;
832 qp_inter_p = 26; // default to 26
835 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_2_PASS_VBR;
837 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
841 ctx->encode_config.rcParams.enableInitialRCQP = 1;
842 ctx->encode_config.rcParams.initialRCQP.qpInterP = qp_inter_p;
844 if(avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
845 ctx->encode_config.rcParams.initialRCQP.qpIntra = qp_inter_p * fabs(avctx->i_quant_factor);
846 ctx->encode_config.rcParams.initialRCQP.qpIntra += qp_inter_p * avctx->i_quant_offset;
847 ctx->encode_config.rcParams.initialRCQP.qpInterB = qp_inter_p * fabs(avctx->b_quant_factor);
848 ctx->encode_config.rcParams.initialRCQP.qpInterB += qp_inter_p * avctx->b_quant_offset;
850 ctx->encode_config.rcParams.initialRCQP.qpIntra = qp_inter_p;
851 ctx->encode_config.rcParams.initialRCQP.qpInterB = qp_inter_p;
855 if (avctx->rc_buffer_size > 0)
856 ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
858 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
859 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
861 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
864 switch (avctx->codec->id) {
865 case AV_CODEC_ID_H264:
866 ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.colourDescriptionPresentFlag = 1;
867 ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.videoSignalTypePresentFlag = 1;
869 ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.colourMatrix = avctx->colorspace;
870 ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.colourPrimaries = avctx->color_primaries;
871 ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.transferCharacteristics = avctx->color_trc;
873 ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.videoFullRangeFlag = avctx->color_range == AVCOL_RANGE_JPEG;
875 ctx->encode_config.encodeCodecConfig.h264Config.disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
876 ctx->encode_config.encodeCodecConfig.h264Config.repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
879 switch (avctx->profile) {
880 case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
881 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
883 case FF_PROFILE_H264_BASELINE:
884 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
886 case FF_PROFILE_H264_MAIN:
887 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
889 case FF_PROFILE_H264_HIGH:
890 case FF_PROFILE_UNKNOWN:
891 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
894 av_log(avctx, AV_LOG_WARNING, "Unsupported profile requested, falling back to high\n");
895 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
899 if (!strcmp(ctx->profile, "high")) {
900 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
901 avctx->profile = FF_PROFILE_H264_HIGH;
902 } else if (!strcmp(ctx->profile, "main")) {
903 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
904 avctx->profile = FF_PROFILE_H264_MAIN;
905 } else if (!strcmp(ctx->profile, "baseline")) {
906 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
907 avctx->profile = FF_PROFILE_H264_BASELINE;
908 } else if (!strcmp(ctx->profile, "high444p")) {
909 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
910 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
912 av_log(avctx, AV_LOG_FATAL, "Profile \"%s\" is unknown! Supported profiles: high, main, baseline\n", ctx->profile);
913 res = AVERROR(EINVAL);
918 ctx->encode_config.encodeCodecConfig.h264Config.chromaFormatIDC = avctx->profile == FF_PROFILE_H264_HIGH_444_PREDICTIVE ? 3 : 1;
921 res = input_string_to_uint32(avctx, nvenc_h264_level_pairs, ctx->level, &ctx->encode_config.encodeCodecConfig.h264Config.level);
924 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);
928 ctx->encode_config.encodeCodecConfig.h264Config.level = NV_ENC_LEVEL_AUTOSELECT;
932 case AV_CODEC_ID_H265:
933 ctx->encode_config.encodeCodecConfig.hevcConfig.disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
934 ctx->encode_config.encodeCodecConfig.hevcConfig.repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
936 /* No other profile is supported in the current SDK version 5 */
937 ctx->encode_config.profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
938 avctx->profile = FF_PROFILE_HEVC_MAIN;
941 res = input_string_to_uint32(avctx, nvenc_hevc_level_pairs, ctx->level, &ctx->encode_config.encodeCodecConfig.hevcConfig.level);
944 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);
948 ctx->encode_config.encodeCodecConfig.hevcConfig.level = NV_ENC_LEVEL_AUTOSELECT;
952 if (!strcmp(ctx->tier, "main")) {
953 ctx->encode_config.encodeCodecConfig.hevcConfig.tier = NV_ENC_TIER_HEVC_MAIN;
954 } else if (!strcmp(ctx->tier, "high")) {
955 ctx->encode_config.encodeCodecConfig.hevcConfig.tier = NV_ENC_TIER_HEVC_HIGH;
957 av_log(avctx, AV_LOG_FATAL, "Tier \"%s\" is unknown! Supported tiers: main, high\n", ctx->tier);
958 res = AVERROR(EINVAL);
964 /* Earlier switch/case will return if unknown codec is passed. */
967 nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
968 if (nv_status != NV_ENC_SUCCESS) {
969 av_log(avctx, AV_LOG_FATAL, "InitializeEncoder failed: 0x%x\n", (int)nv_status);
970 res = AVERROR_EXTERNAL;
974 ctx->input_surfaces = av_malloc(ctx->max_surface_count * sizeof(*ctx->input_surfaces));
976 if (!ctx->input_surfaces) {
977 res = AVERROR(ENOMEM);
981 ctx->output_surfaces = av_malloc(ctx->max_surface_count * sizeof(*ctx->output_surfaces));
983 if (!ctx->output_surfaces) {
984 res = AVERROR(ENOMEM);
988 for (surfaceCount = 0; surfaceCount < ctx->max_surface_count; ++surfaceCount) {
989 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
990 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
991 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
992 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
994 allocSurf.width = (avctx->width + 31) & ~31;
995 allocSurf.height = (avctx->height + 31) & ~31;
997 allocSurf.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
999 switch (avctx->pix_fmt) {
1000 case AV_PIX_FMT_YUV420P:
1001 allocSurf.bufferFmt = NV_ENC_BUFFER_FORMAT_YV12_PL;
1004 case AV_PIX_FMT_NV12:
1005 allocSurf.bufferFmt = NV_ENC_BUFFER_FORMAT_NV12_PL;
1008 case AV_PIX_FMT_YUV444P:
1009 allocSurf.bufferFmt = NV_ENC_BUFFER_FORMAT_YUV444_PL;
1013 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format\n");
1014 res = AVERROR(EINVAL);
1018 nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
1019 if (nv_status != NV_ENC_SUCCESS) {
1020 av_log(avctx, AV_LOG_FATAL, "CreateInputBuffer failed\n");
1021 res = AVERROR_EXTERNAL;
1025 ctx->input_surfaces[surfaceCount].lockCount = 0;
1026 ctx->input_surfaces[surfaceCount].input_surface = allocSurf.inputBuffer;
1027 ctx->input_surfaces[surfaceCount].format = allocSurf.bufferFmt;
1028 ctx->input_surfaces[surfaceCount].width = allocSurf.width;
1029 ctx->input_surfaces[surfaceCount].height = allocSurf.height;
1031 /* 1MB is large enough to hold most output frames. NVENC increases this automaticaly if it's not enough. */
1032 allocOut.size = 1024 * 1024;
1034 allocOut.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
1036 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
1037 if (nv_status != NV_ENC_SUCCESS) {
1038 av_log(avctx, AV_LOG_FATAL, "CreateBitstreamBuffer failed\n");
1039 ctx->output_surfaces[surfaceCount++].output_surface = NULL;
1040 res = AVERROR_EXTERNAL;
1044 ctx->output_surfaces[surfaceCount].output_surface = allocOut.bitstreamBuffer;
1045 ctx->output_surfaces[surfaceCount].size = allocOut.size;
1046 ctx->output_surfaces[surfaceCount].busy = 0;
1049 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1050 uint32_t outSize = 0;
1051 char tmpHeader[256];
1052 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1053 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1055 payload.spsppsBuffer = tmpHeader;
1056 payload.inBufferSize = sizeof(tmpHeader);
1057 payload.outSPSPPSPayloadSize = &outSize;
1059 nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
1060 if (nv_status != NV_ENC_SUCCESS) {
1061 av_log(avctx, AV_LOG_FATAL, "GetSequenceParams failed\n");
1065 avctx->extradata_size = outSize;
1066 avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
1068 if (!avctx->extradata) {
1069 res = AVERROR(ENOMEM);
1073 memcpy(avctx->extradata, tmpHeader, outSize);
1076 if (ctx->encode_config.frameIntervalP > 1)
1077 avctx->has_b_frames = 2;
1079 if (ctx->encode_config.rcParams.averageBitRate > 0)
1080 avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
1086 for (i = 0; i < surfaceCount; ++i) {
1087 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->input_surfaces[i].input_surface);
1088 if (ctx->output_surfaces[i].output_surface)
1089 p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->output_surfaces[i].output_surface);
1093 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1095 if (ctx->cu_context)
1096 dl_fn->cu_ctx_destroy(ctx->cu_context);
1098 nvenc_unload_nvenc(avctx);
1100 ctx->nvencoder = NULL;
1101 ctx->cu_context = NULL;
1106 static av_cold int nvenc_encode_close(AVCodecContext *avctx)
1108 NvencContext *ctx = avctx->priv_data;
1109 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1110 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1113 av_freep(&ctx->timestamp_list.data);
1114 av_freep(&ctx->output_surface_ready_queue.data);
1115 av_freep(&ctx->output_surface_queue.data);
1117 for (i = 0; i < ctx->max_surface_count; ++i) {
1118 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->input_surfaces[i].input_surface);
1119 p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->output_surfaces[i].output_surface);
1121 ctx->max_surface_count = 0;
1123 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1124 ctx->nvencoder = NULL;
1126 dl_fn->cu_ctx_destroy(ctx->cu_context);
1127 ctx->cu_context = NULL;
1129 nvenc_unload_nvenc(avctx);
1134 static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencOutputSurface *tmpoutsurf)
1136 NvencContext *ctx = avctx->priv_data;
1137 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1138 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1140 uint32_t slice_mode_data;
1141 uint32_t *slice_offsets;
1142 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1143 NVENCSTATUS nv_status;
1146 switch (avctx->codec->id) {
1147 case AV_CODEC_ID_H264:
1148 slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1150 case AV_CODEC_ID_H265:
1151 slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1154 av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
1155 res = AVERROR(EINVAL);
1158 slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
1161 return AVERROR(ENOMEM);
1163 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1165 lock_params.doNotWait = 0;
1166 lock_params.outputBitstream = tmpoutsurf->output_surface;
1167 lock_params.sliceOffsets = slice_offsets;
1169 nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
1170 if (nv_status != NV_ENC_SUCCESS) {
1171 av_log(avctx, AV_LOG_ERROR, "Failed locking bitstream buffer\n");
1172 res = AVERROR_EXTERNAL;
1176 if (res = ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes,0)) {
1177 p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1181 memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1183 nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1184 if (nv_status != NV_ENC_SUCCESS)
1185 av_log(avctx, AV_LOG_ERROR, "Failed unlocking bitstream buffer, expect the gates of mordor to open\n");
1187 switch (lock_params.pictureType) {
1188 case NV_ENC_PIC_TYPE_IDR:
1189 pkt->flags |= AV_PKT_FLAG_KEY;
1190 #if FF_API_CODED_FRAME
1191 FF_DISABLE_DEPRECATION_WARNINGS
1192 case NV_ENC_PIC_TYPE_I:
1193 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
1195 case NV_ENC_PIC_TYPE_P:
1196 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
1198 case NV_ENC_PIC_TYPE_B:
1199 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;
1201 case NV_ENC_PIC_TYPE_BI:
1202 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_BI;
1205 av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
1206 av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
1207 res = AVERROR_EXTERNAL;
1209 FF_ENABLE_DEPRECATION_WARNINGS
1213 pkt->pts = lock_params.outputTimeStamp;
1214 pkt->dts = timestamp_queue_dequeue(&ctx->timestamp_list);
1216 /* when there're b frame(s), set dts offset */
1217 if (ctx->encode_config.frameIntervalP >= 2)
1220 if (pkt->dts > pkt->pts)
1221 pkt->dts = pkt->pts;
1223 if (ctx->last_dts != AV_NOPTS_VALUE && pkt->dts <= ctx->last_dts)
1224 pkt->dts = ctx->last_dts + 1;
1226 ctx->last_dts = pkt->dts;
1228 av_free(slice_offsets);
1234 av_free(slice_offsets);
1235 timestamp_queue_dequeue(&ctx->timestamp_list);
1240 static int nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1241 const AVFrame *frame, int *got_packet)
1243 NVENCSTATUS nv_status;
1244 NvencOutputSurface *tmpoutsurf;
1247 NvencContext *ctx = avctx->priv_data;
1248 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1249 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1251 NV_ENC_PIC_PARAMS pic_params = { 0 };
1252 pic_params.version = NV_ENC_PIC_PARAMS_VER;
1255 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1256 NvencInputSurface *inSurf = NULL;
1258 for (i = 0; i < ctx->max_surface_count; ++i) {
1259 if (!ctx->input_surfaces[i].lockCount) {
1260 inSurf = &ctx->input_surfaces[i];
1267 inSurf->lockCount = 1;
1269 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1270 lockBufferParams.inputBuffer = inSurf->input_surface;
1272 nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
1273 if (nv_status != NV_ENC_SUCCESS) {
1274 av_log(avctx, AV_LOG_ERROR, "Failed locking nvenc input buffer\n");
1278 if (avctx->pix_fmt == AV_PIX_FMT_YUV420P) {
1279 uint8_t *buf = lockBufferParams.bufferDataPtr;
1281 av_image_copy_plane(buf, lockBufferParams.pitch,
1282 frame->data[0], frame->linesize[0],
1283 avctx->width, avctx->height);
1285 buf += inSurf->height * lockBufferParams.pitch;
1287 av_image_copy_plane(buf, lockBufferParams.pitch >> 1,
1288 frame->data[2], frame->linesize[2],
1289 avctx->width >> 1, avctx->height >> 1);
1291 buf += (inSurf->height * lockBufferParams.pitch) >> 2;
1293 av_image_copy_plane(buf, lockBufferParams.pitch >> 1,
1294 frame->data[1], frame->linesize[1],
1295 avctx->width >> 1, avctx->height >> 1);
1296 } else if (avctx->pix_fmt == AV_PIX_FMT_NV12) {
1297 uint8_t *buf = lockBufferParams.bufferDataPtr;
1299 av_image_copy_plane(buf, lockBufferParams.pitch,
1300 frame->data[0], frame->linesize[0],
1301 avctx->width, avctx->height);
1303 buf += inSurf->height * lockBufferParams.pitch;
1305 av_image_copy_plane(buf, lockBufferParams.pitch,
1306 frame->data[1], frame->linesize[1],
1307 avctx->width, avctx->height >> 1);
1308 } else if (avctx->pix_fmt == AV_PIX_FMT_YUV444P) {
1309 uint8_t *buf = lockBufferParams.bufferDataPtr;
1311 av_image_copy_plane(buf, lockBufferParams.pitch,
1312 frame->data[0], frame->linesize[0],
1313 avctx->width, avctx->height);
1315 buf += inSurf->height * lockBufferParams.pitch;
1317 av_image_copy_plane(buf, lockBufferParams.pitch,
1318 frame->data[1], frame->linesize[1],
1319 avctx->width, avctx->height);
1321 buf += inSurf->height * lockBufferParams.pitch;
1323 av_image_copy_plane(buf, lockBufferParams.pitch,
1324 frame->data[2], frame->linesize[2],
1325 avctx->width, avctx->height);
1327 av_log(avctx, AV_LOG_FATAL, "Invalid pixel format!\n");
1328 return AVERROR(EINVAL);
1331 nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, inSurf->input_surface);
1332 if (nv_status != NV_ENC_SUCCESS) {
1333 av_log(avctx, AV_LOG_FATAL, "Failed unlocking input buffer!\n");
1334 return AVERROR_EXTERNAL;
1337 for (i = 0; i < ctx->max_surface_count; ++i)
1338 if (!ctx->output_surfaces[i].busy)
1341 if (i == ctx->max_surface_count) {
1342 inSurf->lockCount = 0;
1343 av_log(avctx, AV_LOG_FATAL, "No free output surface found!\n");
1344 return AVERROR_EXTERNAL;
1347 ctx->output_surfaces[i].input_surface = inSurf;
1349 pic_params.inputBuffer = inSurf->input_surface;
1350 pic_params.bufferFmt = inSurf->format;
1351 pic_params.inputWidth = avctx->width;
1352 pic_params.inputHeight = avctx->height;
1353 pic_params.outputBitstream = ctx->output_surfaces[i].output_surface;
1354 pic_params.completionEvent = 0;
1356 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1357 if (frame->top_field_first) {
1358 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
1360 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
1363 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1366 pic_params.encodePicFlags = 0;
1367 pic_params.inputTimeStamp = frame->pts;
1368 pic_params.inputDuration = 0;
1369 switch (avctx->codec->id) {
1370 case AV_CODEC_ID_H264:
1371 pic_params.codecPicParams.h264PicParams.sliceMode = ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1372 pic_params.codecPicParams.h264PicParams.sliceModeData = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1374 case AV_CODEC_ID_H265:
1375 pic_params.codecPicParams.hevcPicParams.sliceMode = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1376 pic_params.codecPicParams.hevcPicParams.sliceModeData = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1379 av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
1380 return AVERROR(EINVAL);
1383 res = timestamp_queue_enqueue(&ctx->timestamp_list, frame->pts);
1388 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1391 nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
1393 if (frame && nv_status == NV_ENC_ERR_NEED_MORE_INPUT) {
1394 res = out_surf_queue_enqueue(&ctx->output_surface_queue, &ctx->output_surfaces[i]);
1399 ctx->output_surfaces[i].busy = 1;
1402 if (nv_status != NV_ENC_SUCCESS && nv_status != NV_ENC_ERR_NEED_MORE_INPUT) {
1403 av_log(avctx, AV_LOG_ERROR, "EncodePicture failed!\n");
1404 return AVERROR_EXTERNAL;
1407 if (nv_status != NV_ENC_ERR_NEED_MORE_INPUT) {
1408 while (ctx->output_surface_queue.count) {
1409 tmpoutsurf = out_surf_queue_dequeue(&ctx->output_surface_queue);
1410 res = out_surf_queue_enqueue(&ctx->output_surface_ready_queue, tmpoutsurf);
1417 res = out_surf_queue_enqueue(&ctx->output_surface_ready_queue, &ctx->output_surfaces[i]);
1422 ctx->output_surfaces[i].busy = 1;
1426 if (ctx->output_surface_ready_queue.count && (!frame || ctx->output_surface_ready_queue.count + ctx->output_surface_queue.count >= ctx->buffer_delay)) {
1427 tmpoutsurf = out_surf_queue_dequeue(&ctx->output_surface_ready_queue);
1429 res = process_output_surface(avctx, pkt, tmpoutsurf);
1434 tmpoutsurf->busy = 0;
1435 av_assert0(tmpoutsurf->input_surface->lockCount);
1436 tmpoutsurf->input_surface->lockCount--;
1446 static const enum AVPixelFormat pix_fmts_nvenc[] = {
1453 #define OFFSET(x) offsetof(NvencContext, x)
1454 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
1455 static const AVOption options[] = {
1456 { "preset", "Set the encoding preset (one of slow = hq 2pass, medium = hq, fast = hp, hq, hp, bd, ll, llhq, llhp, default)", OFFSET(preset), AV_OPT_TYPE_STRING, { .str = "hq" }, 0, 0, VE },
1457 { "profile", "Set the encoding profile (high, main or baseline)", OFFSET(profile), AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE },
1458 { "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, { 0 }, 0, 0, VE },
1459 { "tier", "Set the encoding tier (main or high)", OFFSET(tier), AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE },
1460 { "cbr", "Use cbr encoding mode", OFFSET(cbr), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
1461 { "2pass", "Use 2pass encoding mode", OFFSET(twopass), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, VE },
1462 { "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 },
1463 { "delay", "Delays frame output by the given amount of frames.", OFFSET(buffer_delay), AV_OPT_TYPE_INT, { .i64 = INT_MAX }, 0, INT_MAX, VE },
1467 static const AVCodecDefault nvenc_defaults[] = {
1477 #if CONFIG_NVENC_ENCODER
1478 static const AVClass nvenc_class = {
1479 .class_name = "nvenc",
1480 .item_name = av_default_item_name,
1482 .version = LIBAVUTIL_VERSION_INT,
1485 AVCodec ff_nvenc_encoder = {
1487 .long_name = NULL_IF_CONFIG_SMALL("NVIDIA NVENC h264 encoder"),
1488 .type = AVMEDIA_TYPE_VIDEO,
1489 .id = AV_CODEC_ID_H264,
1490 .priv_data_size = sizeof(NvencContext),
1491 .init = nvenc_encode_init,
1492 .encode2 = nvenc_encode_frame,
1493 .close = nvenc_encode_close,
1494 .capabilities = AV_CODEC_CAP_DELAY,
1495 .priv_class = &nvenc_class,
1496 .defaults = nvenc_defaults,
1497 .pix_fmts = pix_fmts_nvenc,
1501 /* Add an alias for nvenc_h264 */
1502 #if CONFIG_NVENC_H264_ENCODER
1503 static const AVClass nvenc_h264_class = {
1504 .class_name = "nvenc_h264",
1505 .item_name = av_default_item_name,
1507 .version = LIBAVUTIL_VERSION_INT,
1510 AVCodec ff_nvenc_h264_encoder = {
1511 .name = "nvenc_h264",
1512 .long_name = NULL_IF_CONFIG_SMALL("NVIDIA NVENC h264 encoder"),
1513 .type = AVMEDIA_TYPE_VIDEO,
1514 .id = AV_CODEC_ID_H264,
1515 .priv_data_size = sizeof(NvencContext),
1516 .init = nvenc_encode_init,
1517 .encode2 = nvenc_encode_frame,
1518 .close = nvenc_encode_close,
1519 .capabilities = AV_CODEC_CAP_DELAY,
1520 .priv_class = &nvenc_h264_class,
1521 .defaults = nvenc_defaults,
1522 .pix_fmts = pix_fmts_nvenc,
1526 #if CONFIG_NVENC_HEVC_ENCODER
1527 static const AVClass nvenc_hevc_class = {
1528 .class_name = "nvenc_hevc",
1529 .item_name = av_default_item_name,
1531 .version = LIBAVUTIL_VERSION_INT,
1534 AVCodec ff_nvenc_hevc_encoder = {
1535 .name = "nvenc_hevc",
1536 .long_name = NULL_IF_CONFIG_SMALL("NVIDIA NVENC hevc encoder"),
1537 .type = AVMEDIA_TYPE_VIDEO,
1538 .id = AV_CODEC_ID_H265,
1539 .priv_data_size = sizeof(NvencContext),
1540 .init = nvenc_encode_init,
1541 .encode2 = nvenc_encode_frame,
1542 .close = nvenc_encode_close,
1543 .capabilities = AV_CODEC_CAP_DELAY,
1544 .priv_class = &nvenc_hevc_class,
1545 .defaults = nvenc_defaults,
1546 .pix_fmts = pix_fmts_nvenc,