libavcodec/nvenc.c
2a428db5
 /*
cac2df23
  * H.264/HEVC hardware encoding using nvidia nvenc
  * Copyright (c) 2016 Timo Rothenpieler <timo@rothenpieler.org>
2a428db5
  *
  * This file is part of FFmpeg.
  *
  * FFmpeg is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Lesser General Public
  * License as published by the Free Software Foundation; either
  * version 2.1 of the License, or (at your option) any later version.
  *
  * FFmpeg is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  * Lesser General Public License for more details.
  *
  * You should have received a copy of the GNU Lesser General Public
  * License along with FFmpeg; if not, write to the Free Software
  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  */
 
7aa16d59
 #include "config.h"
 
a66835bc
 #include "nvenc.h"
2a428db5
 
a66835bc
 #include "libavutil/hwcontext_cuda.h"
0d021cc8
 #include "libavutil/hwcontext.h"
2a428db5
 #include "libavutil/imgutils.h"
 #include "libavutil/avassert.h"
 #include "libavutil/mem.h"
27038693
 #include "libavutil/pixdesc.h"
2a428db5
 #include "internal.h"
a8cf25dd
 
0d021cc8
 #define NVENC_CAP 0x30
cfbebe9d
 #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR ||             \
                     rc == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ || \
                     rc == NV_ENC_PARAMS_RC_CBR_HQ)
f84dfbc7
 
7aa16d59
 const enum AVPixelFormat ff_nvenc_pix_fmts[] = {
     AV_PIX_FMT_YUV420P,
     AV_PIX_FMT_NV12,
d1bf8a3a
     AV_PIX_FMT_P010,
7aa16d59
     AV_PIX_FMT_YUV444P,
d1bf8a3a
     AV_PIX_FMT_YUV444P16,
4aeb7a88
     AV_PIX_FMT_0RGB32,
     AV_PIX_FMT_0BGR32,
7aa16d59
     AV_PIX_FMT_CUDA,
bff6d98b
 #if CONFIG_D3D11VA
     AV_PIX_FMT_D3D11,
 #endif
7aa16d59
     AV_PIX_FMT_NONE
 };
2a428db5
 
b7cc4eb3
 #define IS_10BIT(pix_fmt)  (pix_fmt == AV_PIX_FMT_P010    || \
                             pix_fmt == AV_PIX_FMT_YUV444P16)
d1bf8a3a
 
 #define IS_YUV444(pix_fmt) (pix_fmt == AV_PIX_FMT_YUV444P || \
                             pix_fmt == AV_PIX_FMT_YUV444P16)
 
e1691c44
 static const struct {
     NVENCSTATUS nverr;
     int         averr;
     const char *desc;
 } nvenc_errors[] = {
     { NV_ENC_SUCCESS,                      0,                "success"                  },
     { NV_ENC_ERR_NO_ENCODE_DEVICE,         AVERROR(ENOENT),  "no encode device"         },
     { NV_ENC_ERR_UNSUPPORTED_DEVICE,       AVERROR(ENOSYS),  "unsupported device"       },
     { NV_ENC_ERR_INVALID_ENCODERDEVICE,    AVERROR(EINVAL),  "invalid encoder device"   },
     { NV_ENC_ERR_INVALID_DEVICE,           AVERROR(EINVAL),  "invalid device"           },
     { NV_ENC_ERR_DEVICE_NOT_EXIST,         AVERROR(EIO),     "device does not exist"    },
     { NV_ENC_ERR_INVALID_PTR,              AVERROR(EFAULT),  "invalid ptr"              },
     { NV_ENC_ERR_INVALID_EVENT,            AVERROR(EINVAL),  "invalid event"            },
     { NV_ENC_ERR_INVALID_PARAM,            AVERROR(EINVAL),  "invalid param"            },
     { NV_ENC_ERR_INVALID_CALL,             AVERROR(EINVAL),  "invalid call"             },
     { NV_ENC_ERR_OUT_OF_MEMORY,            AVERROR(ENOMEM),  "out of memory"            },
     { NV_ENC_ERR_ENCODER_NOT_INITIALIZED,  AVERROR(EINVAL),  "encoder not initialized"  },
     { NV_ENC_ERR_UNSUPPORTED_PARAM,        AVERROR(ENOSYS),  "unsupported param"        },
     { NV_ENC_ERR_LOCK_BUSY,                AVERROR(EAGAIN),  "lock busy"                },
dc48248e
     { NV_ENC_ERR_NOT_ENOUGH_BUFFER,        AVERROR_BUFFER_TOO_SMALL, "not enough buffer"},
e1691c44
     { NV_ENC_ERR_INVALID_VERSION,          AVERROR(EINVAL),  "invalid version"          },
     { NV_ENC_ERR_MAP_FAILED,               AVERROR(EIO),     "map failed"               },
     { NV_ENC_ERR_NEED_MORE_INPUT,          AVERROR(EAGAIN),  "need more input"          },
     { NV_ENC_ERR_ENCODER_BUSY,             AVERROR(EAGAIN),  "encoder busy"             },
     { NV_ENC_ERR_EVENT_NOT_REGISTERD,      AVERROR(EBADF),   "event not registered"     },
     { NV_ENC_ERR_GENERIC,                  AVERROR_UNKNOWN,  "generic error"            },
     { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY,  AVERROR(EINVAL),  "incompatible client key"  },
     { NV_ENC_ERR_UNIMPLEMENTED,            AVERROR(ENOSYS),  "unimplemented"            },
     { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO),     "resource register failed" },
     { NV_ENC_ERR_RESOURCE_NOT_REGISTERED,  AVERROR(EBADF),   "resource not registered"  },
     { NV_ENC_ERR_RESOURCE_NOT_MAPPED,      AVERROR(EBADF),   "resource not mapped"      },
 };
 
 static int nvenc_map_error(NVENCSTATUS err, const char **desc)
 {
     int i;
     for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
         if (nvenc_errors[i].nverr == err) {
             if (desc)
                 *desc = nvenc_errors[i].desc;
             return nvenc_errors[i].averr;
         }
     }
     if (desc)
         *desc = "unknown error";
     return AVERROR_UNKNOWN;
 }
 
 static int nvenc_print_error(void *log_ctx, NVENCSTATUS err,
b7cc4eb3
                              const char *error_string)
e1691c44
 {
     const char *desc;
     int ret;
     ret = nvenc_map_error(err, &desc);
     av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
     return ret;
 }
 
cb3358b6
 static void nvenc_print_driver_requirement(AVCodecContext *avctx, int level)
 {
 #if defined(_WIN32) || defined(__CYGWIN__)
     const char *minver = "378.66";
 #else
     const char *minver = "378.13";
 #endif
     av_log(avctx, level, "The minimum required Nvidia driver for nvenc is %s or newer\n", minver);
 }
 
0d021cc8
 static av_cold int nvenc_load_libraries(AVCodecContext *avctx)
