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 static const GUID dummy_license = { 0x0, 0x0, 0x0, { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 } };
72 typedef struct NvencInputSurface
74 NV_ENC_INPUT_PTR input_surface;
80 NV_ENC_BUFFER_FORMAT format;
83 typedef struct NvencOutputSurface
85 NV_ENC_OUTPUT_PTR output_surface;
88 NvencInputSurface* input_surface;
93 typedef struct NvencData
97 NvencOutputSurface *surface;
101 typedef struct NvencDataList
110 typedef struct NvencDynLoadFunctions
113 PCUDEVICEGETCOUNT cu_device_get_count;
114 PCUDEVICEGET cu_device_get;
115 PCUDEVICEGETNAME cu_device_get_name;
116 PCUDEVICECOMPUTECAPABILITY cu_device_compute_capability;
117 PCUCTXCREATE cu_ctx_create;
118 PCUCTXPOPCURRENT cu_ctx_pop_current;
119 PCUCTXDESTROY cu_ctx_destroy;
121 NV_ENCODE_API_FUNCTION_LIST nvenc_funcs;
122 int nvenc_device_count;
123 CUdevice nvenc_devices[16];
132 } NvencDynLoadFunctions;
134 typedef struct NvencContext
138 NvencDynLoadFunctions nvenc_dload_funcs;
140 NV_ENC_INITIALIZE_PARAMS init_encode_params;
141 NV_ENC_CONFIG encode_config;
142 CUcontext cu_context;
144 int max_surface_count;
145 NvencInputSurface *input_surfaces;
146 NvencOutputSurface *output_surfaces;
148 NvencDataList output_surface_queue;
149 NvencDataList output_surface_ready_queue;
150 NvencDataList timestamp_list;
162 static NvencData* data_queue_dequeue(NvencDataList* queue)
168 av_assert0(queue->size);
169 av_assert0(queue->data);
174 /* Size always is a multiple of two */
175 mask = queue->size - 1;
176 read_pos = (queue->pos - queue->count) & mask;
179 return &queue->data[read_pos];
182 static int data_queue_enqueue(NvencDataList* queue, NvencData *data)
184 NvencDataList new_queue;
189 /* size always has to be a multiple of two */
194 queue->data = av_malloc(queue->size * sizeof(*(queue->data)));
198 return AVERROR(ENOMEM);
202 if (queue->count == queue->size) {
203 new_queue.size = queue->size << 1;
206 new_queue.data = av_malloc(new_queue.size * sizeof(*(queue->data)));
209 return AVERROR(ENOMEM);
211 while (tmp_data = data_queue_dequeue(queue))
212 data_queue_enqueue(&new_queue, tmp_data);
214 av_free(queue->data);
218 mask = queue->size - 1;
220 queue->data[queue->pos] = *data;
221 queue->pos = (queue->pos + 1) & mask;
227 static int out_surf_queue_enqueue(NvencDataList* queue, NvencOutputSurface* surface)
230 data.surface = surface;
232 return data_queue_enqueue(queue, &data);
235 static NvencOutputSurface* out_surf_queue_dequeue(NvencDataList* queue)
237 NvencData* res = data_queue_dequeue(queue);
245 static int timestamp_queue_enqueue(NvencDataList* queue, int64_t timestamp)
248 data.timestamp = timestamp;
250 return data_queue_enqueue(queue, &data);
253 static int64_t timestamp_queue_dequeue(NvencDataList* queue)
255 NvencData* res = data_queue_dequeue(queue);
258 return AV_NOPTS_VALUE;
260 return res->timestamp;
263 #define CHECK_LOAD_FUNC(t, f, s) \
265 (f) = (t)LOAD_FUNC(dl_fn->cuda_lib, s); \
267 av_log(avctx, AV_LOG_FATAL, "Failed loading %s from CUDA library\n", s); \
272 static av_cold int nvenc_dyload_cuda(AVCodecContext *avctx)
274 NvencContext *ctx = avctx->priv_data;
275 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
281 dl_fn->cuda_lib = LoadLibrary(TEXT("nvcuda.dll"));
283 dl_fn->cuda_lib = dlopen("libcuda.so", RTLD_LAZY);
286 if (!dl_fn->cuda_lib) {
287 av_log(avctx, AV_LOG_FATAL, "Failed loading CUDA library\n");
291 CHECK_LOAD_FUNC(PCUINIT, dl_fn->cu_init, "cuInit");
292 CHECK_LOAD_FUNC(PCUDEVICEGETCOUNT, dl_fn->cu_device_get_count, "cuDeviceGetCount");
293 CHECK_LOAD_FUNC(PCUDEVICEGET, dl_fn->cu_device_get, "cuDeviceGet");
294 CHECK_LOAD_FUNC(PCUDEVICEGETNAME, dl_fn->cu_device_get_name, "cuDeviceGetName");
295 CHECK_LOAD_FUNC(PCUDEVICECOMPUTECAPABILITY, dl_fn->cu_device_compute_capability, "cuDeviceComputeCapability");
296 CHECK_LOAD_FUNC(PCUCTXCREATE, dl_fn->cu_ctx_create, "cuCtxCreate_v2");
297 CHECK_LOAD_FUNC(PCUCTXPOPCURRENT, dl_fn->cu_ctx_pop_current, "cuCtxPopCurrent_v2");
298 CHECK_LOAD_FUNC(PCUCTXDESTROY, dl_fn->cu_ctx_destroy, "cuCtxDestroy_v2");
305 DL_CLOSE_FUNC(dl_fn->cuda_lib);
307 dl_fn->cuda_lib = NULL;
312 static av_cold int check_cuda_errors(AVCodecContext *avctx, CUresult err, const char *func)
314 if (err != CUDA_SUCCESS) {
315 av_log(avctx, AV_LOG_FATAL, ">> %s - failed with error code 0x%x\n", func, err);
320 #define check_cuda_errors(f) if (!check_cuda_errors(avctx, f, #f)) goto error
322 static av_cold int nvenc_check_cuda(AVCodecContext *avctx)
324 int device_count = 0;
325 CUdevice cu_device = 0;
327 int smminor = 0, smmajor = 0;
330 NvencContext *ctx = avctx->priv_data;
331 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
333 if (!nvenc_dyload_cuda(avctx))
336 if (dl_fn->nvenc_device_count > 0)
339 check_cuda_errors(dl_fn->cu_init(0));
341 check_cuda_errors(dl_fn->cu_device_get_count(&device_count));
344 av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
348 av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", device_count);
350 dl_fn->nvenc_device_count = 0;
352 for (i = 0; i < device_count; ++i) {
353 check_cuda_errors(dl_fn->cu_device_get(&cu_device, i));
354 check_cuda_errors(dl_fn->cu_device_get_name(gpu_name, sizeof(gpu_name), cu_device));
355 check_cuda_errors(dl_fn->cu_device_compute_capability(&smmajor, &smminor, cu_device));
357 smver = (smmajor << 4) | smminor;
359 av_log(avctx, AV_LOG_VERBOSE, "[ GPU #%d - < %s > has Compute SM %d.%d, NVENC %s ]\n", i, gpu_name, smmajor, smminor, (smver >= 0x30) ? "Available" : "Not Available");
362 dl_fn->nvenc_devices[dl_fn->nvenc_device_count++] = cu_device;
365 if (!dl_fn->nvenc_device_count) {
366 av_log(avctx, AV_LOG_FATAL, "No NVENC capable devices found\n");
374 dl_fn->nvenc_device_count = 0;
379 static av_cold int nvenc_dyload_nvenc(AVCodecContext *avctx)
381 PNVENCODEAPICREATEINSTANCE nvEncodeAPICreateInstance = 0;
382 NVENCSTATUS nvstatus;
384 NvencContext *ctx = avctx->priv_data;
385 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
387 if (!nvenc_check_cuda(avctx))
390 if (dl_fn->nvenc_lib)
394 if (sizeof(void*) == 8) {
395 dl_fn->nvenc_lib = LoadLibrary(TEXT("nvEncodeAPI64.dll"));
397 dl_fn->nvenc_lib = LoadLibrary(TEXT("nvEncodeAPI.dll"));
400 dl_fn->nvenc_lib = dlopen("libnvidia-encode.so.1", RTLD_LAZY);
403 if (!dl_fn->nvenc_lib) {
404 av_log(avctx, AV_LOG_FATAL, "Failed loading the nvenc library\n");
408 nvEncodeAPICreateInstance = (PNVENCODEAPICREATEINSTANCE)LOAD_FUNC(dl_fn->nvenc_lib, "NvEncodeAPICreateInstance");
410 if (!nvEncodeAPICreateInstance) {
411 av_log(avctx, AV_LOG_FATAL, "Failed to load nvenc entrypoint\n");
415 dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
417 nvstatus = nvEncodeAPICreateInstance(&dl_fn->nvenc_funcs);
419 if (nvstatus != NV_ENC_SUCCESS) {
420 av_log(avctx, AV_LOG_FATAL, "Failed to create nvenc instance\n");
424 av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
429 if (dl_fn->nvenc_lib)
430 DL_CLOSE_FUNC(dl_fn->nvenc_lib);
432 dl_fn->nvenc_lib = NULL;
437 static av_cold void nvenc_unload_nvenc(AVCodecContext *avctx)
439 NvencContext *ctx = avctx->priv_data;
440 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
442 DL_CLOSE_FUNC(dl_fn->nvenc_lib);
443 dl_fn->nvenc_lib = NULL;
445 dl_fn->nvenc_device_count = 0;
447 DL_CLOSE_FUNC(dl_fn->cuda_lib);
448 dl_fn->cuda_lib = NULL;
450 dl_fn->cu_init = NULL;
451 dl_fn->cu_device_get_count = NULL;
452 dl_fn->cu_device_get = NULL;
453 dl_fn->cu_device_get_name = NULL;
454 dl_fn->cu_device_compute_capability = NULL;
455 dl_fn->cu_ctx_create = NULL;
456 dl_fn->cu_ctx_pop_current = NULL;
457 dl_fn->cu_ctx_destroy = NULL;
459 av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
462 static av_cold int nvenc_encode_init(AVCodecContext *avctx)
464 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS encode_session_params = { 0 };
465 NV_ENC_PRESET_CONFIG preset_config = { 0 };
466 CUcontext cu_context_curr;
468 GUID encoder_preset = NV_ENC_PRESET_HQ_GUID;
469 GUID license = dummy_license;
470 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
471 int surfaceCount = 0;
476 NvencContext *ctx = avctx->priv_data;
477 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
478 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
480 if (!nvenc_dyload_nvenc(avctx))
481 return AVERROR_EXTERNAL;
483 avctx->coded_frame = av_frame_alloc();
484 if (!avctx->coded_frame) {
485 res = AVERROR(ENOMEM);
489 ctx->last_dts = AV_NOPTS_VALUE;
491 ctx->encode_config.version = NV_ENC_CONFIG_VER;
492 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
493 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
494 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
495 encode_session_params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
496 encode_session_params.apiVersion = NVENCAPI_VERSION;
497 encode_session_params.clientKeyPtr = &license;
499 if (ctx->gpu >= dl_fn->nvenc_device_count) {
500 av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->gpu, dl_fn->nvenc_device_count);
501 res = AVERROR(EINVAL);
505 ctx->cu_context = NULL;
506 cu_res = dl_fn->cu_ctx_create(&ctx->cu_context, 0, dl_fn->nvenc_devices[ctx->gpu]);
508 if (cu_res != CUDA_SUCCESS) {
509 av_log(avctx, AV_LOG_FATAL, "Failed creating CUDA context for NVENC: 0x%x\n", (int)cu_res);
510 res = AVERROR_EXTERNAL;
514 cu_res = dl_fn->cu_ctx_pop_current(&cu_context_curr);
516 if (cu_res != CUDA_SUCCESS) {
517 av_log(avctx, AV_LOG_FATAL, "Failed popping CUDA context: 0x%x\n", (int)cu_res);
518 res = AVERROR_EXTERNAL;
522 encode_session_params.device = ctx->cu_context;
523 encode_session_params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
525 nv_status = p_nvenc->nvEncOpenEncodeSessionEx(&encode_session_params, &ctx->nvencoder);
526 if (nv_status != NV_ENC_SUCCESS) {
527 ctx->nvencoder = NULL;
528 av_log(avctx, AV_LOG_FATAL, "OpenEncodeSessionEx failed: 0x%x - invalid license key?\n", (int)nv_status);
529 res = AVERROR_EXTERNAL;
534 if (!strcmp(ctx->preset, "hp")) {
535 encoder_preset = NV_ENC_PRESET_HP_GUID;
536 } else if (!strcmp(ctx->preset, "hq")) {
537 encoder_preset = NV_ENC_PRESET_HQ_GUID;
538 } else if (!strcmp(ctx->preset, "bd")) {
539 encoder_preset = NV_ENC_PRESET_BD_GUID;
540 } else if (!strcmp(ctx->preset, "ll")) {
541 encoder_preset = NV_ENC_PRESET_LOW_LATENCY_DEFAULT_GUID;
543 } else if (!strcmp(ctx->preset, "llhp")) {
544 encoder_preset = NV_ENC_PRESET_LOW_LATENCY_HP_GUID;
546 } else if (!strcmp(ctx->preset, "llhq")) {
547 encoder_preset = NV_ENC_PRESET_LOW_LATENCY_HQ_GUID;
549 } else if (!strcmp(ctx->preset, "default")) {
550 encoder_preset = NV_ENC_PRESET_DEFAULT_GUID;
552 av_log(avctx, AV_LOG_FATAL, "Preset \"%s\" is unknown! Supported presets: hp, hq, bd, ll, llhp, llhq, default\n", ctx->preset);
553 res = AVERROR(EINVAL);
558 nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder, NV_ENC_CODEC_H264_GUID, encoder_preset, &preset_config);
559 if (nv_status != NV_ENC_SUCCESS) {
560 av_log(avctx, AV_LOG_FATAL, "GetEncodePresetConfig failed: 0x%x\n", (int)nv_status);
561 res = AVERROR_EXTERNAL;
565 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
566 ctx->init_encode_params.encodeHeight = avctx->height;
567 ctx->init_encode_params.encodeWidth = avctx->width;
568 ctx->init_encode_params.darHeight = avctx->height;
569 ctx->init_encode_params.darWidth = avctx->width;
570 ctx->init_encode_params.frameRateNum = avctx->time_base.den;
571 ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
573 num_mbs = ((avctx->width + 15) >> 4) * ((avctx->height + 15) >> 4);
574 ctx->max_surface_count = (num_mbs >= 8160) ? 32 : 48;
576 ctx->init_encode_params.enableEncodeAsync = 0;
577 ctx->init_encode_params.enablePTD = 1;
579 ctx->init_encode_params.presetGUID = encoder_preset;
581 ctx->init_encode_params.encodeConfig = &ctx->encode_config;
582 memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
583 ctx->encode_config.version = NV_ENC_CONFIG_VER;
585 if (avctx->gop_size >= 0) {
586 ctx->encode_config.gopLength = avctx->gop_size;
587 ctx->encode_config.encodeCodecConfig.h264Config.idrPeriod = avctx->gop_size;
590 if (avctx->bit_rate > 0)
591 ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
593 if (avctx->rc_max_rate > 0)
594 ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
598 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CBR;
599 } else if (ctx->twopass == 1 || isLL) {
600 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_2_PASS_QUALITY;
602 ctx->encode_config.encodeCodecConfig.h264Config.adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
603 ctx->encode_config.encodeCodecConfig.h264Config.fmoMode = NV_ENC_H264_FMO_DISABLE;
606 av_log(avctx, AV_LOG_WARNING, "Twopass mode is only known to work with low latency (ll, llhq, llhp) presets.\n");
608 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CBR;
610 } else if (avctx->global_quality > 0) {
611 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
612 ctx->encode_config.rcParams.constQP.qpInterB = avctx->global_quality;
613 ctx->encode_config.rcParams.constQP.qpInterP = avctx->global_quality;
614 ctx->encode_config.rcParams.constQP.qpIntra = avctx->global_quality;
618 } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
619 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
621 ctx->encode_config.rcParams.enableMinQP = 1;
622 ctx->encode_config.rcParams.enableMaxQP = 1;
624 ctx->encode_config.rcParams.minQP.qpInterB = avctx->qmin;
625 ctx->encode_config.rcParams.minQP.qpInterP = avctx->qmin;
626 ctx->encode_config.rcParams.minQP.qpIntra = avctx->qmin;
628 ctx->encode_config.rcParams.maxQP.qpInterB = avctx->qmax;
629 ctx->encode_config.rcParams.maxQP.qpInterP = avctx->qmax;
630 ctx->encode_config.rcParams.maxQP.qpIntra = avctx->qmax;
633 if (avctx->rc_buffer_size > 0)
634 ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
636 if (avctx->flags & CODEC_FLAG_INTERLACED_DCT) {
637 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
639 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
642 switch (avctx->profile) {
643 case FF_PROFILE_H264_BASELINE:
644 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
646 case FF_PROFILE_H264_MAIN:
647 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
649 case FF_PROFILE_H264_HIGH:
650 case FF_PROFILE_UNKNOWN:
651 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
654 av_log(avctx, AV_LOG_WARNING, "Unsupported h264 profile requested, falling back to high\n");
655 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
659 if (ctx->gobpattern >= 0) {
660 ctx->encode_config.frameIntervalP = 1;
663 ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.colourDescriptionPresentFlag = 1;
664 ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.videoSignalTypePresentFlag = 1;
666 ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.colourMatrix = avctx->colorspace;
667 ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.colourPrimaries = avctx->color_primaries;
668 ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.transferCharacteristics = avctx->color_trc;
670 ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.videoFullRangeFlag = avctx->color_range == AVCOL_RANGE_JPEG;
672 ctx->encode_config.encodeCodecConfig.h264Config.disableSPSPPS = (avctx->flags & CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
674 nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
675 if (nv_status != NV_ENC_SUCCESS) {
676 av_log(avctx, AV_LOG_FATAL, "InitializeEncoder failed: 0x%x\n", (int)nv_status);
677 res = AVERROR_EXTERNAL;
681 ctx->input_surfaces = av_malloc(ctx->max_surface_count * sizeof(*ctx->input_surfaces));
683 if (!ctx->input_surfaces) {
684 res = AVERROR(ENOMEM);
688 ctx->output_surfaces = av_malloc(ctx->max_surface_count * sizeof(*ctx->output_surfaces));
690 if (!ctx->output_surfaces) {
691 res = AVERROR(ENOMEM);
695 for (surfaceCount = 0; surfaceCount < ctx->max_surface_count; ++surfaceCount) {
696 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
697 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
698 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
699 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
701 allocSurf.width = (avctx->width + 31) & ~31;
702 allocSurf.height = (avctx->height + 31) & ~31;
704 allocSurf.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
706 switch (avctx->pix_fmt) {
707 case AV_PIX_FMT_YUV420P:
708 allocSurf.bufferFmt = NV_ENC_BUFFER_FORMAT_YV12_PL;
711 case AV_PIX_FMT_NV12:
712 allocSurf.bufferFmt = NV_ENC_BUFFER_FORMAT_NV12_PL;
715 case AV_PIX_FMT_YUV444P:
716 allocSurf.bufferFmt = NV_ENC_BUFFER_FORMAT_YUV444_PL;
720 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format\n");
721 res = AVERROR(EINVAL);
725 nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
726 if (nv_status = NV_ENC_SUCCESS){
727 av_log(avctx, AV_LOG_FATAL, "CreateInputBuffer failed\n");
728 res = AVERROR_EXTERNAL;
732 ctx->input_surfaces[surfaceCount].lockCount = 0;
733 ctx->input_surfaces[surfaceCount].input_surface = allocSurf.inputBuffer;
734 ctx->input_surfaces[surfaceCount].format = allocSurf.bufferFmt;
735 ctx->input_surfaces[surfaceCount].width = allocSurf.width;
736 ctx->input_surfaces[surfaceCount].height = allocSurf.height;
738 /* 1MB is large enough to hold most output frames. NVENC increases this automaticaly if it's not enough. */
739 allocOut.size = 1024 * 1024;
741 allocOut.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
743 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
744 if (nv_status = NV_ENC_SUCCESS) {
745 av_log(avctx, AV_LOG_FATAL, "CreateBitstreamBuffer failed\n");
746 ctx->output_surfaces[surfaceCount++].output_surface = NULL;
747 res = AVERROR_EXTERNAL;
751 ctx->output_surfaces[surfaceCount].output_surface = allocOut.bitstreamBuffer;
752 ctx->output_surfaces[surfaceCount].size = allocOut.size;
753 ctx->output_surfaces[surfaceCount].busy = 0;
756 if (avctx->flags & CODEC_FLAG_GLOBAL_HEADER) {
757 uint32_t outSize = 0;
759 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
760 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
762 payload.spsppsBuffer = tmpHeader;
763 payload.inBufferSize = sizeof(tmpHeader);
764 payload.outSPSPPSPayloadSize = &outSize;
766 nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
767 if (nv_status != NV_ENC_SUCCESS) {
768 av_log(avctx, AV_LOG_FATAL, "GetSequenceParams failed\n");
772 avctx->extradata_size = outSize;
773 avctx->extradata = av_mallocz(outSize + FF_INPUT_BUFFER_PADDING_SIZE);
775 if (!avctx->extradata) {
776 res = AVERROR(ENOMEM);
780 memcpy(avctx->extradata, tmpHeader, outSize);
783 if (ctx->encode_config.frameIntervalP > 1)
784 avctx->has_b_frames = 2;
786 if (ctx->encode_config.rcParams.averageBitRate > 0)
787 avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
793 for (i = 0; i < surfaceCount; ++i) {
794 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->input_surfaces[i].input_surface);
795 if (ctx->output_surfaces[i].output_surface)
796 p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->output_surfaces[i].output_surface);
800 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
803 dl_fn->cu_ctx_destroy(ctx->cu_context);
805 av_frame_free(&avctx->coded_frame);
807 nvenc_unload_nvenc(avctx);
809 ctx->nvencoder = NULL;
810 ctx->cu_context = NULL;
815 static av_cold int nvenc_encode_close(AVCodecContext *avctx)
817 NvencContext *ctx = avctx->priv_data;
818 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
819 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
822 av_freep(&ctx->timestamp_list.data);
823 av_freep(&ctx->output_surface_ready_queue.data);
824 av_freep(&ctx->output_surface_queue.data);
826 for (i = 0; i < ctx->max_surface_count; ++i) {
827 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->input_surfaces[i].input_surface);
828 p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->output_surfaces[i].output_surface);
830 ctx->max_surface_count = 0;
832 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
833 ctx->nvencoder = NULL;
835 dl_fn->cu_ctx_destroy(ctx->cu_context);
836 ctx->cu_context = NULL;
838 nvenc_unload_nvenc(avctx);
840 av_frame_free(&avctx->coded_frame);
845 static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, AVFrame *coded_frame, NvencOutputSurface *tmpoutsurf)
847 NvencContext *ctx = avctx->priv_data;
848 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
849 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
851 uint32_t *slice_offsets = av_mallocz(ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData * sizeof(*slice_offsets));
852 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
853 NVENCSTATUS nv_status;
857 return AVERROR(ENOMEM);
859 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
861 lock_params.doNotWait = 0;
862 lock_params.outputBitstream = tmpoutsurf->output_surface;
863 lock_params.sliceOffsets = slice_offsets;
865 nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
866 if (nv_status != NV_ENC_SUCCESS) {
867 av_log(avctx, AV_LOG_ERROR, "Failed locking bitstream buffer\n");
868 res = AVERROR_EXTERNAL;
872 if (res = ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes)) {
873 p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
877 memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
879 nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
880 if (nv_status != NV_ENC_SUCCESS)
881 av_log(avctx, AV_LOG_ERROR, "Failed unlocking bitstream buffer, expect the gates of mordor to open\n");
883 switch (lock_params.pictureType) {
884 case NV_ENC_PIC_TYPE_IDR:
885 pkt->flags |= AV_PKT_FLAG_KEY;
886 case NV_ENC_PIC_TYPE_I:
887 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
889 case NV_ENC_PIC_TYPE_P:
890 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
892 case NV_ENC_PIC_TYPE_B:
893 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;
895 case NV_ENC_PIC_TYPE_BI:
896 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_BI;
899 av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
900 av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
901 res = AVERROR_EXTERNAL;
905 pkt->pts = lock_params.outputTimeStamp;
906 pkt->dts = timestamp_queue_dequeue(&ctx->timestamp_list);
908 if (pkt->dts > pkt->pts)
911 if (ctx->last_dts != AV_NOPTS_VALUE && pkt->dts <= ctx->last_dts)
912 pkt->dts = ctx->last_dts + 1;
914 ctx->last_dts = pkt->dts;
916 av_free(slice_offsets);
922 av_free(slice_offsets);
923 timestamp_queue_dequeue(&ctx->timestamp_list);
928 static int nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
929 const AVFrame *frame, int *got_packet)
931 NVENCSTATUS nv_status;
932 NvencOutputSurface *tmpoutsurf;
935 NvencContext *ctx = avctx->priv_data;
936 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
937 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
939 NV_ENC_PIC_PARAMS pic_params = { 0 };
940 pic_params.version = NV_ENC_PIC_PARAMS_VER;
943 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
944 NvencInputSurface *inSurf = NULL;
946 for (i = 0; i < ctx->max_surface_count; ++i) {
947 if (!ctx->input_surfaces[i].lockCount) {
948 inSurf = &ctx->input_surfaces[i];
955 inSurf->lockCount = 1;
957 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
958 lockBufferParams.inputBuffer = inSurf->input_surface;
960 nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
961 if (nv_status != NV_ENC_SUCCESS) {
962 av_log(avctx, AV_LOG_ERROR, "Failed locking nvenc input buffer\n");
966 if (avctx->pix_fmt == AV_PIX_FMT_YUV420P) {
967 uint8_t *buf = lockBufferParams.bufferDataPtr;
969 av_image_copy_plane(buf, lockBufferParams.pitch,
970 frame->data[0], frame->linesize[0],
971 avctx->width, avctx->height);
973 buf += inSurf->height * lockBufferParams.pitch;
975 av_image_copy_plane(buf, lockBufferParams.pitch >> 1,
976 frame->data[2], frame->linesize[2],
977 avctx->width >> 1, avctx->height >> 1);
979 buf += (inSurf->height * lockBufferParams.pitch) >> 2;
981 av_image_copy_plane(buf, lockBufferParams.pitch >> 1,
982 frame->data[1], frame->linesize[1],
983 avctx->width >> 1, avctx->height >> 1);
984 } else if (avctx->pix_fmt == AV_PIX_FMT_NV12) {
985 uint8_t *buf = lockBufferParams.bufferDataPtr;
987 av_image_copy_plane(buf, lockBufferParams.pitch,
988 frame->data[0], frame->linesize[0],
989 avctx->width, avctx->height);
991 buf += inSurf->height * lockBufferParams.pitch;
993 av_image_copy_plane(buf, lockBufferParams.pitch,
994 frame->data[1], frame->linesize[1],
995 avctx->width, avctx->height >> 1);
996 } else if (avctx->pix_fmt == AV_PIX_FMT_YUV444P) {
997 uint8_t *buf = lockBufferParams.bufferDataPtr;
999 av_image_copy_plane(buf, lockBufferParams.pitch,
1000 frame->data[0], frame->linesize[0],
1001 avctx->width, avctx->height);
1003 buf += inSurf->height * lockBufferParams.pitch;
1005 av_image_copy_plane(buf, lockBufferParams.pitch,
1006 frame->data[1], frame->linesize[1],
1007 avctx->width, avctx->height);
1009 buf += inSurf->height * lockBufferParams.pitch;
1011 av_image_copy_plane(buf, lockBufferParams.pitch,
1012 frame->data[2], frame->linesize[2],
1013 avctx->width, avctx->height);
1015 av_log(avctx, AV_LOG_FATAL, "Invalid pixel format!\n");
1016 return AVERROR(EINVAL);
1019 nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, inSurf->input_surface);
1020 if (nv_status != NV_ENC_SUCCESS) {
1021 av_log(avctx, AV_LOG_FATAL, "Failed unlocking input buffer!\n");
1022 return AVERROR_EXTERNAL;
1025 for (i = 0; i < ctx->max_surface_count; ++i)
1026 if (!ctx->output_surfaces[i].busy)
1029 if (i == ctx->max_surface_count) {
1030 inSurf->lockCount = 0;
1031 av_log(avctx, AV_LOG_FATAL, "No free output surface found!\n");
1032 return AVERROR_EXTERNAL;
1035 ctx->output_surfaces[i].input_surface = inSurf;
1037 pic_params.inputBuffer = inSurf->input_surface;
1038 pic_params.bufferFmt = inSurf->format;
1039 pic_params.inputWidth = avctx->width;
1040 pic_params.inputHeight = avctx->height;
1041 pic_params.outputBitstream = ctx->output_surfaces[i].output_surface;
1042 pic_params.completionEvent = 0;
1044 if (avctx->flags & CODEC_FLAG_INTERLACED_DCT) {
1045 if (frame->top_field_first) {
1046 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
1048 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
1051 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1054 pic_params.encodePicFlags = 0;
1055 pic_params.inputTimeStamp = frame->pts;
1056 pic_params.inputDuration = 0;
1057 pic_params.codecPicParams.h264PicParams.sliceMode = ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1058 pic_params.codecPicParams.h264PicParams.sliceModeData = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1059 memcpy(&pic_params.rcParams, &ctx->encode_config.rcParams, sizeof(NV_ENC_RC_PARAMS));
1061 res = timestamp_queue_enqueue(&ctx->timestamp_list, frame->pts);
1066 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1069 nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
1071 if (frame && nv_status == NV_ENC_ERR_NEED_MORE_INPUT) {
1072 res = out_surf_queue_enqueue(&ctx->output_surface_queue, &ctx->output_surfaces[i]);
1077 ctx->output_surfaces[i].busy = 1;
1080 if (nv_status != NV_ENC_SUCCESS && nv_status != NV_ENC_ERR_NEED_MORE_INPUT) {
1081 av_log(avctx, AV_LOG_ERROR, "EncodePicture failed!\n");
1082 return AVERROR_EXTERNAL;
1085 if (nv_status != NV_ENC_ERR_NEED_MORE_INPUT) {
1086 while (ctx->output_surface_queue.count) {
1087 tmpoutsurf = out_surf_queue_dequeue(&ctx->output_surface_queue);
1088 res = out_surf_queue_enqueue(&ctx->output_surface_ready_queue, tmpoutsurf);
1095 res = out_surf_queue_enqueue(&ctx->output_surface_ready_queue, &ctx->output_surfaces[i]);
1100 ctx->output_surfaces[i].busy = 1;
1104 if (ctx->output_surface_ready_queue.count) {
1105 tmpoutsurf = out_surf_queue_dequeue(&ctx->output_surface_ready_queue);
1107 res = process_output_surface(avctx, pkt, avctx->coded_frame, tmpoutsurf);
1112 tmpoutsurf->busy = 0;
1113 av_assert0(tmpoutsurf->input_surface->lockCount);
1114 tmpoutsurf->input_surface->lockCount--;
1124 static enum AVPixelFormat pix_fmts_nvenc[] = {
1129 #define OFFSET(x) offsetof(NvencContext, x)
1130 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
1131 static const AVOption options[] = {
1132 { "preset", "Set the encoding preset (one of hq, hp, bd, ll, llhq, llhp, default)", OFFSET(preset), AV_OPT_TYPE_STRING, { .str = "hq" }, 0, 0, VE },
1133 { "cbr", "Use cbr encoding mode", OFFSET(cbr), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
1134 { "2pass", "Use 2pass cbr encoding mode (low latency mode only)", OFFSET(twopass), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, VE },
1135 { "goppattern", "Specifies the GOP pattern as follows: 0: I, 1: IPP, 2: IBP, 3: IBBP", OFFSET(gobpattern), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 3, VE },
1136 { "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 },
1140 static const AVClass nvenc_class = {
1141 .class_name = "nvenc",
1142 .item_name = av_default_item_name,
1144 .version = LIBAVUTIL_VERSION_INT,
1147 static const AVCodecDefault nvenc_defaults[] = {
1157 AVCodec ff_nvenc_encoder = {
1159 .long_name = NULL_IF_CONFIG_SMALL("Nvidia NVENC h264 encoder"),
1160 .type = AVMEDIA_TYPE_VIDEO,
1161 .id = AV_CODEC_ID_H264,
1162 .priv_data_size = sizeof(NvencContext),
1163 .init = nvenc_encode_init,
1164 .encode2 = nvenc_encode_frame,
1165 .close = nvenc_encode_close,
1166 .capabilities = CODEC_CAP_DELAY,
1167 .priv_class = &nvenc_class,
1168 .defaults = nvenc_defaults,
1169 .pix_fmts = pix_fmts_nvenc,