]> git.sesse.net Git - ffmpeg/blob - libavcodec/nvenc.c
nvenc: only write the VUI signal type fields if they are set
[ffmpeg] / libavcodec / nvenc.c
1 /*
2  * NVIDIA NVENC Support
3  * Copyright (C) 2015 Luca Barbato
4  *
5  * This file is part of Libav.
6  *
7  * Libav 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.
11  *
12  * Libav 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.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with Libav; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "config.h"
23
24 #include <cuda.h>
25 #include <nvEncodeAPI.h>
26 #include <string.h>
27
28 #define CUDA_LIBNAME "libcuda.so"
29
30 #if HAVE_DLFCN_H
31 #include <dlfcn.h>
32
33 #define NVENC_LIBNAME "libnvidia-encode.so"
34
35 #elif HAVE_WINDOWS_H
36 #include <windows.h>
37
38 #if ARCH_X86_64
39 #define NVENC_LIBNAME "nvEncodeAPI64.dll"
40 #else
41 #define NVENC_LIBNAME "nvEncodeAPI.dll"
42 #endif
43
44 #define dlopen(filename, flags) LoadLibrary((filename))
45 #define dlsym(handle, symbol)   GetProcAddress(handle, symbol)
46 #define dlclose(handle)         FreeLibrary(handle)
47 #endif
48
49 #include "libavutil/common.h"
50 #include "libavutil/hwcontext.h"
51 #include "libavutil/hwcontext_cuda.h"
52 #include "libavutil/imgutils.h"
53 #include "libavutil/mem.h"
54 #include "avcodec.h"
55 #include "internal.h"
56 #include "nvenc.h"
57
58 #define NVENC_CAP 0x30
59 #define BITSTREAM_BUFFER_SIZE 1024 * 1024
60 #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR ||               \
61                     rc == NV_ENC_PARAMS_RC_2_PASS_QUALITY ||    \
62                     rc == NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP)
63
64 #define LOAD_LIBRARY(l, path)                   \
65     do {                                        \
66         if (!((l) = dlopen(path, RTLD_LAZY))) { \
67             av_log(avctx, AV_LOG_ERROR,         \
68                    "Cannot load %s\n",          \
69                    path);                       \
70             return AVERROR_UNKNOWN;             \
71         }                                       \
72     } while (0)
73
74 #define LOAD_SYMBOL(fun, lib, symbol)        \
75     do {                                     \
76         if (!((fun) = dlsym(lib, symbol))) { \
77             av_log(avctx, AV_LOG_ERROR,      \
78                    "Cannot load %s\n",       \
79                    symbol);                  \
80             return AVERROR_UNKNOWN;          \
81         }                                    \
82     } while (0)
83
84 const enum AVPixelFormat ff_nvenc_pix_fmts[] = {
85     AV_PIX_FMT_NV12,
86     AV_PIX_FMT_YUV420P,
87     AV_PIX_FMT_YUV444P,
88     AV_PIX_FMT_CUDA,
89     AV_PIX_FMT_NONE
90 };
91
92 static const struct {
93     NVENCSTATUS nverr;
94     int         averr;
95     const char *desc;
96 } nvenc_errors[] = {
97     { NV_ENC_SUCCESS,                      0,                "success"                  },
98     { NV_ENC_ERR_NO_ENCODE_DEVICE,         AVERROR(ENOENT),  "no encode device"         },
99     { NV_ENC_ERR_UNSUPPORTED_DEVICE,       AVERROR(ENOSYS),  "unsupported device"       },
100     { NV_ENC_ERR_INVALID_ENCODERDEVICE,    AVERROR(EINVAL),  "invalid encoder device"   },
101     { NV_ENC_ERR_INVALID_DEVICE,           AVERROR(EINVAL),  "invalid device"           },
102     { NV_ENC_ERR_DEVICE_NOT_EXIST,         AVERROR(EIO),     "device does not exist"    },
103     { NV_ENC_ERR_INVALID_PTR,              AVERROR(EFAULT),  "invalid ptr"              },
104     { NV_ENC_ERR_INVALID_EVENT,            AVERROR(EINVAL),  "invalid event"            },
105     { NV_ENC_ERR_INVALID_PARAM,            AVERROR(EINVAL),  "invalid param"            },
106     { NV_ENC_ERR_INVALID_CALL,             AVERROR(EINVAL),  "invalid call"             },
107     { NV_ENC_ERR_OUT_OF_MEMORY,            AVERROR(ENOMEM),  "out of memory"            },
108     { NV_ENC_ERR_ENCODER_NOT_INITIALIZED,  AVERROR(EINVAL),  "encoder not initialized"  },
109     { NV_ENC_ERR_UNSUPPORTED_PARAM,        AVERROR(ENOSYS),  "unsupported param"        },
110     { NV_ENC_ERR_LOCK_BUSY,                AVERROR(EAGAIN),  "lock busy"                },
111     { NV_ENC_ERR_NOT_ENOUGH_BUFFER,        AVERROR(ENOBUFS), "not enough buffer"        },
112     { NV_ENC_ERR_INVALID_VERSION,          AVERROR(EINVAL),  "invalid version"          },
113     { NV_ENC_ERR_MAP_FAILED,               AVERROR(EIO),     "map failed"               },
114     { NV_ENC_ERR_NEED_MORE_INPUT,          AVERROR(EAGAIN),  "need more input"          },
115     { NV_ENC_ERR_ENCODER_BUSY,             AVERROR(EAGAIN),  "encoder busy"             },
116     { NV_ENC_ERR_EVENT_NOT_REGISTERD,      AVERROR(EBADF),   "event not registered"     },
117     { NV_ENC_ERR_GENERIC,                  AVERROR_UNKNOWN,  "generic error"            },
118     { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY,  AVERROR(EINVAL),  "incompatible client key"  },
119     { NV_ENC_ERR_UNIMPLEMENTED,            AVERROR(ENOSYS),  "unimplemented"            },
120     { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO),     "resource register failed" },
121     { NV_ENC_ERR_RESOURCE_NOT_REGISTERED,  AVERROR(EBADF),   "resource not registered"  },
122     { NV_ENC_ERR_RESOURCE_NOT_MAPPED,      AVERROR(EBADF),   "resource not mapped"      },
123 };
124
125 static int nvenc_map_error(NVENCSTATUS err, const char **desc)
126 {
127     int i;
128     for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
129         if (nvenc_errors[i].nverr == err) {
130             if (desc)
131                 *desc = nvenc_errors[i].desc;
132             return nvenc_errors[i].averr;
133         }
134     }
135     if (desc)
136         *desc = "unknown error";
137     return AVERROR_UNKNOWN;
138 }
139
140 static int nvenc_print_error(void *log_ctx, NVENCSTATUS err,
141                              const char *error_string)
142 {
143     const char *desc;
144     int ret;
145     ret = nvenc_map_error(err, &desc);
146     av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
147     return ret;
148 }
149
150 static av_cold int nvenc_load_libraries(AVCodecContext *avctx)
151 {
152     NVENCContext *ctx         = avctx->priv_data;
153     NVENCLibraryContext *nvel = &ctx->nvel;
154     PNVENCODEAPICREATEINSTANCE nvenc_create_instance;
155     NVENCSTATUS err;
156
157 #if CONFIG_CUDA
158     nvel->cu_init                      = cuInit;
159     nvel->cu_device_get_count          = cuDeviceGetCount;
160     nvel->cu_device_get                = cuDeviceGet;
161     nvel->cu_device_get_name           = cuDeviceGetName;
162     nvel->cu_device_compute_capability = cuDeviceComputeCapability;
163     nvel->cu_ctx_create                = cuCtxCreate_v2;
164     nvel->cu_ctx_pop_current           = cuCtxPopCurrent_v2;
165     nvel->cu_ctx_destroy               = cuCtxDestroy_v2;
166 #else
167     LOAD_LIBRARY(nvel->cuda, CUDA_LIBNAME);
168
169     LOAD_SYMBOL(nvel->cu_init, nvel->cuda, "cuInit");
170     LOAD_SYMBOL(nvel->cu_device_get_count, nvel->cuda, "cuDeviceGetCount");
171     LOAD_SYMBOL(nvel->cu_device_get, nvel->cuda, "cuDeviceGet");
172     LOAD_SYMBOL(nvel->cu_device_get_name, nvel->cuda, "cuDeviceGetName");
173     LOAD_SYMBOL(nvel->cu_device_compute_capability, nvel->cuda,
174                 "cuDeviceComputeCapability");
175     LOAD_SYMBOL(nvel->cu_ctx_create, nvel->cuda, "cuCtxCreate_v2");
176     LOAD_SYMBOL(nvel->cu_ctx_pop_current, nvel->cuda, "cuCtxPopCurrent_v2");
177     LOAD_SYMBOL(nvel->cu_ctx_destroy, nvel->cuda, "cuCtxDestroy_v2");
178 #endif
179
180     LOAD_LIBRARY(nvel->nvenc, NVENC_LIBNAME);
181
182     LOAD_SYMBOL(nvenc_create_instance, nvel->nvenc,
183                 "NvEncodeAPICreateInstance");
184
185     nvel->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
186
187     err = nvenc_create_instance(&nvel->nvenc_funcs);
188     if (err != NV_ENC_SUCCESS)
189         return nvenc_print_error(avctx, err, "Cannot create the NVENC instance");
190
191     return 0;
192 }
193
194 static int nvenc_open_session(AVCodecContext *avctx)
195 {
196     NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
197     NVENCContext *ctx                           = avctx->priv_data;
198     NV_ENCODE_API_FUNCTION_LIST *nv             = &ctx->nvel.nvenc_funcs;
199     int ret;
200
201     params.version    = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
202     params.apiVersion = NVENCAPI_VERSION;
203     params.device     = ctx->cu_context;
204     params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
205
206     ret = nv->nvEncOpenEncodeSessionEx(&params, &ctx->nvenc_ctx);
207     if (ret != NV_ENC_SUCCESS) {
208         ctx->nvenc_ctx = NULL;
209         return nvenc_print_error(avctx, ret, "Cannot open the NVENC Session");
210     }
211
212     return 0;
213 }
214
215 static int nvenc_check_codec_support(AVCodecContext *avctx)
216 {
217     NVENCContext *ctx               = avctx->priv_data;
218     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
219     int i, ret, count = 0;
220     GUID *guids = NULL;
221
222     ret = nv->nvEncGetEncodeGUIDCount(ctx->nvenc_ctx, &count);
223
224     if (ret != NV_ENC_SUCCESS || !count)
225         return AVERROR(ENOSYS);
226
227     guids = av_malloc(count * sizeof(GUID));
228     if (!guids)
229         return AVERROR(ENOMEM);
230
231     ret = nv->nvEncGetEncodeGUIDs(ctx->nvenc_ctx, guids, count, &count);
232     if (ret != NV_ENC_SUCCESS) {
233         ret = AVERROR(ENOSYS);
234         goto fail;
235     }
236
237     ret = AVERROR(ENOSYS);
238     for (i = 0; i < count; i++) {
239         if (!memcmp(&guids[i], &ctx->params.encodeGUID, sizeof(*guids))) {
240             ret = 0;
241             break;
242         }
243     }
244
245 fail:
246     av_free(guids);
247
248     return ret;
249 }
250
251 static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
252 {
253     NVENCContext *ctx               = avctx->priv_data;
254     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
255     NV_ENC_CAPS_PARAM params        = { 0 };
256     int ret, val = 0;
257
258     params.version     = NV_ENC_CAPS_PARAM_VER;
259     params.capsToQuery = cap;
260
261     ret = nv->nvEncGetEncodeCaps(ctx->nvenc_ctx, ctx->params.encodeGUID, &params, &val);
262
263     if (ret == NV_ENC_SUCCESS)
264         return val;
265     return 0;
266 }
267
268 static int nvenc_check_capabilities(AVCodecContext *avctx)
269 {
270     NVENCContext *ctx = avctx->priv_data;
271     int ret;
272
273     ret = nvenc_check_codec_support(avctx);
274     if (ret < 0) {
275         av_log(avctx, AV_LOG_VERBOSE, "Codec not supported\n");
276         return ret;
277     }
278
279     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
280     if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P && ret <= 0) {
281         av_log(avctx, AV_LOG_VERBOSE, "YUV444P not supported\n");
282         return AVERROR(ENOSYS);
283     }
284
285     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
286     if (ret < avctx->width) {
287         av_log(avctx, AV_LOG_VERBOSE, "Width %d exceeds %d\n",
288                avctx->width, ret);
289         return AVERROR(ENOSYS);
290     }
291
292     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
293     if (ret < avctx->height) {
294         av_log(avctx, AV_LOG_VERBOSE, "Height %d exceeds %d\n",
295                avctx->height, ret);
296         return AVERROR(ENOSYS);
297     }
298
299     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
300     if (ret < avctx->max_b_frames) {
301         av_log(avctx, AV_LOG_VERBOSE, "Max B-frames %d exceed %d\n",
302                avctx->max_b_frames, ret);
303
304         return AVERROR(ENOSYS);
305     }
306
307     return 0;
308 }
309
310 static int nvenc_check_device(AVCodecContext *avctx, int idx)
311 {
312     NVENCContext *ctx               = avctx->priv_data;
313     NVENCLibraryContext *nvel       = &ctx->nvel;
314     char name[128]                  = { 0 };
315     int major, minor, ret;
316     CUdevice cu_device;
317     CUcontext dummy;
318     int loglevel = AV_LOG_VERBOSE;
319
320     if (ctx->device == LIST_DEVICES)
321         loglevel = AV_LOG_INFO;
322
323     ret = nvel->cu_device_get(&cu_device, idx);
324     if (ret != CUDA_SUCCESS) {
325         av_log(avctx, AV_LOG_ERROR,
326                "Cannot access the CUDA device %d\n",
327                idx);
328         return -1;
329     }
330
331     ret = nvel->cu_device_get_name(name, sizeof(name), cu_device);
332     if (ret != CUDA_SUCCESS)
333         return -1;
334
335     ret = nvel->cu_device_compute_capability(&major, &minor, cu_device);
336     if (ret != CUDA_SUCCESS)
337         return -1;
338
339     av_log(avctx, loglevel, "Device %d [%s] ", cu_device, name);
340
341     if (((major << 4) | minor) < NVENC_CAP)
342         goto fail;
343
344     ret = nvel->cu_ctx_create(&ctx->cu_context_internal, 0, cu_device);
345     if (ret != CUDA_SUCCESS)
346         goto fail;
347
348     ctx->cu_context = ctx->cu_context_internal;
349
350     ret = nvel->cu_ctx_pop_current(&dummy);
351     if (ret != CUDA_SUCCESS)
352         goto fail2;
353
354     if ((ret = nvenc_open_session(avctx)) < 0)
355         goto fail2;
356
357     if ((ret = nvenc_check_capabilities(avctx)) < 0)
358         goto fail3;
359
360     av_log(avctx, loglevel, "supports NVENC\n");
361
362     if (ctx->device == cu_device || ctx->device == ANY_DEVICE)
363         return 0;
364
365 fail3:
366     nvel->nvenc_funcs.nvEncDestroyEncoder(ctx->nvenc_ctx);
367     ctx->nvenc_ctx = NULL;
368
369 fail2:
370     nvel->cu_ctx_destroy(ctx->cu_context_internal);
371     ctx->cu_context_internal = NULL;
372
373 fail:
374     if (ret != 0)
375         av_log(avctx, loglevel, "does not support NVENC (major %d minor %d)\n",
376                major, minor);
377
378     return AVERROR(ENOSYS);
379 }
380
381 static int nvenc_setup_device(AVCodecContext *avctx)
382 {
383     NVENCContext *ctx         = avctx->priv_data;
384     NVENCLibraryContext *nvel = &ctx->nvel;
385
386     switch (avctx->codec->id) {
387     case AV_CODEC_ID_H264:
388         ctx->params.encodeGUID = NV_ENC_CODEC_H264_GUID;
389         break;
390     case AV_CODEC_ID_HEVC:
391         ctx->params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
392         break;
393     default:
394         return AVERROR_BUG;
395     }
396
397     if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
398         AVHWFramesContext   *frames_ctx;
399         AVCUDADeviceContext *device_hwctx;
400         int ret;
401
402         if (!avctx->hw_frames_ctx)
403             return AVERROR(EINVAL);
404
405         frames_ctx   = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
406         device_hwctx = frames_ctx->device_ctx->hwctx;
407
408         ctx->cu_context = device_hwctx->cuda_ctx;
409
410         ret = nvenc_open_session(avctx);
411         if (ret < 0)
412             return ret;
413
414         ret = nvenc_check_capabilities(avctx);
415         if (ret < 0)
416             return ret;
417     } else {
418         int i, nb_devices = 0;
419
420         if ((nvel->cu_init(0)) != CUDA_SUCCESS) {
421             av_log(avctx, AV_LOG_ERROR,
422                    "Cannot init CUDA\n");
423             return AVERROR_UNKNOWN;
424         }
425
426         if ((nvel->cu_device_get_count(&nb_devices)) != CUDA_SUCCESS) {
427             av_log(avctx, AV_LOG_ERROR,
428                    "Cannot enumerate the CUDA devices\n");
429             return AVERROR_UNKNOWN;
430         }
431
432
433         for (i = 0; i < nb_devices; ++i) {
434             if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
435                 return 0;
436         }
437
438         if (ctx->device == LIST_DEVICES)
439             return AVERROR_EXIT;
440
441         return AVERROR(ENOSYS);
442     }
443
444     return 0;
445 }
446
447 typedef struct GUIDTuple {
448     const GUID guid;
449     int flags;
450 } GUIDTuple;
451
452 static int nvec_map_preset(NVENCContext *ctx)
453 {
454     GUIDTuple presets[] = {
455         { NV_ENC_PRESET_DEFAULT_GUID },
456         { NV_ENC_PRESET_HP_GUID },
457         { NV_ENC_PRESET_HQ_GUID },
458         { NV_ENC_PRESET_BD_GUID },
459         { NV_ENC_PRESET_LOW_LATENCY_DEFAULT_GUID, NVENC_LOWLATENCY },
460         { NV_ENC_PRESET_LOW_LATENCY_HP_GUID,      NVENC_LOWLATENCY },
461         { NV_ENC_PRESET_LOW_LATENCY_HQ_GUID,      NVENC_LOWLATENCY },
462         { NV_ENC_PRESET_LOSSLESS_DEFAULT_GUID,    NVENC_LOSSLESS },
463         { NV_ENC_PRESET_LOSSLESS_HP_GUID,         NVENC_LOSSLESS },
464         { { 0 } }
465     };
466
467     GUIDTuple *t = &presets[ctx->preset];
468
469     ctx->params.presetGUID = t->guid;
470     ctx->flags             = t->flags;
471
472     return AVERROR(EINVAL);
473 }
474
475 static void set_constqp(AVCodecContext *avctx, NV_ENC_RC_PARAMS *rc)
476 {
477     rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
478     rc->constQP.qpInterB = avctx->global_quality;
479     rc->constQP.qpInterP = avctx->global_quality;
480     rc->constQP.qpIntra  = avctx->global_quality;
481 }
482
483 static void set_vbr(AVCodecContext *avctx, NV_ENC_RC_PARAMS *rc)
484 {
485     if (avctx->qmin >= 0) {
486         rc->enableMinQP    = 1;
487         rc->minQP.qpInterB = avctx->qmin;
488         rc->minQP.qpInterP = avctx->qmin;
489         rc->minQP.qpIntra  = avctx->qmin;
490     }
491
492     if (avctx->qmax >= 0) {
493         rc->enableMaxQP = 1;
494         rc->maxQP.qpInterB = avctx->qmax;
495         rc->maxQP.qpInterP = avctx->qmax;
496         rc->maxQP.qpIntra  = avctx->qmax;
497     }
498 }
499
500 static void set_lossless(AVCodecContext *avctx, NV_ENC_RC_PARAMS *rc)
501 {
502     rc->rateControlMode  = NV_ENC_PARAMS_RC_CONSTQP;
503     rc->constQP.qpInterB = 0;
504     rc->constQP.qpInterP = 0;
505     rc->constQP.qpIntra  = 0;
506 }
507
508 static void nvenc_override_rate_control(AVCodecContext *avctx,
509                                         NV_ENC_RC_PARAMS *rc)
510 {
511     NVENCContext *ctx    = avctx->priv_data;
512
513     switch (ctx->rc) {
514     case NV_ENC_PARAMS_RC_CONSTQP:
515         if (avctx->global_quality < 0) {
516             av_log(avctx, AV_LOG_WARNING,
517                    "The constant quality rate-control requires "
518                    "the 'global_quality' option set.\n");
519             return;
520         }
521         set_constqp(avctx, rc);
522         return;
523     case NV_ENC_PARAMS_RC_2_PASS_VBR:
524     case NV_ENC_PARAMS_RC_VBR:
525         if (avctx->qmin < 0 && avctx->qmax < 0) {
526             av_log(avctx, AV_LOG_WARNING,
527                    "The variable bitrate rate-control requires "
528                    "the 'qmin' and/or 'qmax' option set.\n");
529             return;
530         }
531     case NV_ENC_PARAMS_RC_VBR_MINQP:
532         if (avctx->qmin < 0) {
533             av_log(avctx, AV_LOG_WARNING,
534                    "The variable bitrate rate-control requires "
535                    "the 'qmin' option set.\n");
536             return;
537         }
538         set_vbr(avctx, rc);
539         break;
540     case NV_ENC_PARAMS_RC_CBR:
541         break;
542     case NV_ENC_PARAMS_RC_2_PASS_QUALITY:
543     case NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP:
544         if (!(ctx->flags & NVENC_LOWLATENCY)) {
545             av_log(avctx, AV_LOG_WARNING,
546                    "The multipass rate-control requires "
547                    "a low-latency preset.\n");
548             return;
549         }
550     }
551
552     rc->rateControlMode = ctx->rc;
553 }
554
555 static void nvenc_setup_rate_control(AVCodecContext *avctx)
556 {
557     NVENCContext *ctx    = avctx->priv_data;
558     NV_ENC_RC_PARAMS *rc = &ctx->config.rcParams;
559
560     if (avctx->bit_rate > 0)
561         rc->averageBitRate = avctx->bit_rate;
562
563     if (avctx->rc_max_rate > 0)
564         rc->maxBitRate = avctx->rc_max_rate;
565
566     if (ctx->rc > 0) {
567         nvenc_override_rate_control(avctx, rc);
568     } else if (ctx->flags & NVENC_LOSSLESS) {
569         set_lossless(avctx, rc);
570     } else if (avctx->global_quality > 0) {
571         set_constqp(avctx, rc);
572     } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
573         rc->rateControlMode = NV_ENC_PARAMS_RC_VBR;
574         set_vbr(avctx, rc);
575     }
576
577     if (avctx->rc_buffer_size > 0)
578         rc->vbvBufferSize = avctx->rc_buffer_size;
579
580     if (rc->averageBitRate > 0)
581         avctx->bit_rate = rc->averageBitRate;
582 }
583
584 static int nvenc_setup_h264_config(AVCodecContext *avctx)
585 {
586     NVENCContext *ctx                      = avctx->priv_data;
587     NV_ENC_CONFIG *cc                      = &ctx->config;
588     NV_ENC_CONFIG_H264 *h264               = &cc->encodeCodecConfig.h264Config;
589     NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
590
591     vui->colourDescriptionPresentFlag = avctx->colorspace      != AVCOL_SPC_UNSPECIFIED ||
592                                         avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
593                                         avctx->color_trc       != AVCOL_TRC_UNSPECIFIED;
594
595     vui->colourMatrix            = avctx->colorspace;
596     vui->colourPrimaries         = avctx->color_primaries;
597     vui->transferCharacteristics = avctx->color_trc;
598
599     vui->videoFullRangeFlag = avctx->color_range == AVCOL_RANGE_JPEG;
600
601     vui->videoSignalTypePresentFlag = vui->colourDescriptionPresentFlag ||
602                                       vui->videoFullRangeFlag;
603
604     h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
605     h264->repeatSPSPPS  = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
606     h264->outputAUD     = 1;
607
608     h264->maxNumRefFrames = avctx->refs;
609     h264->idrPeriod       = cc->gopLength;
610
611     if (ctx->flags & NVENC_LOSSLESS)
612         h264->qpPrimeYZeroTransformBypassFlag = 1;
613
614     if (IS_CBR(cc->rcParams.rateControlMode)) {
615         h264->outputBufferingPeriodSEI = 1;
616         h264->outputPictureTimingSEI   = 1;
617     }
618
619     if (ctx->profile)
620         avctx->profile = ctx->profile;
621
622     if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P)
623         h264->chromaFormatIDC = 3;
624     else
625         h264->chromaFormatIDC = 1;
626
627     switch (ctx->profile) {
628     case NV_ENC_H264_PROFILE_BASELINE:
629         cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
630         break;
631     case NV_ENC_H264_PROFILE_MAIN:
632         cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
633         break;
634     case NV_ENC_H264_PROFILE_HIGH:
635         cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
636         break;
637     case NV_ENC_H264_PROFILE_HIGH_444:
638         cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
639         break;
640     case NV_ENC_H264_PROFILE_CONSTRAINED_HIGH:
641         cc->profileGUID = NV_ENC_H264_PROFILE_CONSTRAINED_HIGH_GUID;
642         break;
643     }
644
645     h264->level = ctx->level;
646
647     return 0;
648 }
649
650 static int nvenc_setup_hevc_config(AVCodecContext *avctx)
651 {
652     NVENCContext *ctx                      = avctx->priv_data;
653     NV_ENC_CONFIG *cc                      = &ctx->config;
654     NV_ENC_CONFIG_HEVC *hevc               = &cc->encodeCodecConfig.hevcConfig;
655
656     hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
657     hevc->repeatSPSPPS  = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
658     hevc->outputAUD     = 1;
659
660     hevc->maxNumRefFramesInDPB = avctx->refs;
661     hevc->idrPeriod            = cc->gopLength;
662
663     if (IS_CBR(cc->rcParams.rateControlMode)) {
664         hevc->outputBufferingPeriodSEI = 1;
665         hevc->outputPictureTimingSEI   = 1;
666     }
667
668     /* No other profile is supported in the current SDK version 5 */
669     cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
670     avctx->profile  = FF_PROFILE_HEVC_MAIN;
671
672     if (ctx->level) {
673         hevc->level = ctx->level;
674     } else {
675         hevc->level = NV_ENC_LEVEL_AUTOSELECT;
676     }
677
678     if (ctx->tier) {
679         hevc->tier = ctx->tier;
680     }
681
682     return 0;
683 }
684 static int nvenc_setup_codec_config(AVCodecContext *avctx)
685 {
686     switch (avctx->codec->id) {
687     case AV_CODEC_ID_H264:
688         return nvenc_setup_h264_config(avctx);
689     case AV_CODEC_ID_HEVC:
690         return nvenc_setup_hevc_config(avctx);
691     }
692     return 0;
693 }
694
695 static int nvenc_setup_encoder(AVCodecContext *avctx)
696 {
697     NVENCContext *ctx               = avctx->priv_data;
698     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
699     NV_ENC_PRESET_CONFIG preset_cfg = { 0 };
700     AVCPBProperties *cpb_props;
701     int ret;
702
703     ctx->params.version = NV_ENC_INITIALIZE_PARAMS_VER;
704
705     ctx->params.encodeHeight = avctx->height;
706     ctx->params.encodeWidth  = avctx->width;
707
708     if (avctx->sample_aspect_ratio.num &&
709         avctx->sample_aspect_ratio.den &&
710         (avctx->sample_aspect_ratio.num != 1 ||
711          avctx->sample_aspect_ratio.den != 1)) {
712         av_reduce(&ctx->params.darWidth,
713                   &ctx->params.darHeight,
714                   avctx->width * avctx->sample_aspect_ratio.num,
715                   avctx->height * avctx->sample_aspect_ratio.den,
716                   INT_MAX / 8);
717     } else {
718         ctx->params.darHeight = avctx->height;
719         ctx->params.darWidth  = avctx->width;
720     }
721
722     ctx->params.frameRateNum = avctx->time_base.den;
723     ctx->params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
724
725     ctx->params.enableEncodeAsync = 0;
726     ctx->params.enablePTD         = 1;
727
728     ctx->params.encodeConfig = &ctx->config;
729
730     nvec_map_preset(ctx);
731
732     preset_cfg.version           = NV_ENC_PRESET_CONFIG_VER;
733     preset_cfg.presetCfg.version = NV_ENC_CONFIG_VER;
734
735     ret = nv->nvEncGetEncodePresetConfig(ctx->nvenc_ctx,
736                                          ctx->params.encodeGUID,
737                                          ctx->params.presetGUID,
738                                          &preset_cfg);
739     if (ret != NV_ENC_SUCCESS)
740         return nvenc_print_error(avctx, ret, "Cannot get the preset configuration");
741
742     memcpy(&ctx->config, &preset_cfg.presetCfg, sizeof(ctx->config));
743
744     ctx->config.version = NV_ENC_CONFIG_VER;
745
746     if (avctx->gop_size > 0) {
747         if (avctx->max_b_frames > 0) {
748             /* 0 is intra-only,
749              * 1 is I/P only,
750              * 2 is one B-Frame,
751              * 3 two B-frames, and so on. */
752             ctx->config.frameIntervalP = avctx->max_b_frames + 1;
753         } else if (avctx->max_b_frames == 0) {
754             ctx->config.frameIntervalP = 1;
755         }
756         ctx->config.gopLength = avctx->gop_size;
757     } else if (avctx->gop_size == 0) {
758         ctx->config.frameIntervalP = 0;
759         ctx->config.gopLength      = 1;
760     }
761
762     if (ctx->config.frameIntervalP > 1)
763         avctx->max_b_frames = ctx->config.frameIntervalP - 1;
764
765     ctx->initial_pts[0] = AV_NOPTS_VALUE;
766     ctx->initial_pts[1] = AV_NOPTS_VALUE;
767
768     nvenc_setup_rate_control(avctx);
769
770     if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
771         ctx->config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
772     } else {
773         ctx->config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
774     }
775
776     if ((ret = nvenc_setup_codec_config(avctx)) < 0)
777         return ret;
778
779     ret = nv->nvEncInitializeEncoder(ctx->nvenc_ctx, &ctx->params);
780     if (ret != NV_ENC_SUCCESS)
781         return nvenc_print_error(avctx, ret, "Cannot initialize the decoder");
782
783     cpb_props = ff_add_cpb_side_data(avctx);
784     if (!cpb_props)
785         return AVERROR(ENOMEM);
786     cpb_props->max_bitrate = avctx->rc_max_rate;
787     cpb_props->min_bitrate = avctx->rc_min_rate;
788     cpb_props->avg_bitrate = avctx->bit_rate;
789     cpb_props->buffer_size = avctx->rc_buffer_size;
790
791     return 0;
792 }
793
794 static int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
795 {
796     NVENCContext *ctx               = avctx->priv_data;
797     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
798     int ret;
799     NV_ENC_CREATE_BITSTREAM_BUFFER out_buffer = { 0 };
800
801     switch (ctx->data_pix_fmt) {
802     case AV_PIX_FMT_YUV420P:
803         ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YV12_PL;
804         break;
805     case AV_PIX_FMT_NV12:
806         ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_NV12_PL;
807         break;
808     case AV_PIX_FMT_YUV444P:
809         ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YUV444_PL;
810         break;
811     default:
812         return AVERROR_BUG;
813     }
814
815     if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
816         ctx->frames[idx].in_ref = av_frame_alloc();
817         if (!ctx->frames[idx].in_ref)
818             return AVERROR(ENOMEM);
819     } else {
820         NV_ENC_CREATE_INPUT_BUFFER in_buffer      = { 0 };
821
822         in_buffer.version  = NV_ENC_CREATE_INPUT_BUFFER_VER;
823
824         in_buffer.width  = avctx->width;
825         in_buffer.height = avctx->height;
826
827         in_buffer.bufferFmt  = ctx->frames[idx].format;
828         in_buffer.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED;
829
830         ret = nv->nvEncCreateInputBuffer(ctx->nvenc_ctx, &in_buffer);
831         if (ret != NV_ENC_SUCCESS)
832             return nvenc_print_error(avctx, ret, "CreateInputBuffer failed");
833
834         ctx->frames[idx].in     = in_buffer.inputBuffer;
835     }
836
837     out_buffer.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
838     /* 1MB is large enough to hold most output frames.
839      * NVENC increases this automatically if it is not enough. */
840     out_buffer.size = BITSTREAM_BUFFER_SIZE;
841
842     out_buffer.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED;
843
844     ret = nv->nvEncCreateBitstreamBuffer(ctx->nvenc_ctx, &out_buffer);
845     if (ret != NV_ENC_SUCCESS)
846         return nvenc_print_error(avctx, ret, "CreateBitstreamBuffer failed");
847
848     ctx->frames[idx].out  = out_buffer.bitstreamBuffer;
849
850     return 0;
851 }
852
853 static int nvenc_setup_surfaces(AVCodecContext *avctx)
854 {
855     NVENCContext *ctx = avctx->priv_data;
856     int i, ret;
857
858     ctx->nb_surfaces = FFMAX(4 + avctx->max_b_frames,
859                              ctx->nb_surfaces);
860     ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
861
862
863     ctx->frames = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->frames));
864     if (!ctx->frames)
865         return AVERROR(ENOMEM);
866
867     ctx->timestamps = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
868     if (!ctx->timestamps)
869         return AVERROR(ENOMEM);
870     ctx->pending = av_fifo_alloc(ctx->nb_surfaces * sizeof(*ctx->frames));
871     if (!ctx->pending)
872         return AVERROR(ENOMEM);
873     ctx->ready = av_fifo_alloc(ctx->nb_surfaces * sizeof(*ctx->frames));
874     if (!ctx->ready)
875         return AVERROR(ENOMEM);
876
877     for (i = 0; i < ctx->nb_surfaces; i++) {
878         if ((ret = nvenc_alloc_surface(avctx, i)) < 0)
879             return ret;
880     }
881
882     return 0;
883 }
884
885 #define EXTRADATA_SIZE 512
886
887 static int nvenc_setup_extradata(AVCodecContext *avctx)
888 {
889     NVENCContext *ctx                     = avctx->priv_data;
890     NV_ENCODE_API_FUNCTION_LIST *nv       = &ctx->nvel.nvenc_funcs;
891     NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
892     int ret;
893
894     avctx->extradata = av_mallocz(EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
895     if (!avctx->extradata)
896         return AVERROR(ENOMEM);
897
898     payload.version              = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
899     payload.spsppsBuffer         = avctx->extradata;
900     payload.inBufferSize         = EXTRADATA_SIZE;
901     payload.outSPSPPSPayloadSize = &avctx->extradata_size;
902
903     ret = nv->nvEncGetSequenceParams(ctx->nvenc_ctx, &payload);
904     if (ret != NV_ENC_SUCCESS)
905         return nvenc_print_error(avctx, ret, "Cannot get the extradata");
906
907     return 0;
908 }
909
910 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
911 {
912     NVENCContext *ctx               = avctx->priv_data;
913     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
914     int i;
915
916     /* the encoder has to be flushed before it can be closed */
917     if (ctx->nvenc_ctx) {
918         NV_ENC_PIC_PARAMS params        = { .version        = NV_ENC_PIC_PARAMS_VER,
919                                             .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
920
921         nv->nvEncEncodePicture(ctx->nvenc_ctx, &params);
922     }
923
924     av_fifo_free(ctx->timestamps);
925     av_fifo_free(ctx->pending);
926     av_fifo_free(ctx->ready);
927
928     if (ctx->frames) {
929         for (i = 0; i < ctx->nb_surfaces; ++i) {
930             if (avctx->pix_fmt != AV_PIX_FMT_CUDA) {
931                 nv->nvEncDestroyInputBuffer(ctx->nvenc_ctx, ctx->frames[i].in);
932             } else if (ctx->frames[i].in) {
933                 nv->nvEncUnmapInputResource(ctx->nvenc_ctx, ctx->frames[i].in_map.mappedResource);
934             }
935
936             av_frame_free(&ctx->frames[i].in_ref);
937             nv->nvEncDestroyBitstreamBuffer(ctx->nvenc_ctx, ctx->frames[i].out);
938         }
939     }
940     for (i = 0; i < ctx->nb_registered_frames; i++) {
941         if (ctx->registered_frames[i].regptr)
942             nv->nvEncUnregisterResource(ctx->nvenc_ctx, ctx->registered_frames[i].regptr);
943     }
944     ctx->nb_registered_frames = 0;
945
946     av_freep(&ctx->frames);
947
948     if (ctx->nvenc_ctx)
949         nv->nvEncDestroyEncoder(ctx->nvenc_ctx);
950
951     if (ctx->cu_context_internal)
952         ctx->nvel.cu_ctx_destroy(ctx->cu_context_internal);
953
954     if (ctx->nvel.nvenc)
955         dlclose(ctx->nvel.nvenc);
956
957 #if !CONFIG_CUDA
958     if (ctx->nvel.cuda)
959         dlclose(ctx->nvel.cuda);
960 #endif
961
962     return 0;
963 }
964
965 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
966 {
967     NVENCContext *ctx = avctx->priv_data;
968     int ret;
969
970     if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
971         AVHWFramesContext *frames_ctx;
972         if (!avctx->hw_frames_ctx) {
973             av_log(avctx, AV_LOG_ERROR,
974                    "hw_frames_ctx must be set when using GPU frames as input\n");
975             return AVERROR(EINVAL);
976         }
977         frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
978         ctx->data_pix_fmt = frames_ctx->sw_format;
979     } else {
980         ctx->data_pix_fmt = avctx->pix_fmt;
981     }
982
983     if ((ret = nvenc_load_libraries(avctx)) < 0)
984         return ret;
985
986     if ((ret = nvenc_setup_device(avctx)) < 0)
987         return ret;
988
989     if ((ret = nvenc_setup_encoder(avctx)) < 0)
990         return ret;
991
992     if ((ret = nvenc_setup_surfaces(avctx)) < 0)
993         return ret;
994
995     if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
996         if ((ret = nvenc_setup_extradata(avctx)) < 0)
997             return ret;
998     }
999
1000     return 0;
1001 }
1002
1003 static NVENCFrame *get_free_frame(NVENCContext *ctx)
1004 {
1005     int i;
1006
1007     for (i = 0; i < ctx->nb_surfaces; i++) {
1008         if (!ctx->frames[i].locked) {
1009             ctx->frames[i].locked = 1;
1010             return &ctx->frames[i];
1011         }
1012     }
1013
1014     return NULL;
1015 }
1016
1017 static int nvenc_copy_frame(NV_ENC_LOCK_INPUT_BUFFER *in, const AVFrame *frame)
1018 {
1019     uint8_t *buf = in->bufferDataPtr;
1020     int off      = frame->height * in->pitch;
1021
1022     switch (frame->format) {
1023     case AV_PIX_FMT_YUV420P:
1024         av_image_copy_plane(buf, in->pitch,
1025                             frame->data[0], frame->linesize[0],
1026                             frame->width, frame->height);
1027         buf += off;
1028
1029         av_image_copy_plane(buf, in->pitch >> 1,
1030                             frame->data[2], frame->linesize[2],
1031                             frame->width >> 1, frame->height >> 1);
1032
1033         buf += off >> 2;
1034
1035         av_image_copy_plane(buf, in->pitch >> 1,
1036                             frame->data[1], frame->linesize[1],
1037                             frame->width >> 1, frame->height >> 1);
1038         break;
1039     case AV_PIX_FMT_NV12:
1040         av_image_copy_plane(buf, in->pitch,
1041                             frame->data[0], frame->linesize[0],
1042                             frame->width, frame->height);
1043         buf += off;
1044
1045         av_image_copy_plane(buf, in->pitch,
1046                             frame->data[1], frame->linesize[1],
1047                             frame->width, frame->height >> 1);
1048         break;
1049     case AV_PIX_FMT_YUV444P:
1050         av_image_copy_plane(buf, in->pitch,
1051                             frame->data[0], frame->linesize[0],
1052                             frame->width, frame->height);
1053         buf += off;
1054
1055         av_image_copy_plane(buf, in->pitch,
1056                             frame->data[1], frame->linesize[1],
1057                             frame->width, frame->height);
1058         buf += off;
1059
1060         av_image_copy_plane(buf, in->pitch,
1061                             frame->data[2], frame->linesize[2],
1062                             frame->width, frame->height);
1063         break;
1064     default:
1065         return AVERROR_BUG;
1066     }
1067
1068     return 0;
1069 }
1070
1071 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1072 {
1073     NVENCContext               *ctx = avctx->priv_data;
1074     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1075     int i;
1076
1077     if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1078         for (i = 0; i < ctx->nb_registered_frames; i++) {
1079             if (!ctx->registered_frames[i].mapped) {
1080                 if (ctx->registered_frames[i].regptr) {
1081                     nv->nvEncUnregisterResource(ctx->nvenc_ctx,
1082                                                 ctx->registered_frames[i].regptr);
1083                     ctx->registered_frames[i].regptr = NULL;
1084                 }
1085                 return i;
1086             }
1087         }
1088     } else {
1089         return ctx->nb_registered_frames++;
1090     }
1091
1092     av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1093     return AVERROR(ENOMEM);
1094 }
1095
1096 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1097 {
1098     NVENCContext               *ctx = avctx->priv_data;
1099     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1100     AVHWFramesContext   *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1101     NV_ENC_REGISTER_RESOURCE reg;
1102     int i, idx, ret;
1103
1104     for (i = 0; i < ctx->nb_registered_frames; i++) {
1105         if (ctx->registered_frames[i].ptr == (CUdeviceptr)frame->data[0])
1106             return i;
1107     }
1108
1109     idx = nvenc_find_free_reg_resource(avctx);
1110     if (idx < 0)
1111         return idx;
1112
1113     reg.version            = NV_ENC_REGISTER_RESOURCE_VER;
1114     reg.resourceType       = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1115     reg.width              = frames_ctx->width;
1116     reg.height             = frames_ctx->height;
1117     reg.bufferFormat       = ctx->frames[0].format;
1118     reg.pitch              = frame->linesize[0];
1119     reg.resourceToRegister = frame->data[0];
1120
1121     ret = nv->nvEncRegisterResource(ctx->nvenc_ctx, &reg);
1122     if (ret != NV_ENC_SUCCESS) {
1123         nvenc_print_error(avctx, ret, "Error registering an input resource");
1124         return AVERROR_UNKNOWN;
1125     }
1126
1127     ctx->registered_frames[idx].ptr    = (CUdeviceptr)frame->data[0];
1128     ctx->registered_frames[idx].regptr = reg.registeredResource;
1129     return idx;
1130 }
1131
1132 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1133                               NVENCFrame *nvenc_frame)
1134 {
1135     NVENCContext *ctx               = avctx->priv_data;
1136     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1137     int ret;
1138
1139     if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1140         int reg_idx;
1141
1142         ret = nvenc_register_frame(avctx, frame);
1143         if (ret < 0) {
1144             av_log(avctx, AV_LOG_ERROR, "Could not register an input CUDA frame\n");
1145             return ret;
1146         }
1147         reg_idx = ret;
1148
1149         ret = av_frame_ref(nvenc_frame->in_ref, frame);
1150         if (ret < 0)
1151             return ret;
1152
1153         nvenc_frame->in_map.version            = NV_ENC_MAP_INPUT_RESOURCE_VER;
1154         nvenc_frame->in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1155
1156         ret = nv->nvEncMapInputResource(ctx->nvenc_ctx, &nvenc_frame->in_map);
1157         if (ret != NV_ENC_SUCCESS) {
1158             av_frame_unref(nvenc_frame->in_ref);
1159             return nvenc_print_error(avctx, ret, "Error mapping an input resource");
1160         }
1161
1162         ctx->registered_frames[reg_idx].mapped = 1;
1163         nvenc_frame->reg_idx                   = reg_idx;
1164         nvenc_frame->in                        = nvenc_frame->in_map.mappedResource;
1165     } else {
1166         NV_ENC_LOCK_INPUT_BUFFER params = { 0 };
1167
1168         params.version     = NV_ENC_LOCK_INPUT_BUFFER_VER;
1169         params.inputBuffer = nvenc_frame->in;
1170
1171         ret = nv->nvEncLockInputBuffer(ctx->nvenc_ctx, &params);
1172         if (ret != NV_ENC_SUCCESS)
1173             return nvenc_print_error(avctx, ret, "Cannot lock the buffer");
1174
1175         ret = nvenc_copy_frame(&params, frame);
1176         if (ret < 0) {
1177             nv->nvEncUnlockInputBuffer(ctx->nvenc_ctx, nvenc_frame->in);
1178             return ret;
1179         }
1180
1181         ret = nv->nvEncUnlockInputBuffer(ctx->nvenc_ctx, nvenc_frame->in);
1182         if (ret != NV_ENC_SUCCESS)
1183             return nvenc_print_error(avctx, ret, "Cannot unlock the buffer");
1184     }
1185
1186     return 0;
1187 }
1188
1189 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1190                                             NV_ENC_PIC_PARAMS *params)
1191 {
1192     NVENCContext *ctx = avctx->priv_data;
1193
1194     switch (avctx->codec->id) {
1195     case AV_CODEC_ID_H264:
1196         params->codecPicParams.h264PicParams.sliceMode =
1197             ctx->config.encodeCodecConfig.h264Config.sliceMode;
1198         params->codecPicParams.h264PicParams.sliceModeData =
1199             ctx->config.encodeCodecConfig.h264Config.sliceModeData;
1200         break;
1201     case AV_CODEC_ID_HEVC:
1202         params->codecPicParams.hevcPicParams.sliceMode =
1203             ctx->config.encodeCodecConfig.hevcConfig.sliceMode;
1204         params->codecPicParams.hevcPicParams.sliceModeData =
1205             ctx->config.encodeCodecConfig.hevcConfig.sliceModeData;
1206         break;
1207     }
1208 }
1209
1210 static inline int nvenc_enqueue_timestamp(AVFifoBuffer *f, int64_t pts)
1211 {
1212     return av_fifo_generic_write(f, &pts, sizeof(pts), NULL);
1213 }
1214
1215 static inline int nvenc_dequeue_timestamp(AVFifoBuffer *f, int64_t *pts)
1216 {
1217     return av_fifo_generic_read(f, pts, sizeof(*pts), NULL);
1218 }
1219
1220 static int nvenc_set_timestamp(AVCodecContext *avctx,
1221                                NV_ENC_LOCK_BITSTREAM *params,
1222                                AVPacket *pkt)
1223 {
1224     NVENCContext *ctx = avctx->priv_data;
1225
1226     pkt->pts      = params->outputTimeStamp;
1227     pkt->duration = params->outputDuration;
1228
1229     /* generate the first dts by linearly extrapolating the
1230      * first two pts values to the past */
1231     if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
1232         ctx->initial_pts[1] != AV_NOPTS_VALUE) {
1233         int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
1234         int64_t delta;
1235
1236         if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
1237             (ts0 > 0 && ts1 < INT64_MIN + ts0))
1238             return AVERROR(ERANGE);
1239         delta = ts1 - ts0;
1240
1241         if ((delta < 0 && ts0 > INT64_MAX + delta) ||
1242             (delta > 0 && ts0 < INT64_MIN + delta))
1243             return AVERROR(ERANGE);
1244         pkt->dts = ts0 - delta;
1245
1246         ctx->first_packet_output = 1;
1247         return 0;
1248     }
1249     return nvenc_dequeue_timestamp(ctx->timestamps, &pkt->dts);
1250 }
1251
1252 static int nvenc_get_output(AVCodecContext *avctx, AVPacket *pkt)
1253 {
1254     NVENCContext *ctx               = avctx->priv_data;
1255     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1256     NV_ENC_LOCK_BITSTREAM params    = { 0 };
1257     NVENCFrame *frame;
1258     int ret;
1259
1260     ret = av_fifo_generic_read(ctx->ready, &frame, sizeof(frame), NULL);
1261     if (ret)
1262         return ret;
1263
1264     params.version         = NV_ENC_LOCK_BITSTREAM_VER;
1265     params.outputBitstream = frame->out;
1266
1267     ret = nv->nvEncLockBitstream(ctx->nvenc_ctx, &params);
1268     if (ret < 0)
1269         return nvenc_print_error(avctx, ret, "Cannot lock the bitstream");
1270
1271     ret = ff_alloc_packet(pkt, params.bitstreamSizeInBytes);
1272     if (ret < 0)
1273         return ret;
1274
1275     memcpy(pkt->data, params.bitstreamBufferPtr, pkt->size);
1276
1277     ret = nv->nvEncUnlockBitstream(ctx->nvenc_ctx, frame->out);
1278     if (ret < 0)
1279         return nvenc_print_error(avctx, ret, "Cannot unlock the bitstream");
1280
1281     if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1282         nv->nvEncUnmapInputResource(ctx->nvenc_ctx, frame->in_map.mappedResource);
1283         av_frame_unref(frame->in_ref);
1284         ctx->registered_frames[frame->reg_idx].mapped = 0;
1285
1286         frame->in = NULL;
1287     }
1288
1289     frame->locked = 0;
1290
1291     ret = nvenc_set_timestamp(avctx, &params, pkt);
1292     if (ret < 0)
1293         return ret;
1294
1295     switch (params.pictureType) {
1296     case NV_ENC_PIC_TYPE_IDR:
1297         pkt->flags |= AV_PKT_FLAG_KEY;
1298 #if FF_API_CODED_FRAME
1299 FF_DISABLE_DEPRECATION_WARNINGS
1300     case NV_ENC_PIC_TYPE_INTRA_REFRESH:
1301     case NV_ENC_PIC_TYPE_I:
1302         avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
1303         break;
1304     case NV_ENC_PIC_TYPE_P:
1305         avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
1306         break;
1307     case NV_ENC_PIC_TYPE_B:
1308         avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;
1309         break;
1310     case NV_ENC_PIC_TYPE_BI:
1311         avctx->coded_frame->pict_type = AV_PICTURE_TYPE_BI;
1312         break;
1313 FF_ENABLE_DEPRECATION_WARNINGS
1314 #endif
1315     }
1316
1317     return 0;
1318 }
1319
1320 static int output_ready(AVCodecContext *avctx, int flush)
1321 {
1322     NVENCContext *ctx = avctx->priv_data;
1323     int nb_ready, nb_pending;
1324
1325     /* when B-frames are enabled, we wait for two initial timestamps to
1326      * calculate the first dts */
1327     if (!flush && avctx->max_b_frames > 0 &&
1328         (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
1329         return 0;
1330
1331     nb_ready   = av_fifo_size(ctx->ready)   / sizeof(NVENCFrame*);
1332     nb_pending = av_fifo_size(ctx->pending) / sizeof(NVENCFrame*);
1333     if (flush)
1334         return nb_ready > 0;
1335     return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
1336 }
1337
1338 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1339                           const AVFrame *frame, int *got_packet)
1340 {
1341     NVENCContext *ctx               = avctx->priv_data;
1342     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1343     NV_ENC_PIC_PARAMS params        = { 0 };
1344     NVENCFrame         *nvenc_frame = NULL;
1345     int enc_ret, ret;
1346
1347     params.version = NV_ENC_PIC_PARAMS_VER;
1348
1349     if (frame) {
1350         nvenc_frame = get_free_frame(ctx);
1351         if (!nvenc_frame) {
1352             av_log(avctx, AV_LOG_ERROR, "No free surfaces\n");
1353             return AVERROR_BUG;
1354         }
1355
1356         ret = nvenc_upload_frame(avctx, frame, nvenc_frame);
1357         if (ret < 0)
1358             return ret;
1359
1360         params.inputBuffer     = nvenc_frame->in;
1361         params.bufferFmt       = nvenc_frame->format;
1362         params.inputWidth      = frame->width;
1363         params.inputHeight     = frame->height;
1364         params.outputBitstream = nvenc_frame->out;
1365         params.inputTimeStamp  = frame->pts;
1366
1367         if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1368             if (frame->top_field_first)
1369                 params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
1370             else
1371                 params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
1372         } else {
1373             params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1374         }
1375
1376         nvenc_codec_specific_pic_params(avctx, &params);
1377
1378         ret = nvenc_enqueue_timestamp(ctx->timestamps, frame->pts);
1379         if (ret < 0)
1380             return ret;
1381
1382         if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
1383             ctx->initial_pts[0] = frame->pts;
1384         else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
1385             ctx->initial_pts[1] = frame->pts;
1386     } else {
1387         params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1388     }
1389
1390     enc_ret = nv->nvEncEncodePicture(ctx->nvenc_ctx, &params);
1391     if (enc_ret != NV_ENC_SUCCESS &&
1392         enc_ret != NV_ENC_ERR_NEED_MORE_INPUT)
1393         return nvenc_print_error(avctx, enc_ret, "Error encoding the frame");
1394
1395     if (nvenc_frame) {
1396         ret = av_fifo_generic_write(ctx->pending, &nvenc_frame, sizeof(nvenc_frame), NULL);
1397         if (ret < 0)
1398             return ret;
1399     }
1400
1401     /* all the pending buffers are now ready for output */
1402     if (enc_ret == NV_ENC_SUCCESS) {
1403         while (av_fifo_size(ctx->pending) > 0) {
1404             av_fifo_generic_read(ctx->pending, &nvenc_frame, sizeof(nvenc_frame), NULL);
1405             av_fifo_generic_write(ctx->ready,  &nvenc_frame, sizeof(nvenc_frame), NULL);
1406         }
1407     }
1408
1409     if (output_ready(avctx, !frame)) {
1410         ret = nvenc_get_output(avctx, pkt);
1411         if (ret < 0)
1412             return ret;
1413         *got_packet = 1;
1414     } else {
1415         *got_packet = 0;
1416     }
1417
1418     return 0;
1419 }