2a428db5
 {
b7cc4eb3
     NvencContext *ctx            = avctx->priv_data;
2a428db5
     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
0d021cc8
     NVENCSTATUS err;
df615efc
     uint32_t nvenc_max_ver;
a66835bc
     int ret;
 
1dc483a6
     ret = cuda_load_functions(&dl_fn->cuda_dl, avctx);
a66835bc
     if (ret < 0)
         return ret;
 
1dc483a6
     ret = nvenc_load_functions(&dl_fn->nvenc_dl, avctx);
cb3358b6
     if (ret < 0) {
         nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
a66835bc
         return ret;
cb3358b6
     }
2a428db5
 
a66835bc
     err = dl_fn->nvenc_dl->NvEncodeAPIGetMaxSupportedVersion(&nvenc_max_ver);
df615efc
     if (err != NV_ENC_SUCCESS)
         return nvenc_print_error(avctx, err, "Failed to query nvenc max version");
 
     av_log(avctx, AV_LOG_VERBOSE, "Loaded Nvenc version %d.%d\n", nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
 
     if ((NVENCAPI_MAJOR_VERSION << 4 | NVENCAPI_MINOR_VERSION) > nvenc_max_ver) {
         av_log(avctx, AV_LOG_ERROR, "Driver does not support the required nvenc API version. "
                "Required: %d.%d Found: %d.%d\n",
                NVENCAPI_MAJOR_VERSION, NVENCAPI_MINOR_VERSION,
                nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
cb3358b6
         nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
df615efc
         return AVERROR(ENOSYS);
     }
 
0d021cc8
     dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
2a428db5
 
a66835bc
     err = dl_fn->nvenc_dl->NvEncodeAPICreateInstance(&dl_fn->nvenc_funcs);
0d021cc8
     if (err != NV_ENC_SUCCESS)
         return nvenc_print_error(avctx, err, "Failed to create nvenc instance");
2a428db5
 
0d021cc8
     av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
2a428db5
 
     return 0;
 }
 
6fcbf39f
 static int nvenc_push_context(AVCodecContext *avctx)
 {
     NvencContext *ctx            = avctx->priv_data;
     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
     CUresult cu_res;
 
bff6d98b
     if (ctx->d3d11_device)
         return 0;
 
6fcbf39f
     cu_res = dl_fn->cuda_dl->cuCtxPushCurrent(ctx->cu_context);
     if (cu_res != CUDA_SUCCESS) {
         av_log(avctx, AV_LOG_ERROR, "cuCtxPushCurrent failed\n");
         return AVERROR_EXTERNAL;
     }
 
     return 0;
 }
 
 static int nvenc_pop_context(AVCodecContext *avctx)
 {
     NvencContext *ctx            = avctx->priv_data;
     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
     CUresult cu_res;
     CUcontext dummy;
 
bff6d98b
     if (ctx->d3d11_device)
         return 0;
 
6fcbf39f
     cu_res = dl_fn->cuda_dl->cuCtxPopCurrent(&dummy);
     if (cu_res != CUDA_SUCCESS) {
         av_log(avctx, AV_LOG_ERROR, "cuCtxPopCurrent failed\n");
         return AVERROR_EXTERNAL;
     }
 
     return 0;
 }
 
0d021cc8
 static av_cold int nvenc_open_session(AVCodecContext *avctx)
2a428db5
 {
0d021cc8
     NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
     NvencContext *ctx = avctx->priv_data;
     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
     NVENCSTATUS ret;
 
     params.version    = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
     params.apiVersion = NVENCAPI_VERSION;
bff6d98b
     if (ctx->d3d11_device) {
         params.device     = ctx->d3d11_device;
         params.deviceType = NV_ENC_DEVICE_TYPE_DIRECTX;
     } else {
         params.device     = ctx->cu_context;
         params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
     }
0d021cc8
 
     ret = p_nvenc->nvEncOpenEncodeSessionEx(&params, &ctx->nvencoder);
     if (ret != NV_ENC_SUCCESS) {
         ctx->nvencoder = NULL;
         return nvenc_print_error(avctx, ret, "OpenEncodeSessionEx failed");
2a428db5
     }
0d021cc8
 
     return 0;
2a428db5
 }
 
0d021cc8
 static int nvenc_check_codec_support(AVCodecContext *avctx)
2a428db5
 {
b7cc4eb3
     NvencContext *ctx                    = avctx->priv_data;
0d021cc8
     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
     int i, ret, count = 0;
     GUID *guids = NULL;
2a428db5
 
0d021cc8
     ret = p_nvenc->nvEncGetEncodeGUIDCount(ctx->nvencoder, &count);
21175d85
 
0d021cc8
     if (ret != NV_ENC_SUCCESS || !count)
         return AVERROR(ENOSYS);
24fcb233
 
0d021cc8
     guids = av_malloc(count * sizeof(GUID));
     if (!guids)
         return AVERROR(ENOMEM);
2a428db5
 
0d021cc8
     ret = p_nvenc->nvEncGetEncodeGUIDs(ctx->nvencoder, guids, count, &count);
     if (ret != NV_ENC_SUCCESS) {
         ret = AVERROR(ENOSYS);
         goto fail;
     }
2a428db5
 
0d021cc8
     ret = AVERROR(ENOSYS);
     for (i = 0; i < count; i++) {
         if (!memcmp(&guids[i], &ctx->init_encode_params.encodeGUID, sizeof(*guids))) {
             ret = 0;
             break;
         }
     }
2a428db5
 
0d021cc8
 fail:
     av_free(guids);
2a428db5
 
0d021cc8
     return ret;
 }
2a428db5
 
0d021cc8
 static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
 {
     NvencContext *ctx = avctx->priv_data;
     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
     NV_ENC_CAPS_PARAM params        = { 0 };
     int ret, val = 0;
2a428db5
 
0d021cc8
     params.version     = NV_ENC_CAPS_PARAM_VER;
     params.capsToQuery = cap;
2a428db5
 
0d021cc8
     ret = p_nvenc->nvEncGetEncodeCaps(ctx->nvencoder, ctx->init_encode_params.encodeGUID, &params, &val);
2a428db5
 
0d021cc8
     if (ret == NV_ENC_SUCCESS)
         return val;
     return 0;
 }
2a428db5
 
0d021cc8
 static int nvenc_check_capabilities(AVCodecContext *avctx)
 {
     NvencContext *ctx = avctx->priv_data;
     int ret;
2a428db5
 
0d021cc8
     ret = nvenc_check_codec_support(avctx);
     if (ret < 0) {
         av_log(avctx, AV_LOG_VERBOSE, "Codec not supported\n");
         return ret;
2a428db5
     }
 
0d021cc8
     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
d1bf8a3a
     if (IS_YUV444(ctx->data_pix_fmt) && ret <= 0) {
0d021cc8
         av_log(avctx, AV_LOG_VERBOSE, "YUV444P not supported\n");
         return AVERROR(ENOSYS);
2a428db5
     }
 
0d021cc8
     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOSSLESS_ENCODE);
     if (ctx->preset >= PRESET_LOSSLESS_DEFAULT && ret <= 0) {
         av_log(avctx, AV_LOG_VERBOSE, "Lossless encoding not supported\n");
         return AVERROR(ENOSYS);
     }
2a428db5
 
0d021cc8
     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
     if (ret < avctx->width) {
         av_log(avctx, AV_LOG_VERBOSE, "Width %d exceeds %d\n",
                avctx->width, ret);
         return AVERROR(ENOSYS);
     }
2a428db5
 
0d021cc8
     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
     if (ret < avctx->height) {
         av_log(avctx, AV_LOG_VERBOSE, "Height %d exceeds %d\n",
                avctx->height, ret);
         return AVERROR(ENOSYS);
     }
 
     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
     if (ret < avctx->max_b_frames) {
41ed7ab4
         av_log(avctx, AV_LOG_VERBOSE, "Max B-frames %d exceed %d\n",
0d021cc8
                avctx->max_b_frames, ret);
 
         return AVERROR(ENOSYS);
     }
2a428db5
 
808356c6
     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_FIELD_ENCODING);
     if (ret < 1 && avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
         av_log(avctx, AV_LOG_VERBOSE,
                "Interlaced encoding is not supported. Supported level: %d\n",
                ret);
         return AVERROR(ENOSYS);
     }
 
d1bf8a3a
     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_10BIT_ENCODE);
     if (IS_10BIT(ctx->data_pix_fmt) && ret <= 0) {
         av_log(avctx, AV_LOG_VERBOSE, "10 bit encode not supported\n");
         return AVERROR(ENOSYS);
     }
 
a81b398e
     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOOKAHEAD);
     if (ctx->rc_lookahead > 0 && ret <= 0) {
         av_log(avctx, AV_LOG_VERBOSE, "RC lookahead not supported\n");
         return AVERROR(ENOSYS);
     }
 
da4d0fa8
     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_TEMPORAL_AQ);
     if (ctx->temporal_aq > 0 && ret <= 0) {
         av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ not supported\n");
         return AVERROR(ENOSYS);
     }
 
01775730
     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_WEIGHTED_PREDICTION);
     if (ctx->weighted_pred > 0 && ret <= 0) {
         av_log (avctx, AV_LOG_VERBOSE, "Weighted Prediction not supported\n");
         return AVERROR(ENOSYS);
     }
 
a0b69e2b
     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_CABAC);
     if (ctx->coder == NV_ENC_H264_ENTROPY_CODING_MODE_CABAC && ret <= 0) {
         av_log(avctx, AV_LOG_VERBOSE, "CABAC entropy coding not supported\n");
         return AVERROR(ENOSYS);
     }
 
2a428db5
     return 0;
 }
 
0d021cc8
 static av_cold int nvenc_check_device(AVCodecContext *avctx, int idx)
2a428db5
 {
     NvencContext *ctx = avctx->priv_data;
     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
0d021cc8
     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
     char name[128] = { 0};
     int major, minor, ret;
     CUresult cu_res;
     CUdevice cu_device;
     int loglevel = AV_LOG_VERBOSE;
2a428db5
 
0d021cc8
     if (ctx->device == LIST_DEVICES)
         loglevel = AV_LOG_INFO;
2a428db5
 
a66835bc
     cu_res = dl_fn->cuda_dl->cuDeviceGet(&cu_device, idx);
0d021cc8
     if (cu_res != CUDA_SUCCESS) {
         av_log(avctx, AV_LOG_ERROR,
                "Cannot access the CUDA device %d\n",
                idx);
         return -1;
     }
2a428db5
 
a66835bc
     cu_res = dl_fn->cuda_dl->cuDeviceGetName(name, sizeof(name), cu_device);
6b0a3ee6
     if (cu_res != CUDA_SUCCESS) {
         av_log(avctx, AV_LOG_ERROR, "cuDeviceGetName failed on device %d\n", idx);
0d021cc8
         return -1;
6b0a3ee6
     }
0d021cc8
 
a66835bc
     cu_res = dl_fn->cuda_dl->cuDeviceComputeCapability(&major, &minor, cu_device);
6b0a3ee6
     if (cu_res != CUDA_SUCCESS) {
         av_log(avctx, AV_LOG_ERROR, "cuDeviceComputeCapability failed on device %d\n", idx);
0d021cc8
         return -1;
6b0a3ee6
     }
0d021cc8
 
     av_log(avctx, loglevel, "[ GPU #%d - < %s > has Compute SM %d.%d ]\n", idx, name, major, minor);
     if (((major << 4) | minor) < NVENC_CAP) {
         av_log(avctx, loglevel, "does not support NVENC\n");
         goto fail;
2a428db5
     }
 
5403d90f
     if (ctx->device != idx && ctx->device != ANY_DEVICE)
         return -1;
 
a66835bc
     cu_res = dl_fn->cuda_dl->cuCtxCreate(&ctx->cu_context_internal, 0, cu_device);
0d021cc8
     if (cu_res != CUDA_SUCCESS) {
         av_log(avctx, AV_LOG_FATAL, "Failed creating CUDA context for NVENC: 0x%x\n", (int)cu_res);
         goto fail;
2a428db5
     }
 
0d021cc8
     ctx->cu_context = ctx->cu_context_internal;
2a428db5
 
6fcbf39f
     if ((ret = nvenc_pop_context(avctx)) < 0)
0d021cc8
         goto fail2;
2a428db5
 
0d021cc8
     if ((ret = nvenc_open_session(avctx)) < 0)
         goto fail2;
2a428db5
 
0d021cc8
     if ((ret = nvenc_check_capabilities(avctx)) < 0)
         goto fail3;
2a428db5
 
0d021cc8
     av_log(avctx, loglevel, "supports NVENC\n");
2a428db5
 
0d021cc8
     dl_fn->nvenc_device_count++;
2a428db5
 
5403d90f
     if (ctx->device == idx || ctx->device == ANY_DEVICE)
0d021cc8
         return 0;
2a428db5
 
0d021cc8
 fail3:
6fcbf39f
     if ((ret = nvenc_push_context(avctx)) < 0)
         return ret;
43c417ac
 
0d021cc8
     p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
     ctx->nvencoder = NULL;
2a428db5
 
6fcbf39f
     if ((ret = nvenc_pop_context(avctx)) < 0)
         return ret;
43c417ac
 
0d021cc8
 fail2:
a66835bc
     dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal);
0d021cc8
     ctx->cu_context_internal = NULL;
2a428db5
 
0d021cc8
 fail:
     return AVERROR(ENOSYS);
2a428db5
 }
 
82d705e2
 static av_cold int nvenc_setup_device(AVCodecContext *avctx)
2a428db5
 {
b7cc4eb3
     NvencContext *ctx            = avctx->priv_data;
2a428db5
     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
 
faffff88
     switch (avctx->codec->id) {
     case AV_CODEC_ID_H264:
         ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
         break;
     case AV_CODEC_ID_HEVC:
         ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
         break;
     default:
         return AVERROR_BUG;
     }
 
bff6d98b
     if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11 || avctx->hw_frames_ctx || avctx->hw_device_ctx) {
0d021cc8
         AVHWFramesContext   *frames_ctx;
dad6f44b
         AVHWDeviceContext   *hwdev_ctx;
bff6d98b
         AVCUDADeviceContext *cuda_device_hwctx = NULL;
 #if CONFIG_D3D11VA
         AVD3D11VADeviceContext *d3d11_device_hwctx = NULL;
 #endif
0d021cc8
         int ret;
a8cf25dd
 
dad6f44b
         if (avctx->hw_frames_ctx) {
             frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
bff6d98b
             if (frames_ctx->format == AV_PIX_FMT_CUDA)
                 cuda_device_hwctx = frames_ctx->device_ctx->hwctx;
 #if CONFIG_D3D11VA
             else if (frames_ctx->format == AV_PIX_FMT_D3D11)
                 d3d11_device_hwctx = frames_ctx->device_ctx->hwctx;
 #endif
             else
                 return AVERROR(EINVAL);
dad6f44b
         } else if (avctx->hw_device_ctx) {
             hwdev_ctx = (AVHWDeviceContext*)avctx->hw_device_ctx->data;
bff6d98b
             if (hwdev_ctx->type == AV_HWDEVICE_TYPE_CUDA)
                 cuda_device_hwctx = hwdev_ctx->hwctx;
 #if CONFIG_D3D11VA
             else if (hwdev_ctx->type == AV_HWDEVICE_TYPE_D3D11VA)
                 d3d11_device_hwctx = hwdev_ctx->hwctx;
 #endif
             else
                 return AVERROR(EINVAL);
dad6f44b
         } else {
a8cf25dd
             return AVERROR(EINVAL);
dad6f44b
         }
a8cf25dd
 
bff6d98b
         if (cuda_device_hwctx) {
             ctx->cu_context = cuda_device_hwctx->cuda_ctx;
         }
 #if CONFIG_D3D11VA
         else if (d3d11_device_hwctx) {
             ctx->d3d11_device = d3d11_device_hwctx->device;
             ID3D11Device_AddRef(ctx->d3d11_device);
         }
 #endif
2a428db5
 
0d021cc8
         ret = nvenc_open_session(avctx);
         if (ret < 0)
             return ret;
2a428db5
 
0d021cc8
         ret = nvenc_check_capabilities(avctx);
         if (ret < 0) {
             av_log(avctx, AV_LOG_FATAL, "Provided device doesn't support required NVENC features\n");
             return ret;
         }
     } else {
         int i, nb_devices = 0;
2a428db5
 
a66835bc
         if ((dl_fn->cuda_dl->cuInit(0)) != CUDA_SUCCESS) {
0d021cc8
             av_log(avctx, AV_LOG_ERROR,
                    "Cannot init CUDA\n");
             return AVERROR_UNKNOWN;
         }
2a428db5
 
a66835bc
         if ((dl_fn->cuda_dl->cuDeviceGetCount(&nb_devices)) != CUDA_SUCCESS) {
0d021cc8
             av_log(avctx, AV_LOG_ERROR,
                    "Cannot enumerate the CUDA devices\n");
             return AVERROR_UNKNOWN;
         }
2a428db5
 
0d021cc8
         if (!nb_devices) {
             av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
                 return AVERROR_EXTERNAL;
         }
a8cf25dd
 
0d021cc8
         av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", nb_devices);
82d705e2
 
0d021cc8
         dl_fn->nvenc_device_count = 0;
         for (i = 0; i < nb_devices; ++i) {
             if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
                 return 0;
         }
82d705e2
 
0d021cc8
         if (ctx->device == LIST_DEVICES)
             return AVERROR_EXIT;
82d705e2
 
0d021cc8
         if (!dl_fn->nvenc_device_count) {
             av_log(avctx, AV_LOG_FATAL, "No NVENC capable devices found\n");
             return AVERROR_EXTERNAL;
         }
2a428db5
 
5403d90f
         av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->device, nb_devices);
0d021cc8
         return AVERROR(EINVAL);
82d705e2
     }
 
     return 0;
 }
 
faffff88
 typedef struct GUIDTuple {
     const GUID guid;
     int flags;
 } GUIDTuple;
 
a81b000a
 #define PRESET_ALIAS(alias, name, ...) \
     [PRESET_ ## alias] = { NV_ENC_PRESET_ ## name ## _GUID, __VA_ARGS__ }
 
 #define PRESET(name, ...) PRESET_ALIAS(name, name, __VA_ARGS__)
 
faffff88
 static void nvenc_map_preset(NvencContext *ctx)
 {
     GUIDTuple presets[] = {
a81b000a
         PRESET(DEFAULT),
         PRESET(HP),
         PRESET(HQ),
         PRESET(BD),
         PRESET_ALIAS(SLOW,   HQ,    NVENC_TWO_PASSES),
         PRESET_ALIAS(MEDIUM, HQ,    NVENC_ONE_PASS),
         PRESET_ALIAS(FAST,   HP,    NVENC_ONE_PASS),
         PRESET(LOW_LATENCY_DEFAULT, NVENC_LOWLATENCY),
         PRESET(LOW_LATENCY_HP,      NVENC_LOWLATENCY),
         PRESET(LOW_LATENCY_HQ,      NVENC_LOWLATENCY),
         PRESET(LOSSLESS_DEFAULT,    NVENC_LOSSLESS),
         PRESET(LOSSLESS_HP,         NVENC_LOSSLESS),
faffff88
     };
 
     GUIDTuple *t = &presets[ctx->preset];
 
     ctx->init_encode_params.presetGUID = t->guid;
     ctx->flags = t->flags;
 }
 
a81b000a
 #undef PRESET
 #undef PRESET_ALIAS
 
82d705e2
 static av_cold void set_constqp(AVCodecContext *avctx)
 {
     NvencContext *ctx = avctx->priv_data;
f84dfbc7
     NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
 
     rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
2db5ab73
 
     if (ctx->init_qp_p >= 0) {
         rc->constQP.qpInterP = ctx->init_qp_p;
         if (ctx->init_qp_i >= 0 && ctx->init_qp_b >= 0) {
             rc->constQP.qpIntra = ctx->init_qp_i;
             rc->constQP.qpInterB = ctx->init_qp_b;
         } else if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
             rc->constQP.qpIntra = av_clip(
                 rc->constQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
             rc->constQP.qpInterB = av_clip(
                 rc->constQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
         } else {
             rc->constQP.qpIntra = rc->constQP.qpInterP;
             rc->constQP.qpInterB = rc->constQP.qpInterP;
         }
7fb2a7af
     } else if (ctx->cqp >= 0) {
d84c2298
         rc->constQP.qpInterP = rc->constQP.qpInterB = rc->constQP.qpIntra = ctx->cqp;
         if (avctx->b_quant_factor != 0.0)
             rc->constQP.qpInterB = av_clip(ctx->cqp * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
         if (avctx->i_quant_factor != 0.0)
             rc->constQP.qpIntra = av_clip(ctx->cqp * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
2db5ab73
     }
82d705e2
 
f84dfbc7
     avctx->qmin = -1;
     avctx->qmax = -1;
82d705e2
 }
 
 static av_cold void set_vbr(AVCodecContext *avctx)
 {
     NvencContext *ctx = avctx->priv_data;
f84dfbc7
     NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
     int qp_inter_p;
 
     if (avctx->qmin >= 0 && avctx->qmax >= 0) {
         rc->enableMinQP = 1;
         rc->enableMaxQP = 1;
 
         rc->minQP.qpInterB = avctx->qmin;
         rc->minQP.qpInterP = avctx->qmin;
b7cc4eb3
         rc->minQP.qpIntra  = avctx->qmin;
82d705e2
 
f84dfbc7
         rc->maxQP.qpInterB = avctx->qmax;
         rc->maxQP.qpInterP = avctx->qmax;
         rc->maxQP.qpIntra = avctx->qmax;
82d705e2
 
f84dfbc7
         qp_inter_p = (avctx->qmax + 3 * avctx->qmin) / 4; // biased towards Qmin
971351b6
     } else if (avctx->qmin >= 0) {
         rc->enableMinQP = 1;
 
         rc->minQP.qpInterB = avctx->qmin;
         rc->minQP.qpInterP = avctx->qmin;
         rc->minQP.qpIntra = avctx->qmin;
 
         qp_inter_p = avctx->qmin;
f84dfbc7
     } else {
         qp_inter_p = 26; // default to 26
     }
 
     rc->enableInitialRCQP = 1;
82d705e2
 
5f44a4a0
     if (ctx->init_qp_p < 0) {
         rc->initialRCQP.qpInterP  = qp_inter_p;
f84dfbc7
     } else {
5f44a4a0
         rc->initialRCQP.qpInterP = ctx->init_qp_p;
     }
 
     if (ctx->init_qp_i < 0) {
         if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
             rc->initialRCQP.qpIntra = av_clip(
                 rc->initialRCQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
         } else {
             rc->initialRCQP.qpIntra = rc->initialRCQP.qpInterP;
         }
     } else {
         rc->initialRCQP.qpIntra = ctx->init_qp_i;
     }
 
     if (ctx->init_qp_b < 0) {
         if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
             rc->initialRCQP.qpInterB = av_clip(
                 rc->initialRCQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
         } else {
             rc->initialRCQP.qpInterB = rc->initialRCQP.qpInterP;
         }
     } else {
         rc->initialRCQP.qpInterB = ctx->init_qp_b;
f84dfbc7
     }
82d705e2
 }
 
 static av_cold void set_lossless(AVCodecContext *avctx)
 {
     NvencContext *ctx = avctx->priv_data;
f84dfbc7
     NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
82d705e2
 
f84dfbc7
     rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
     rc->constQP.qpInterB = 0;
     rc->constQP.qpInterP = 0;
b7cc4eb3
     rc->constQP.qpIntra  = 0;
f84dfbc7
 
     avctx->qmin = -1;
     avctx->qmax = -1;
 }
 
 static void nvenc_override_rate_control(AVCodecContext *avctx)
 {
     NvencContext *ctx    = avctx->priv_data;
     NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
 
     switch (ctx->rc) {
     case NV_ENC_PARAMS_RC_CONSTQP:
         set_constqp(avctx);
         return;
     case NV_ENC_PARAMS_RC_VBR_MINQP:
         if (avctx->qmin < 0) {
             av_log(avctx, AV_LOG_WARNING,
                    "The variable bitrate rate-control requires "
                    "the 'qmin' option set.\n");
             set_vbr(avctx);
             return;
         }
a549243b
         /* fall through */
cfbebe9d
     case NV_ENC_PARAMS_RC_VBR_HQ:
a549243b
     case NV_ENC_PARAMS_RC_VBR:
f84dfbc7
         set_vbr(avctx);
         break;
     case NV_ENC_PARAMS_RC_CBR:
cfbebe9d
     case NV_ENC_PARAMS_RC_CBR_HQ:
     case NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ:
eae4eba9
         break;
f84dfbc7
     }
 
     rc->rateControlMode = ctx->rc;
82d705e2
 }
 
de2faec2
 static av_cold int nvenc_recalc_surfaces(AVCodecContext *avctx)
 {
     NvencContext *ctx = avctx->priv_data;
8de3458a
     // default minimum of 4 surfaces
     // multiply by 2 for number of NVENCs on gpu (hardcode to 2)
     // another multiply by 2 to avoid blocking next PBB group
     int nb_surfaces = FFMAX(4, ctx->encode_config.frameIntervalP * 2 * 2);
de2faec2
 
8de3458a
     // lookahead enabled
de2faec2
     if (ctx->rc_lookahead > 0) {
8de3458a
         // +1 is to account for lkd_bound calculation later
         // +4 is to allow sufficient pipelining with lookahead
         nb_surfaces = FFMAX(1, FFMAX(nb_surfaces, ctx->rc_lookahead + ctx->encode_config.frameIntervalP + 1 + 4));
         if (nb_surfaces > ctx->nb_surfaces && ctx->nb_surfaces > 0)
         {
de2faec2
             av_log(avctx, AV_LOG_WARNING,
                    "Defined rc_lookahead requires more surfaces, "
                    "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
         }
8de3458a
         ctx->nb_surfaces = FFMAX(nb_surfaces, ctx->nb_surfaces);
     } else {
         if (ctx->encode_config.frameIntervalP > 1 && ctx->nb_surfaces < nb_surfaces && ctx->nb_surfaces > 0)
         {
             av_log(avctx, AV_LOG_WARNING,
                    "Defined b-frame requires more surfaces, "
                    "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
             ctx->nb_surfaces = FFMAX(ctx->nb_surfaces, nb_surfaces);
         }
         else if (ctx->nb_surfaces <= 0)
             ctx->nb_surfaces = nb_surfaces;
         // otherwise use user specified value
de2faec2
     }
 
     ctx->nb_surfaces = FFMAX(1, FFMIN(MAX_REGISTERED_FRAMES, ctx->nb_surfaces));
     ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
 
     return 0;
 }
 
faffff88
 static av_cold void nvenc_setup_rate_control(AVCodecContext *avctx)
82d705e2
 {
     NvencContext *ctx = avctx->priv_data;
 
7fb2a7af
     if (avctx->global_quality > 0)
         av_log(avctx, AV_LOG_WARNING, "Using global_quality with nvenc is deprecated. Use qp instead.\n");
 
     if (ctx->cqp < 0 && avctx->global_quality > 0)
         ctx->cqp = avctx->global_quality;
 
82d705e2
     if (avctx->bit_rate > 0) {
         ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
     } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
         ctx->encode_config.rcParams.maxBitRate = ctx->encode_config.rcParams.averageBitRate;
     }
 
     if (avctx->rc_max_rate > 0)
         ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
 
f84dfbc7
     if (ctx->rc < 0) {
         if (ctx->flags & NVENC_ONE_PASS)
             ctx->twopass = 0;
         if (ctx->flags & NVENC_TWO_PASSES)
             ctx->twopass = 1;
82d705e2
 
f84dfbc7
         if (ctx->twopass < 0)
             ctx->twopass = (ctx->flags & NVENC_LOWLATENCY) != 0;
82d705e2
 
f84dfbc7
         if (ctx->cbr) {
82d705e2
             if (ctx->twopass) {
cfbebe9d
                 ctx->rc = NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ;
82d705e2
             } else {
f84dfbc7
                 ctx->rc = NV_ENC_PARAMS_RC_CBR;
82d705e2
             }
7fb2a7af
         } else if (ctx->cqp >= 0) {
f84dfbc7
             ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
         } else if (ctx->twopass) {
cfbebe9d
             ctx->rc = NV_ENC_PARAMS_RC_VBR_HQ;
f84dfbc7
         } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
             ctx->rc = NV_ENC_PARAMS_RC_VBR_MINQP;
82d705e2
         }
f84dfbc7
     }
82d705e2
 
cfbebe9d
     if (ctx->rc >= 0 && ctx->rc & RC_MODE_DEPRECATED) {
         av_log(avctx, AV_LOG_WARNING, "Specified rc mode is deprecated.\n");
         av_log(avctx, AV_LOG_WARNING, "\tll_2pass_quality -> cbr_ld_hq\n");
         av_log(avctx, AV_LOG_WARNING, "\tll_2pass_size -> cbr_hq\n");
         av_log(avctx, AV_LOG_WARNING, "\tvbr_2pass -> vbr_hq\n");
         av_log(avctx, AV_LOG_WARNING, "\tvbr_minqp -> (no replacement)\n");
 
         ctx->rc &= ~RC_MODE_DEPRECATED;
     }
 
f84dfbc7
     if (ctx->flags & NVENC_LOSSLESS) {
         set_lossless(avctx);
1330a0f3
     } else if (ctx->rc >= 0) {
f84dfbc7
         nvenc_override_rate_control(avctx);
     } else {
         ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
         set_vbr(avctx);
82d705e2
     }
 
     if (avctx->rc_buffer_size > 0) {
         ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
     } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
         ctx->encode_config.rcParams.vbvBufferSize = 2 * ctx->encode_config.rcParams.averageBitRate;
     }
a81b398e
 
facc19ef
     if (ctx->aq) {
         ctx->encode_config.rcParams.enableAQ   = 1;
         ctx->encode_config.rcParams.aqStrength = ctx->aq_strength;
         av_log(avctx, AV_LOG_VERBOSE, "AQ enabled.\n");
a81b398e
     }
facc19ef
 
     if (ctx->temporal_aq) {
         ctx->encode_config.rcParams.enableTemporalAQ = 1;
         av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ enabled.\n");
     }
 
67db4ff3
     if (ctx->rc_lookahead > 0) {
facc19ef
         int lkd_bound = FFMIN(ctx->nb_surfaces, ctx->async_depth) -
                         ctx->encode_config.frameIntervalP - 4;
 
         if (lkd_bound < 0) {
             av_log(avctx, AV_LOG_WARNING,
                    "Lookahead not enabled. Increase buffer delay (-delay).\n");
         } else {
             ctx->encode_config.rcParams.enableLookahead = 1;
             ctx->encode_config.rcParams.lookaheadDepth  = av_clip(ctx->rc_lookahead, 0, lkd_bound);
             ctx->encode_config.rcParams.disableIadapt   = ctx->no_scenecut;
             ctx->encode_config.rcParams.disableBadapt   = !ctx->b_adapt;
             av_log(avctx, AV_LOG_VERBOSE,
                    "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",
                    ctx->encode_config.rcParams.lookaheadDepth,
                    ctx->encode_config.rcParams.disableIadapt ? "disabled" : "enabled",
                    ctx->encode_config.rcParams.disableBadapt ? "disabled" : "enabled");
         }
     }
 
     if (ctx->strict_gop) {
         ctx->encode_config.rcParams.strictGOPTarget = 1;
         av_log(avctx, AV_LOG_VERBOSE, "Strict GOP target enabled.\n");
     }
 
     if (ctx->nonref_p)
         ctx->encode_config.rcParams.enableNonRefP = 1;
 
     if (ctx->zerolatency)
         ctx->encode_config.rcParams.zeroReorderDelay = 1;
 
     if (ctx->quality)
18a659d1
     {
         //convert from float to fixed point 8.8
         int tmp_quality = (int)(ctx->quality * 256.0f);
         ctx->encode_config.rcParams.targetQuality = (uint8_t)(tmp_quality >> 8);
         ctx->encode_config.rcParams.targetQualityLSB = (uint8_t)(tmp_quality & 0xff);
     }
82d705e2
 }
 
faffff88
 static av_cold int nvenc_setup_h264_config(AVCodecContext *avctx)
82d705e2
 {
faffff88
     NvencContext *ctx                      = avctx->priv_data;
     NV_ENC_CONFIG *cc                      = &ctx->encode_config;
     NV_ENC_CONFIG_H264 *h264               = &cc->encodeCodecConfig.h264Config;
     NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
82d705e2
 
faffff88
     vui->colourMatrix = avctx->colorspace;
     vui->colourPrimaries = avctx->color_primaries;
     vui->transferCharacteristics = avctx->color_trc;
     vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
a8cf25dd
         || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
82d705e2
 
faffff88
     vui->colourDescriptionPresentFlag =
82d705e2
         (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
 
faffff88
     vui->videoSignalTypePresentFlag =
         (vui->colourDescriptionPresentFlag
         || vui->videoFormat != 5
         || vui->videoFullRangeFlag != 0);
82d705e2
 
faffff88
     h264->sliceMode = 3;
     h264->sliceModeData = 1;
82d705e2
 
faffff88
     h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
f84dfbc7
     h264->repeatSPSPPS  = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
1841eda6
     h264->outputAUD     = ctx->aud;
82d705e2
 
f84dfbc7
     if (avctx->refs >= 0) {
         /* 0 means "let the hardware decide" */
         h264->maxNumRefFrames = avctx->refs;
     }
     if (avctx->gop_size >= 0) {
         h264->idrPeriod = cc->gopLength;
     }
 
     if (IS_CBR(cc->rcParams.rateControlMode)) {
         h264->outputBufferingPeriodSEI = 1;
     }
 
4e6638ab
     h264->outputPictureTimingSEI = 1;
 
cfbebe9d
     if (cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ ||
         cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_HQ ||
         cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_VBR_HQ) {
f84dfbc7
         h264->adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
         h264->fmoMode = NV_ENC_H264_FMO_DISABLE;
     }
82d705e2
 
9824321b
     if (ctx->flags & NVENC_LOSSLESS) {
         h264->qpPrimeYZeroTransformBypassFlag = 1;
     } else {
         switch(ctx->profile) {
         case NV_ENC_H264_PROFILE_BASELINE:
faffff88
             cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
9824321b
             avctx->profile = FF_PROFILE_H264_BASELINE;
82d705e2
             break;
9824321b
         case NV_ENC_H264_PROFILE_MAIN:
faffff88
             cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
9824321b
             avctx->profile = FF_PROFILE_H264_MAIN;
82d705e2
             break;
9824321b
         case NV_ENC_H264_PROFILE_HIGH:
faffff88
             cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
82d705e2
             avctx->profile = FF_PROFILE_H264_HIGH;
9824321b
             break;
         case NV_ENC_H264_PROFILE_HIGH_444P:
faffff88
             cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
82d705e2
             avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
9824321b
             break;
82d705e2
         }
     }
 
     // force setting profile as high444p if input is AV_PIX_FMT_YUV444P
a8cf25dd
     if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P) {
faffff88
         cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
82d705e2
         avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
     }
 
faffff88
     h264->chromaFormatIDC = avctx->profile == FF_PROFILE_H264_HIGH_444_PREDICTIVE ? 3 : 1;
82d705e2
 
b0172873
     h264->level = ctx->level;
82d705e2
 
a0b69e2b
     if (ctx->coder >= 0)
         h264->entropyCodingMode = ctx->coder;
 
82d705e2
     return 0;
 }
 
 static av_cold int nvenc_setup_hevc_config(AVCodecContext *avctx)
 {
faffff88
     NvencContext *ctx                      = avctx->priv_data;
     NV_ENC_CONFIG *cc                      = &ctx->encode_config;
     NV_ENC_CONFIG_HEVC *hevc               = &cc->encodeCodecConfig.hevcConfig;
     NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
82d705e2
 
faffff88
     vui->colourMatrix = avctx->colorspace;
     vui->colourPrimaries = avctx->color_primaries;
     vui->transferCharacteristics = avctx->color_trc;
     vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
a8cf25dd
         || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
82d705e2
 
faffff88
     vui->colourDescriptionPresentFlag =
82d705e2
         (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
 
faffff88
     vui->videoSignalTypePresentFlag =
         (vui->colourDescriptionPresentFlag
         || vui->videoFormat != 5
         || vui->videoFullRangeFlag != 0);
82d705e2
 
faffff88
     hevc->sliceMode = 3;
     hevc->sliceModeData = 1;
82d705e2
 
faffff88
     hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
f84dfbc7
     hevc->repeatSPSPPS  = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
1841eda6
     hevc->outputAUD     = ctx->aud;
f84dfbc7
 
     if (avctx->refs >= 0) {
         /* 0 means "let the hardware decide" */
         hevc->maxNumRefFramesInDPB = avctx->refs;
     }
     if (avctx->gop_size >= 0) {
         hevc->idrPeriod = cc->gopLength;
     }
82d705e2
 
f84dfbc7
     if (IS_CBR(cc->rcParams.rateControlMode)) {
         hevc->outputBufferingPeriodSEI = 1;
     }
82d705e2
 
4e6638ab
     hevc->outputPictureTimingSEI = 1;
 
b7cc4eb3
     switch (ctx->profile) {
d1bf8a3a
     case NV_ENC_HEVC_PROFILE_MAIN:
         cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
b7cc4eb3
         avctx->profile  = FF_PROFILE_HEVC_MAIN;
d1bf8a3a
         break;
     case NV_ENC_HEVC_PROFILE_MAIN_10:
         cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
b7cc4eb3
         avctx->profile  = FF_PROFILE_HEVC_MAIN_10;
d1bf8a3a
         break;
033f98c9
     case NV_ENC_HEVC_PROFILE_REXT:
         cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
b7cc4eb3
         avctx->profile  = FF_PROFILE_HEVC_REXT;
033f98c9
         break;
d1bf8a3a
     }
 
     // force setting profile as main10 if input is 10 bit
     if (IS_10BIT(ctx->data_pix_fmt)) {
         cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
         avctx->profile = FF_PROFILE_HEVC_MAIN_10;
     }
 
033f98c9
     // force setting profile as rext if input is yuv444
     if (IS_YUV444(ctx->data_pix_fmt)) {
         cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
         avctx->profile = FF_PROFILE_HEVC_REXT;
     }
 
d1bf8a3a
     hevc->chromaFormatIDC = IS_YUV444(ctx->data_pix_fmt) ? 3 : 1;
 
     hevc->pixelBitDepthMinus8 = IS_10BIT(ctx->data_pix_fmt) ? 2 : 0;
82d705e2
 
b0172873
     hevc->level = ctx->level;
2a428db5
 
40df468a
     hevc->tier = ctx->tier;
82d705e2
 
     return 0;
 }
 
faffff88
 static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx)
82d705e2
 {
     switch (avctx->codec->id) {
     case AV_CODEC_ID_H264:
faffff88
         return nvenc_setup_h264_config(avctx);
     case AV_CODEC_ID_HEVC:
82d705e2
         return nvenc_setup_hevc_config(avctx);
     /* Earlier switch/case will return if unknown codec is passed. */
     }
 
     return 0;
 }
 
 static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
 {
     NvencContext *ctx = avctx->priv_data;
     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
 
     NV_ENC_PRESET_CONFIG preset_config = { 0 };
     NVENCSTATUS nv_status = NV_ENC_SUCCESS;
     AVCPBProperties *cpb_props;
     int res = 0;
     int dw, dh;
 
     ctx->encode_config.version = NV_ENC_CONFIG_VER;
     ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
 
faffff88
     ctx->init_encode_params.encodeHeight = avctx->height;
     ctx->init_encode_params.encodeWidth = avctx->width;
 
     ctx->init_encode_params.encodeConfig = &ctx->encode_config;
 
     nvenc_map_preset(ctx);
 
     preset_config.version = NV_ENC_PRESET_CONFIG_VER;
     preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
21175d85
 
faffff88
     nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder,
                                                     ctx->init_encode_params.encodeGUID,
                                                     ctx->init_encode_params.presetGUID,
                                                     &preset_config);
     if (nv_status != NV_ENC_SUCCESS)
         return nvenc_print_error(avctx, nv_status, "Cannot get the preset configuration");
2a428db5
 
faffff88
     memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
 
     ctx->encode_config.version = NV_ENC_CONFIG_VER;
fb34c580
 
f2dd6aee
     dw = avctx->width;
     dh = avctx->height;
     if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0) {
         dw*= avctx->sample_aspect_ratio.num;
         dh*= avctx->sample_aspect_ratio.den;
     }
     av_reduce(&dw, &dh, dw, dh, 1024 * 1024);
     ctx->init_encode_params.darHeight = dh;
     ctx->init_encode_params.darWidth = dw;
fb34c580
 
2a428db5
     ctx->init_encode_params.frameRateNum = avctx->time_base.den;
     ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
 
     ctx->init_encode_params.enableEncodeAsync = 0;
     ctx->init_encode_params.enablePTD = 1;
 
01775730
     if (ctx->weighted_pred == 1)
         ctx->init_encode_params.enableWeightedPrediction = 1;
 
9b425bd2
     if (ctx->bluray_compat) {
         ctx->aud = 1;
         avctx->refs = FFMIN(FFMAX(avctx->refs, 0), 6);
         avctx->max_b_frames = FFMIN(avctx->max_b_frames, 3);
         switch (avctx->codec->id) {
         case AV_CODEC_ID_H264:
             /* maximum level depends on used resolution */
             break;
         case AV_CODEC_ID_HEVC:
             ctx->level = NV_ENC_LEVEL_HEVC_51;
             ctx->tier = NV_ENC_TIER_HEVC_HIGH;
             break;
         }
     }
 
914fd42b
     if (avctx->gop_size > 0) {
         if (avctx->max_b_frames >= 0) {
8ef57a0d
             /* 0 is intra-only, 1 is I/P only, 2 is one B-Frame, 3 two B-frames, and so on. */
914fd42b
             ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
         }
 
2a428db5
         ctx->encode_config.gopLength = avctx->gop_size;
914fd42b
     } else if (avctx->gop_size == 0) {
         ctx->encode_config.frameIntervalP = 0;
         ctx->encode_config.gopLength = 1;
2a428db5
     }
 
e5babccf
     ctx->initial_pts[0] = AV_NOPTS_VALUE;
     ctx->initial_pts[1] = AV_NOPTS_VALUE;
914fd42b
 
de2faec2
     nvenc_recalc_surfaces(avctx);
 
faffff88
     nvenc_setup_rate_control(avctx);
2a428db5
 
94d68a41
     if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
2a428db5
         ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
     } else {
         ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
     }
 
faffff88
     res = nvenc_setup_codec_config(avctx);
82d705e2
     if (res)
         return res;
362e05f1
 
6fcbf39f
     res = nvenc_push_context(avctx);
     if (res < 0)
         return res;
43c417ac
 
82d705e2
     nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
43c417ac
 
6fcbf39f
     res = nvenc_pop_context(avctx);
     if (res < 0)
         return res;
43c417ac
 
82d705e2
     if (nv_status != NV_ENC_SUCCESS) {
e1691c44
         return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
82d705e2
     }
2a428db5
 
82d705e2
     if (ctx->encode_config.frameIntervalP > 1)
         avctx->has_b_frames = 2;
2a428db5
 
82d705e2
     if (ctx->encode_config.rcParams.averageBitRate > 0)
         avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
f1a88973
 
82d705e2
     cpb_props = ff_add_cpb_side_data(avctx);
     if (!cpb_props)
         return AVERROR(ENOMEM);
     cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
     cpb_props->avg_bitrate = avctx->bit_rate;
     cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
764f87b6
 
82d705e2
     return 0;
 }
b3557c79
 
27038693
 static NV_ENC_BUFFER_FORMAT nvenc_map_buffer_format(enum AVPixelFormat pix_fmt)
82d705e2
 {
27038693
     switch (pix_fmt) {
82d705e2
     case AV_PIX_FMT_YUV420P:
27038693
         return NV_ENC_BUFFER_FORMAT_YV12_PL;
82d705e2
     case AV_PIX_FMT_NV12:
27038693
         return NV_ENC_BUFFER_FORMAT_NV12_PL;
d1bf8a3a
     case AV_PIX_FMT_P010:
27038693
         return NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
82d705e2
     case AV_PIX_FMT_YUV444P:
27038693
         return NV_ENC_BUFFER_FORMAT_YUV444_PL;
d1bf8a3a
     case AV_PIX_FMT_YUV444P16:
27038693
         return NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
4aeb7a88
     case AV_PIX_FMT_0RGB32:
27038693
         return NV_ENC_BUFFER_FORMAT_ARGB;
4aeb7a88
     case AV_PIX_FMT_0BGR32:
27038693
         return NV_ENC_BUFFER_FORMAT_ABGR;
82d705e2
     default:
27038693
         return NV_ENC_BUFFER_FORMAT_UNDEFINED;
82d705e2
     }
27038693
 }
 
 static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
 {
     NvencContext *ctx = avctx->priv_data;
     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
8de3458a
     NvencSurface* tmp_surface = &ctx->surfaces[idx];
27038693
 
     NVENCSTATUS nv_status;
     NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
     allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
f1a88973
 
bff6d98b
     if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
a8cf25dd
         ctx->surfaces[idx].in_ref = av_frame_alloc();
         if (!ctx->surfaces[idx].in_ref)
             return AVERROR(ENOMEM);
     } else {
         NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
27038693
 
         ctx->surfaces[idx].format = nvenc_map_buffer_format(ctx->data_pix_fmt);
         if (ctx->surfaces[idx].format == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
             av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
                    av_get_pix_fmt_name(ctx->data_pix_fmt));
             return AVERROR(EINVAL);
         }
 
a8cf25dd
         allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
a1652aca
         allocSurf.width = avctx->width;
         allocSurf.height = avctx->height;
a8cf25dd
         allocSurf.bufferFmt = ctx->surfaces[idx].format;
 
         nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
         if (nv_status != NV_ENC_SUCCESS) {
             return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
         }
 
         ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
         ctx->surfaces[idx].width = allocSurf.width;
         ctx->surfaces[idx].height = allocSurf.height;
82d705e2
     }
764f87b6
 
82d705e2
     nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
     if (nv_status != NV_ENC_SUCCESS) {
e1691c44
         int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
bff6d98b
         if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
a8cf25dd
             p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
         av_frame_free(&ctx->surfaces[idx].in_ref);
e1691c44
         return err;
82d705e2
     }
7b0689c5
 
e1691c44
     ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
     ctx->surfaces[idx].size = allocOut.size;
7b0689c5
 
8de3458a
     av_fifo_generic_write(ctx->unused_surface_queue, &tmp_surface, sizeof(tmp_surface), NULL);
 
82d705e2
     return 0;
 }
2a428db5
 
b6933530
 static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx)
82d705e2
 {
     NvencContext *ctx = avctx->priv_data;
4e93f00b
     int i, res = 0, res2;
2a428db5
 
f052ef30
     ctx->surfaces = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->surfaces));
     if (!ctx->surfaces)
82d705e2
         return AVERROR(ENOMEM);
2a428db5
 
f052ef30
     ctx->timestamp_list = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
cfb49fc6
     if (!ctx->timestamp_list)
         return AVERROR(ENOMEM);
8de3458a
 
     ctx->unused_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
     if (!ctx->unused_surface_queue)
         return AVERROR(ENOMEM);
 
f052ef30
     ctx->output_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
cfb49fc6
     if (!ctx->output_surface_queue)
         return AVERROR(ENOMEM);
f052ef30
     ctx->output_surface_ready_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
cfb49fc6
     if (!ctx->output_surface_ready_queue)
         return AVERROR(ENOMEM);
 
6fcbf39f
     res = nvenc_push_context(avctx);
     if (res < 0)
         return res;
43c417ac
 
f052ef30
     for (i = 0; i < ctx->nb_surfaces; i++) {
b6933530
         if ((res = nvenc_alloc_surface(avctx, i)) < 0)
4e93f00b
             goto fail;
43c417ac
     }
 
4e93f00b
 fail:
     res2 = nvenc_pop_context(avctx);
     if (res2 < 0)
         return res2;
2a428db5
 
4e93f00b
     return res;
82d705e2
 }
2a428db5
 
82d705e2
 static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
 {
     NvencContext *ctx = avctx->priv_data;
     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
2a428db5
 
82d705e2
     NVENCSTATUS nv_status;
     uint32_t outSize = 0;
     char tmpHeader[256];
     NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
     payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
2a428db5
 
82d705e2
     payload.spsppsBuffer = tmpHeader;
     payload.inBufferSize = sizeof(tmpHeader);
     payload.outSPSPPSPayloadSize = &outSize;
2a428db5
 
82d705e2
     nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
     if (nv_status != NV_ENC_SUCCESS) {
e1691c44
         return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
82d705e2
     }
2a428db5
 
82d705e2
     avctx->extradata_size = outSize;
     avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
2a428db5
 
82d705e2
     if (!avctx->extradata) {
         return AVERROR(ENOMEM);
     }
2a428db5
 
82d705e2
     memcpy(avctx->extradata, tmpHeader, outSize);
2a428db5
 
82d705e2
     return 0;
 }
2a428db5
 
b6933530
 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
82d705e2
 {
b6933530
     NvencContext *ctx               = avctx->priv_data;
82d705e2
     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
6fcbf39f
     int i, res;
2a428db5
 
b6933530
     /* the encoder has to be flushed before it can be closed */
     if (ctx->nvencoder) {
         NV_ENC_PIC_PARAMS params        = { .version        = NV_ENC_PIC_PARAMS_VER,
                                             .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
2a428db5
 
6fcbf39f
         res = nvenc_push_context(avctx);
         if (res < 0)
             return res;
0e995eac
 
b6933530
         p_nvenc->nvEncEncodePicture(ctx->nvencoder, &params);
82d705e2
     }
b08caa87
 
cfb49fc6
     av_fifo_freep(&ctx->timestamp_list);
     av_fifo_freep(&ctx->output_surface_ready_queue);
     av_fifo_freep(&ctx->output_surface_queue);
8de3458a
     av_fifo_freep(&ctx->unused_surface_queue);
2a428db5
 
bff6d98b
     if (ctx->surfaces && (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11)) {
f052ef30
         for (i = 0; i < ctx->nb_surfaces; ++i) {
a8cf25dd
             if (ctx->surfaces[i].input_surface) {
                  p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->surfaces[i].in_map.mappedResource);
             }
         }
         for (i = 0; i < ctx->nb_registered_frames; i++) {
             if (ctx->registered_frames[i].regptr)
                 p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
         }
         ctx->nb_registered_frames = 0;
     }
 
b6933530
     if (ctx->surfaces) {
f052ef30
         for (i = 0; i < ctx->nb_surfaces; ++i) {
bff6d98b
             if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
b6933530
                 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
             av_frame_free(&ctx->surfaces[i].in_ref);
             p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
         }
2a428db5
     }
cfb49fc6
     av_freep(&ctx->surfaces);
f052ef30
     ctx->nb_surfaces = 0;
2a428db5
 
0e995eac
     if (ctx->nvencoder) {
b6933530
         p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
2a428db5
 
6fcbf39f
         res = nvenc_pop_context(avctx);
         if (res < 0)
             return res;
43c417ac
     }
0e995eac
     ctx->nvencoder = NULL;
43c417ac
 
a8cf25dd
     if (ctx->cu_context_internal)
a66835bc
         dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal);
a8cf25dd
     ctx->cu_context = ctx->cu_context_internal = NULL;
2a428db5
 
bff6d98b
 #if CONFIG_D3D11VA
     if (ctx->d3d11_device) {
         ID3D11Device_Release(ctx->d3d11_device);
         ctx->d3d11_device = NULL;
     }
 #endif
 
a66835bc
     nvenc_free_functions(&dl_fn->nvenc_dl);
     cuda_free_functions(&dl_fn->cuda_dl);
b6933530
 
     dl_fn->nvenc_device_count = 0;
 
     av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
 
     return 0;
 }
 
 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
 {
0d021cc8
     NvencContext *ctx = avctx->priv_data;
     int ret;
b6933530
 
bff6d98b
     if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
0d021cc8
         AVHWFramesContext *frames_ctx;
         if (!avctx->hw_frames_ctx) {
             av_log(avctx, AV_LOG_ERROR,
                    "hw_frames_ctx must be set when using GPU frames as input\n");
             return AVERROR(EINVAL);
         }
         frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
bff6d98b
         if (frames_ctx->format != avctx->pix_fmt) {
             av_log(avctx, AV_LOG_ERROR,
                    "hw_frames_ctx must match the GPU frame type\n");
             return AVERROR(EINVAL);
         }
0d021cc8
         ctx->data_pix_fmt = frames_ctx->sw_format;
     } else {
         ctx->data_pix_fmt = avctx->pix_fmt;
     }
b6933530
 
0d021cc8
     if ((ret = nvenc_load_libraries(avctx)) < 0)
         return ret;
b6933530
 
0d021cc8
     if ((ret = nvenc_setup_device(avctx)) < 0)
         return ret;
b6933530
 
0d021cc8
     if ((ret = nvenc_setup_encoder(avctx)) < 0)
         return ret;
b6933530
 
0d021cc8
     if ((ret = nvenc_setup_surfaces(avctx)) < 0)
         return ret;
b6933530
 
     if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
0d021cc8
         if ((ret = nvenc_setup_extradata(avctx)) < 0)
             return ret;
b6933530
     }
2a428db5
 
     return 0;
 }
 
e1691c44
 static NvencSurface *get_free_frame(NvencContext *ctx)
82d705e2
 {
8de3458a
     NvencSurface *tmp_surf;
82d705e2
 
8de3458a
     if (!(av_fifo_size(ctx->unused_surface_queue) > 0))
         // queue empty
         return NULL;
82d705e2
 
8de3458a
     av_fifo_generic_read(ctx->unused_surface_queue, &tmp_surf, sizeof(tmp_surf), NULL);
     return tmp_surf;
82d705e2
 }
 
96cba1c5
 static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *nv_surface,
             NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params, const AVFrame *frame)
82d705e2
 {
96cba1c5
     int dst_linesize[4] = {
         lock_buffer_params->pitch,
         lock_buffer_params->pitch,
         lock_buffer_params->pitch,
         lock_buffer_params->pitch
     };
     uint8_t *dst_data[4];
     int ret;
d1bf8a3a
 
96cba1c5
     if (frame->format == AV_PIX_FMT_YUV420P)
         dst_linesize[1] = dst_linesize[2] >>= 1;
d1bf8a3a
 
96cba1c5
     ret = av_image_fill_pointers(dst_data, frame->format, nv_surface->height,
                                  lock_buffer_params->bufferDataPtr, dst_linesize);
     if (ret < 0)
         return ret;
d1bf8a3a
 
96cba1c5
     if (frame->format == AV_PIX_FMT_YUV420P)
         FFSWAP(uint8_t*, dst_data[1], dst_data[2]);
d1bf8a3a
 
96cba1c5
     av_image_copy(dst_data, dst_linesize,
                   (const uint8_t**)frame->data, frame->linesize, frame->format,
8ebe1ddd
                   avctx->width, avctx->height);
82d705e2
 
     return 0;
 }
 
a8cf25dd
 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
 {
     NvencContext *ctx = avctx->priv_data;
     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
 
     int i;
 
     if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
         for (i = 0; i < ctx->nb_registered_frames; i++) {
             if (!ctx->registered_frames[i].mapped) {
                 if (ctx->registered_frames[i].regptr) {
                     p_nvenc->nvEncUnregisterResource(ctx->nvencoder,
                                                 ctx->registered_frames[i].regptr);
                     ctx->registered_frames[i].regptr = NULL;
                 }
                 return i;
             }
         }
     } else {
         return ctx->nb_registered_frames++;
     }
 
     av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
     return AVERROR(ENOMEM);
 }
 
 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
 {
     NvencContext *ctx = avctx->priv_data;
     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
 
f89a89c5
     AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frame->hw_frames_ctx->data;
a8cf25dd
     NV_ENC_REGISTER_RESOURCE reg;
     int i, idx, ret;
 
     for (i = 0; i < ctx->nb_registered_frames; i++) {
bff6d98b
         if (avctx->pix_fmt == AV_PIX_FMT_CUDA && ctx->registered_frames[i].ptr == frame->data[0])
             return i;
         else if (avctx->pix_fmt == AV_PIX_FMT_D3D11 && ctx->registered_frames[i].ptr == frame->data[0] && ctx->registered_frames[i].ptr_index == (intptr_t)frame->data[1])
a8cf25dd
             return i;
     }
 
     idx = nvenc_find_free_reg_resource(avctx);
     if (idx < 0)
         return idx;
 
     reg.version            = NV_ENC_REGISTER_RESOURCE_VER;
     reg.width              = frames_ctx->width;
     reg.height             = frames_ctx->height;
     reg.pitch              = frame->linesize[0];
     reg.resourceToRegister = frame->data[0];
 
bff6d98b
     if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
         reg.resourceType   = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
     }
     else if (avctx->pix_fmt == AV_PIX_FMT_D3D11) {
         reg.resourceType     = NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX;
         reg.subResourceIndex = (intptr_t)frame->data[1];
     }
 
27038693
     reg.bufferFormat       = nvenc_map_buffer_format(frames_ctx->sw_format);
     if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
         av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
                av_get_pix_fmt_name(frames_ctx->sw_format));
         return AVERROR(EINVAL);
     }
 
a8cf25dd
     ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, &reg);
     if (ret != NV_ENC_SUCCESS) {
         nvenc_print_error(avctx, ret, "Error registering an input resource");
         return AVERROR_UNKNOWN;
     }
 
bff6d98b
     ctx->registered_frames[idx].ptr       = frame->data[0];
     ctx->registered_frames[idx].ptr_index = reg.subResourceIndex;
     ctx->registered_frames[idx].regptr    = reg.registeredResource;
a8cf25dd
     return idx;
 }
 
82d705e2
 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
e1691c44
                                       NvencSurface *nvenc_frame)
82d705e2
 {
     NvencContext *ctx = avctx->priv_data;
     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
 
     int res;
     NVENCSTATUS nv_status;
 
bff6d98b
     if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
a8cf25dd
         int reg_idx = nvenc_register_frame(avctx, frame);
         if (reg_idx < 0) {
bff6d98b
             av_log(avctx, AV_LOG_ERROR, "Could not register an input HW frame\n");
a8cf25dd
             return reg_idx;
         }
82d705e2
 
a8cf25dd
         res = av_frame_ref(nvenc_frame->in_ref, frame);
         if (res < 0)
             return res;
82d705e2
 
a8cf25dd
         nvenc_frame->in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
         nvenc_frame->in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
         nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &nvenc_frame->in_map);
         if (nv_status != NV_ENC_SUCCESS) {
             av_frame_unref(nvenc_frame->in_ref);
             return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
         }
82d705e2
 
a8cf25dd
         ctx->registered_frames[reg_idx].mapped = 1;
         nvenc_frame->reg_idx                   = reg_idx;
         nvenc_frame->input_surface             = nvenc_frame->in_map.mappedResource;
8a3fea14
         nvenc_frame->format                    = nvenc_frame->in_map.mappedBufferFmt;
fa3ecad0
         nvenc_frame->pitch                     = frame->linesize[0];
a8cf25dd
         return 0;
     } else {
         NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
82d705e2
 
a8cf25dd
         lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
         lockBufferParams.inputBuffer = nvenc_frame->input_surface;
 
         nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
         if (nv_status != NV_ENC_SUCCESS) {
             return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
         }
 
fa3ecad0
         nvenc_frame->pitch = lockBufferParams.pitch;
a8cf25dd
         res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
 
         nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
         if (nv_status != NV_ENC_SUCCESS) {
             return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
         }
 
         return res;
     }
82d705e2
 }
 
 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
2f53b5b7
                                             NV_ENC_PIC_PARAMS *params)
82d705e2
 {
     NvencContext *ctx = avctx->priv_data;
 
     switch (avctx->codec->id) {
     case AV_CODEC_ID_H264:
2f53b5b7
         params->codecPicParams.h264PicParams.sliceMode =
             ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
         params->codecPicParams.h264PicParams.sliceModeData =
             ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
82d705e2
       break;
2f53b5b7
     case AV_CODEC_ID_HEVC:
         params->codecPicParams.hevcPicParams.sliceMode =
             ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
         params->codecPicParams.hevcPicParams.sliceModeData =
             ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
         break;
82d705e2
     }
 }
 
2f53b5b7
 static inline void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
 {
     av_fifo_generic_write(queue, &timestamp, sizeof(timestamp), NULL);
 }
 
 static inline int64_t timestamp_queue_dequeue(AVFifoBuffer* queue)
 {
     int64_t timestamp = AV_NOPTS_VALUE;
     if (av_fifo_size(queue) > 0)
         av_fifo_generic_read(queue, &timestamp, sizeof(timestamp), NULL);
 
     return timestamp;
 }
 
d3463912
 static int nvenc_set_timestamp(AVCodecContext *avctx,
                                NV_ENC_LOCK_BITSTREAM *params,
                                AVPacket *pkt)
 {
     NvencContext *ctx = avctx->priv_data;
 
     pkt->pts = params->outputTimeStamp;
 
e5babccf
     /* generate the first dts by linearly extrapolating the
      * first two pts values to the past */
     if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
         ctx->initial_pts[1] != AV_NOPTS_VALUE) {
         int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
         int64_t delta;
 
         if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
             (ts0 > 0 && ts1 < INT64_MIN + ts0))
             return AVERROR(ERANGE);
         delta = ts1 - ts0;
d3463912
 
e5babccf
         if ((delta < 0 && ts0 > INT64_MAX + delta) ||
             (delta > 0 && ts0 < INT64_MIN + delta))
             return AVERROR(ERANGE);
         pkt->dts = ts0 - delta;
 
         ctx->first_packet_output = 1;
         return 0;
     }
d3463912
 
e5babccf
     pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
d3463912
 
     return 0;
 }
 
e1691c44
 static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
2a428db5
 {
     NvencContext *ctx = avctx->priv_data;
     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
 
21175d85
     uint32_t slice_mode_data;
a19989ca
     uint32_t *slice_offsets = NULL;
2a428db5
     NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
     NVENCSTATUS nv_status;
     int res = 0;
 
fd55470c
     enum AVPictureType pict_type;
 
21175d85
     switch (avctx->codec->id) {
     case AV_CODEC_ID_H264:
       slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
       break;
     case AV_CODEC_ID_H265:
       slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
       break;
     default:
49046580
       av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
21175d85
       res = AVERROR(EINVAL);
       goto error;
     }
     slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
 
eb69e7be
     if (!slice_offsets) {
         res = AVERROR(ENOMEM);
d3463912
         goto error;
eb69e7be
     }
2a428db5
 
     lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
 
     lock_params.doNotWait = 0;
     lock_params.outputBitstream = tmpoutsurf->output_surface;
     lock_params.sliceOffsets = slice_offsets;
 
     nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
     if (nv_status != NV_ENC_SUCCESS) {
e1691c44
         res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
2a428db5
         goto error;
     }
 
49046580
     if (res = ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes,0)) {
2a428db5
         p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
         goto error;
     }
 
     memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
 
     nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
     if (nv_status != NV_ENC_SUCCESS)
e1691c44
         nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
2a428db5
 
a8cf25dd
 
bff6d98b
     if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
a8cf25dd
         p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, tmpoutsurf->in_map.mappedResource);
         av_frame_unref(tmpoutsurf->in_ref);
         ctx->registered_frames[tmpoutsurf->reg_idx].mapped = 0;
 
         tmpoutsurf->input_surface = NULL;
     }
 
2a428db5
     switch (lock_params.pictureType) {
     case NV_ENC_PIC_TYPE_IDR:
         pkt->flags |= AV_PKT_FLAG_KEY;
     case NV_ENC_PIC_TYPE_I:
fd55470c
         pict_type = AV_PICTURE_TYPE_I;
2a428db5
         break;
     case NV_ENC_PIC_TYPE_P:
fd55470c
         pict_type = AV_PICTURE_TYPE_P;
2a428db5
         break;
     case NV_ENC_PIC_TYPE_B:
fd55470c
         pict_type = AV_PICTURE_TYPE_B;
2a428db5
         break;
     case NV_ENC_PIC_TYPE_BI:
fd55470c
         pict_type = AV_PICTURE_TYPE_BI;
2a428db5
         break;
     default:
         av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
         av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
         res = AVERROR_EXTERNAL;
         goto error;
fd55470c
     }
 
 #if FF_API_CODED_FRAME
 FF_DISABLE_DEPRECATION_WARNINGS
     avctx->coded_frame->pict_type = pict_type;
40cf1bba
 FF_ENABLE_DEPRECATION_WARNINGS
 #endif
fd55470c
 
     ff_side_data_set_encoder_stats(pkt,
         (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
2a428db5
 
d3463912
     res = nvenc_set_timestamp(avctx, &lock_params, pkt);
     if (res < 0)
         goto error2;
2a428db5
 
     av_free(slice_offsets);
 
     return 0;
 
 error:
d3463912
     timestamp_queue_dequeue(ctx->timestamp_list);
2a428db5
 
d3463912
 error2:
2a428db5
     av_free(slice_offsets);
 
     return res;
 }
 
2f53b5b7
 static int output_ready(AVCodecContext *avctx, int flush)
cfb49fc6
 {
2f53b5b7
     NvencContext *ctx = avctx->priv_data;
cfb49fc6
     int nb_ready, nb_pending;
 
e5babccf
     /* when B-frames are enabled, we wait for two initial timestamps to
      * calculate the first dts */
     if (!flush && avctx->max_b_frames > 0 &&
         (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
         return 0;
 
cfb49fc6
     nb_ready   = av_fifo_size(ctx->output_surface_ready_queue)   / sizeof(NvencSurface*);
     nb_pending = av_fifo_size(ctx->output_surface_queue)         / sizeof(NvencSurface*);
2f53b5b7
     if (flush)
         return nb_ready > 0;
     return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
cfb49fc6
 }
 
a56d0497
 int ff_nvenc_send_frame(AVCodecContext *avctx, const AVFrame *frame)
2a428db5
 {
     NVENCSTATUS nv_status;
d0961d30
     NvencSurface *tmp_out_surf, *in_surf;
6fcbf39f
     int res, res2;
2a428db5
 
     NvencContext *ctx = avctx->priv_data;
     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
 
     NV_ENC_PIC_PARAMS pic_params = { 0 };
     pic_params.version = NV_ENC_PIC_PARAMS_VER;
 
bff6d98b
     if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
a56d0497
         return AVERROR(EINVAL);
 
     if (ctx->encoder_flushing)
         return AVERROR_EOF;
 
2a428db5
     if (frame) {
d0961d30
         in_surf = get_free_frame(ctx);
         if (!in_surf)
a56d0497
             return AVERROR(EAGAIN);
2a428db5
 
6fcbf39f
         res = nvenc_push_context(avctx);
         if (res < 0)
             return res;
be74ba64
 
d0961d30
         res = nvenc_upload_frame(avctx, frame, in_surf);
be74ba64
 
6fcbf39f
         res2 = nvenc_pop_context(avctx);
         if (res2 < 0)
             return res2;
be74ba64
 
a56d0497
         if (res)
82d705e2
             return res;
2a428db5
 
d0961d30
         pic_params.inputBuffer = in_surf->input_surface;
         pic_params.bufferFmt = in_surf->format;
         pic_params.inputWidth = in_surf->width;
         pic_params.inputHeight = in_surf->height;
         pic_params.inputPitch = in_surf->pitch;
         pic_params.outputBitstream = in_surf->output_surface;
2a428db5
 
7c6eb0a1
         if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
2f53b5b7
             if (frame->top_field_first)
2a428db5
                 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
2f53b5b7
             else
2a428db5
                 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
         } else {
             pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
         }
 
30c55875
         if (ctx->forced_idr >= 0 && frame->pict_type == AV_PICTURE_TYPE_I) {
             pic_params.encodePicFlags =
                 ctx->forced_idr ? NV_ENC_PIC_FLAG_FORCEIDR : NV_ENC_PIC_FLAG_FORCEINTRA;
         } else {
             pic_params.encodePicFlags = 0;
         }
 
2a428db5
         pic_params.inputTimeStamp = frame->pts;
82d705e2
 
         nvenc_codec_specific_pic_params(avctx, &pic_params);
2a428db5
     } else {
         pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
a56d0497
         ctx->encoder_flushing = 1;
2a428db5
     }
 
6fcbf39f
     res = nvenc_push_context(avctx);
     if (res < 0)
         return res;
be74ba64
 
2a428db5
     nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
be74ba64
 
6fcbf39f
     res = nvenc_pop_context(avctx);
     if (res < 0)
         return res;
be74ba64
 
2f53b5b7
     if (nv_status != NV_ENC_SUCCESS &&
         nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
         return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
2a428db5
 
58c6dcb4
     if (frame) {
d0961d30
         av_fifo_generic_write(ctx->output_surface_queue, &in_surf, sizeof(in_surf), NULL);
58c6dcb4
         timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
e5babccf
 
         if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
             ctx->initial_pts[0] = frame->pts;
         else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
             ctx->initial_pts[1] = frame->pts;
58c6dcb4
     }
2a428db5
 
2f53b5b7
     /* all the pending buffers are now ready for output */
     if (nv_status == NV_ENC_SUCCESS) {
cfb49fc6
         while (av_fifo_size(ctx->output_surface_queue) > 0) {
d0961d30
             av_fifo_generic_read(ctx->output_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
             av_fifo_generic_write(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2a428db5
         }
     }
 
a56d0497
     return 0;
 }
 
 int ff_nvenc_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
 {
d0961d30
     NvencSurface *tmp_out_surf;
6fcbf39f
     int res, res2;
a56d0497
 
     NvencContext *ctx = avctx->priv_data;
 
bff6d98b
     if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
a56d0497
         return AVERROR(EINVAL);
 
     if (output_ready(avctx, ctx->encoder_flushing)) {
d0961d30
         av_fifo_generic_read(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2a428db5
 
6fcbf39f
         res = nvenc_push_context(avctx);
         if (res < 0)
             return res;
43c417ac
 
d0961d30
         res = process_output_surface(avctx, pkt, tmp_out_surf);
2a428db5
 
6fcbf39f
         res2 = nvenc_pop_context(avctx);
         if (res2 < 0)
             return res2;
43c417ac
 
2a428db5
         if (res)
             return res;
 
d0961d30
         av_fifo_generic_write(ctx->unused_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
a56d0497
     } else if (ctx->encoder_flushing) {
         return AVERROR_EOF;
2a428db5
     } else {
a56d0497
         return AVERROR(EAGAIN);
     }
 
     return 0;
 }
 
 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
                           const AVFrame *frame, int *got_packet)
 {
     NvencContext *ctx = avctx->priv_data;
     int res;
 
     if (!ctx->encoder_flushing) {
         res = ff_nvenc_send_frame(avctx, frame);
         if (res < 0)
             return res;
     }
 
     res = ff_nvenc_receive_packet(avctx, pkt);
     if (res == AVERROR(EAGAIN) || res == AVERROR_EOF) {
2a428db5
         *got_packet = 0;
a56d0497
     } else if (res < 0) {
         return res;
     } else {
         *got_packet = 1;
2a428db5
     }
 
     return 0;
 }