]> git.sesse.net Git - ffmpeg/blob - libavcodec/nvenc.c
nvenc: Generate bufferingPeriod/pictureTiming SEI
[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 = 1;
592     vui->videoSignalTypePresentFlag   = 1;
593
594     vui->colourMatrix            = avctx->colorspace;
595     vui->colourPrimaries         = avctx->color_primaries;
596     vui->transferCharacteristics = avctx->color_trc;
597
598     vui->videoFullRangeFlag = avctx->color_range == AVCOL_RANGE_JPEG;
599
600     h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
601     h264->repeatSPSPPS  = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
602     h264->outputAUD     = 1;
603
604     h264->maxNumRefFrames = avctx->refs;
605     h264->idrPeriod       = cc->gopLength;
606
607     if (ctx->flags & NVENC_LOSSLESS)
608         h264->qpPrimeYZeroTransformBypassFlag = 1;
609
610     if (IS_CBR(cc->rcParams.rateControlMode)) {
611         h264->outputBufferingPeriodSEI = 1;
612         h264->outputPictureTimingSEI   = 1;
613     }
614
615     if (ctx->profile)
616         avctx->profile = ctx->profile;
617
618     if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P)
619         h264->chromaFormatIDC = 3;
620     else
621         h264->chromaFormatIDC = 1;
622
623     switch (ctx->profile) {
624     case NV_ENC_H264_PROFILE_BASELINE:
625         cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
626         break;
627     case NV_ENC_H264_PROFILE_MAIN:
628         cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
629         break;
630     case NV_ENC_H264_PROFILE_HIGH:
631         cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
632         break;
633     case NV_ENC_H264_PROFILE_HIGH_444:
634         cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
635         break;
636     case NV_ENC_H264_PROFILE_CONSTRAINED_HIGH:
637         cc->profileGUID = NV_ENC_H264_PROFILE_CONSTRAINED_HIGH_GUID;
638         break;
639     }
640
641     h264->level = ctx->level;
642
643     return 0;
644 }
645
646 static int nvenc_setup_hevc_config(AVCodecContext *avctx)
647 {
648     NVENCContext *ctx                      = avctx->priv_data;
649     NV_ENC_CONFIG *cc                      = &ctx->config;
650     NV_ENC_CONFIG_HEVC *hevc               = &cc->encodeCodecConfig.hevcConfig;
651
652     hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
653     hevc->repeatSPSPPS  = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
654     hevc->outputAUD     = 1;
655
656     hevc->maxNumRefFramesInDPB = avctx->refs;
657     hevc->idrPeriod            = cc->gopLength;
658
659     if (IS_CBR(cc->rcParams.rateControlMode)) {
660         hevc->outputBufferingPeriodSEI = 1;
661         hevc->outputPictureTimingSEI   = 1;
662     }
663
664     /* No other profile is supported in the current SDK version 5 */
665     cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
666     avctx->profile  = FF_PROFILE_HEVC_MAIN;
667
668     if (ctx->level) {
669         hevc->level = ctx->level;
670     } else {
671         hevc->level = NV_ENC_LEVEL_AUTOSELECT;
672     }
673
674     if (ctx->tier) {
675         hevc->tier = ctx->tier;
676     }
677
678     return 0;
679 }
680 static int nvenc_setup_codec_config(AVCodecContext *avctx)
681 {
682     switch (avctx->codec->id) {
683     case AV_CODEC_ID_H264:
684         return nvenc_setup_h264_config(avctx);
685     case AV_CODEC_ID_HEVC:
686         return nvenc_setup_hevc_config(avctx);
687     }
688     return 0;
689 }
690
691 static int nvenc_setup_encoder(AVCodecContext *avctx)
692 {
693     NVENCContext *ctx               = avctx->priv_data;
694     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
695     NV_ENC_PRESET_CONFIG preset_cfg = { 0 };
696     AVCPBProperties *cpb_props;
697     int ret;
698
699     ctx->params.version = NV_ENC_INITIALIZE_PARAMS_VER;
700
701     ctx->params.encodeHeight = avctx->height;
702     ctx->params.encodeWidth  = avctx->width;
703
704     if (avctx->sample_aspect_ratio.num &&
705         avctx->sample_aspect_ratio.den &&
706         (avctx->sample_aspect_ratio.num != 1 ||
707          avctx->sample_aspect_ratio.den != 1)) {
708         av_reduce(&ctx->params.darWidth,
709                   &ctx->params.darHeight,
710                   avctx->width * avctx->sample_aspect_ratio.num,
711                   avctx->height * avctx->sample_aspect_ratio.den,
712                   INT_MAX / 8);
713     } else {
714         ctx->params.darHeight = avctx->height;
715         ctx->params.darWidth  = avctx->width;
716     }
717
718     ctx->params.frameRateNum = avctx->time_base.den;
719     ctx->params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
720
721     ctx->params.enableEncodeAsync = 0;
722     ctx->params.enablePTD         = 1;
723
724     ctx->params.encodeConfig = &ctx->config;
725
726     nvec_map_preset(ctx);
727
728     preset_cfg.version           = NV_ENC_PRESET_CONFIG_VER;
729     preset_cfg.presetCfg.version = NV_ENC_CONFIG_VER;
730
731     ret = nv->nvEncGetEncodePresetConfig(ctx->nvenc_ctx,
732                                          ctx->params.encodeGUID,
733                                          ctx->params.presetGUID,
734                                          &preset_cfg);
735     if (ret != NV_ENC_SUCCESS)
736         return nvenc_print_error(avctx, ret, "Cannot get the preset configuration");
737
738     memcpy(&ctx->config, &preset_cfg.presetCfg, sizeof(ctx->config));
739
740     ctx->config.version = NV_ENC_CONFIG_VER;
741
742     if (avctx->gop_size > 0) {
743         if (avctx->max_b_frames > 0) {
744             /* 0 is intra-only,
745              * 1 is I/P only,
746              * 2 is one B-Frame,
747              * 3 two B-frames, and so on. */
748             ctx->config.frameIntervalP = avctx->max_b_frames + 1;
749         } else if (avctx->max_b_frames == 0) {
750             ctx->config.frameIntervalP = 1;
751         }
752         ctx->config.gopLength = avctx->gop_size;
753     } else if (avctx->gop_size == 0) {
754         ctx->config.frameIntervalP = 0;
755         ctx->config.gopLength      = 1;
756     }
757
758     if (ctx->config.frameIntervalP > 1)
759         avctx->max_b_frames = ctx->config.frameIntervalP - 1;
760
761     ctx->initial_pts[0] = AV_NOPTS_VALUE;
762     ctx->initial_pts[1] = AV_NOPTS_VALUE;
763
764     nvenc_setup_rate_control(avctx);
765
766     if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
767         ctx->config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
768     } else {
769         ctx->config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
770     }
771
772     if ((ret = nvenc_setup_codec_config(avctx)) < 0)
773         return ret;
774
775     ret = nv->nvEncInitializeEncoder(ctx->nvenc_ctx, &ctx->params);
776     if (ret != NV_ENC_SUCCESS)
777         return nvenc_print_error(avctx, ret, "Cannot initialize the decoder");
778
779     cpb_props = ff_add_cpb_side_data(avctx);
780     if (!cpb_props)
781         return AVERROR(ENOMEM);
782     cpb_props->max_bitrate = avctx->rc_max_rate;
783     cpb_props->min_bitrate = avctx->rc_min_rate;
784     cpb_props->avg_bitrate = avctx->bit_rate;
785     cpb_props->buffer_size = avctx->rc_buffer_size;
786
787     return 0;
788 }
789
790 static int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
791 {
792     NVENCContext *ctx               = avctx->priv_data;
793     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
794     int ret;
795     NV_ENC_CREATE_BITSTREAM_BUFFER out_buffer = { 0 };
796
797     switch (ctx->data_pix_fmt) {
798     case AV_PIX_FMT_YUV420P:
799         ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YV12_PL;
800         break;
801     case AV_PIX_FMT_NV12:
802         ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_NV12_PL;
803         break;
804     case AV_PIX_FMT_YUV444P:
805         ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YUV444_PL;
806         break;
807     default:
808         return AVERROR_BUG;
809     }
810
811     if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
812         ctx->frames[idx].in_ref = av_frame_alloc();
813         if (!ctx->frames[idx].in_ref)
814             return AVERROR(ENOMEM);
815     } else {
816         NV_ENC_CREATE_INPUT_BUFFER in_buffer      = { 0 };
817
818         in_buffer.version  = NV_ENC_CREATE_INPUT_BUFFER_VER;
819
820         in_buffer.width  = avctx->width;
821         in_buffer.height = avctx->height;
822
823         in_buffer.bufferFmt  = ctx->frames[idx].format;
824         in_buffer.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED;
825
826         ret = nv->nvEncCreateInputBuffer(ctx->nvenc_ctx, &in_buffer);
827         if (ret != NV_ENC_SUCCESS)
828             return nvenc_print_error(avctx, ret, "CreateInputBuffer failed");
829
830         ctx->frames[idx].in     = in_buffer.inputBuffer;
831     }
832
833     out_buffer.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
834     /* 1MB is large enough to hold most output frames.
835      * NVENC increases this automatically if it is not enough. */
836     out_buffer.size = BITSTREAM_BUFFER_SIZE;
837
838     out_buffer.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED;
839
840     ret = nv->nvEncCreateBitstreamBuffer(ctx->nvenc_ctx, &out_buffer);
841     if (ret != NV_ENC_SUCCESS)
842         return nvenc_print_error(avctx, ret, "CreateBitstreamBuffer failed");
843
844     ctx->frames[idx].out  = out_buffer.bitstreamBuffer;
845
846     return 0;
847 }
848
849 static int nvenc_setup_surfaces(AVCodecContext *avctx)
850 {
851     NVENCContext *ctx = avctx->priv_data;
852     int i, ret;
853
854     ctx->nb_surfaces = FFMAX(4 + avctx->max_b_frames,
855                              ctx->nb_surfaces);
856     ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
857
858
859     ctx->frames = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->frames));
860     if (!ctx->frames)
861         return AVERROR(ENOMEM);
862
863     ctx->timestamps = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
864     if (!ctx->timestamps)
865         return AVERROR(ENOMEM);
866     ctx->pending = av_fifo_alloc(ctx->nb_surfaces * sizeof(*ctx->frames));
867     if (!ctx->pending)
868         return AVERROR(ENOMEM);
869     ctx->ready = av_fifo_alloc(ctx->nb_surfaces * sizeof(*ctx->frames));
870     if (!ctx->ready)
871         return AVERROR(ENOMEM);
872
873     for (i = 0; i < ctx->nb_surfaces; i++) {
874         if ((ret = nvenc_alloc_surface(avctx, i)) < 0)
875             return ret;
876     }
877
878     return 0;
879 }
880
881 #define EXTRADATA_SIZE 512
882
883 static int nvenc_setup_extradata(AVCodecContext *avctx)
884 {
885     NVENCContext *ctx                     = avctx->priv_data;
886     NV_ENCODE_API_FUNCTION_LIST *nv       = &ctx->nvel.nvenc_funcs;
887     NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
888     int ret;
889
890     avctx->extradata = av_mallocz(EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
891     if (!avctx->extradata)
892         return AVERROR(ENOMEM);
893
894     payload.version              = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
895     payload.spsppsBuffer         = avctx->extradata;
896     payload.inBufferSize         = EXTRADATA_SIZE;
897     payload.outSPSPPSPayloadSize = &avctx->extradata_size;
898
899     ret = nv->nvEncGetSequenceParams(ctx->nvenc_ctx, &payload);
900     if (ret != NV_ENC_SUCCESS)
901         return nvenc_print_error(avctx, ret, "Cannot get the extradata");
902
903     return 0;
904 }
905
906 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
907 {
908     NVENCContext *ctx               = avctx->priv_data;
909     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
910     int i;
911
912     /* the encoder has to be flushed before it can be closed */
913     if (ctx->nvenc_ctx) {
914         NV_ENC_PIC_PARAMS params        = { .version        = NV_ENC_PIC_PARAMS_VER,
915                                             .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
916
917         nv->nvEncEncodePicture(ctx->nvenc_ctx, &params);
918     }
919
920     av_fifo_free(ctx->timestamps);
921     av_fifo_free(ctx->pending);
922     av_fifo_free(ctx->ready);
923
924     if (ctx->frames) {
925         for (i = 0; i < ctx->nb_surfaces; ++i) {
926             if (avctx->pix_fmt != AV_PIX_FMT_CUDA) {
927                 nv->nvEncDestroyInputBuffer(ctx->nvenc_ctx, ctx->frames[i].in);
928             } else if (ctx->frames[i].in) {
929                 nv->nvEncUnmapInputResource(ctx->nvenc_ctx, ctx->frames[i].in_map.mappedResource);
930             }
931
932             av_frame_free(&ctx->frames[i].in_ref);
933             nv->nvEncDestroyBitstreamBuffer(ctx->nvenc_ctx, ctx->frames[i].out);
934         }
935     }
936     for (i = 0; i < ctx->nb_registered_frames; i++) {
937         if (ctx->registered_frames[i].regptr)
938             nv->nvEncUnregisterResource(ctx->nvenc_ctx, ctx->registered_frames[i].regptr);
939     }
940     ctx->nb_registered_frames = 0;
941
942     av_freep(&ctx->frames);
943
944     if (ctx->nvenc_ctx)
945         nv->nvEncDestroyEncoder(ctx->nvenc_ctx);
946
947     if (ctx->cu_context_internal)
948         ctx->nvel.cu_ctx_destroy(ctx->cu_context_internal);
949
950     if (ctx->nvel.nvenc)
951         dlclose(ctx->nvel.nvenc);
952
953 #if !CONFIG_CUDA
954     if (ctx->nvel.cuda)
955         dlclose(ctx->nvel.cuda);
956 #endif
957
958     return 0;
959 }
960
961 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
962 {
963     NVENCContext *ctx = avctx->priv_data;
964     int ret;
965
966     if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
967         AVHWFramesContext *frames_ctx;
968         if (!avctx->hw_frames_ctx) {
969             av_log(avctx, AV_LOG_ERROR,
970                    "hw_frames_ctx must be set when using GPU frames as input\n");
971             return AVERROR(EINVAL);
972         }
973         frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
974         ctx->data_pix_fmt = frames_ctx->sw_format;
975     } else {
976         ctx->data_pix_fmt = avctx->pix_fmt;
977     }
978
979     if ((ret = nvenc_load_libraries(avctx)) < 0)
980         return ret;
981
982     if ((ret = nvenc_setup_device(avctx)) < 0)
983         return ret;
984
985     if ((ret = nvenc_setup_encoder(avctx)) < 0)
986         return ret;
987
988     if ((ret = nvenc_setup_surfaces(avctx)) < 0)
989         return ret;
990
991     if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
992         if ((ret = nvenc_setup_extradata(avctx)) < 0)
993             return ret;
994     }
995
996     return 0;
997 }
998
999 static NVENCFrame *get_free_frame(NVENCContext *ctx)
1000 {
1001     int i;
1002
1003     for (i = 0; i < ctx->nb_surfaces; i++) {
1004         if (!ctx->frames[i].locked) {
1005             ctx->frames[i].locked = 1;
1006             return &ctx->frames[i];
1007         }
1008     }
1009
1010     return NULL;
1011 }
1012
1013 static int nvenc_copy_frame(NV_ENC_LOCK_INPUT_BUFFER *in, const AVFrame *frame)
1014 {
1015     uint8_t *buf = in->bufferDataPtr;
1016     int off      = frame->height * in->pitch;
1017
1018     switch (frame->format) {
1019     case AV_PIX_FMT_YUV420P:
1020         av_image_copy_plane(buf, in->pitch,
1021                             frame->data[0], frame->linesize[0],
1022                             frame->width, frame->height);
1023         buf += off;
1024
1025         av_image_copy_plane(buf, in->pitch >> 1,
1026                             frame->data[2], frame->linesize[2],
1027                             frame->width >> 1, frame->height >> 1);
1028
1029         buf += off >> 2;
1030
1031         av_image_copy_plane(buf, in->pitch >> 1,
1032                             frame->data[1], frame->linesize[1],
1033                             frame->width >> 1, frame->height >> 1);
1034         break;
1035     case AV_PIX_FMT_NV12:
1036         av_image_copy_plane(buf, in->pitch,
1037                             frame->data[0], frame->linesize[0],
1038                             frame->width, frame->height);
1039         buf += off;
1040
1041         av_image_copy_plane(buf, in->pitch,
1042                             frame->data[1], frame->linesize[1],
1043                             frame->width, frame->height >> 1);
1044         break;
1045     case AV_PIX_FMT_YUV444P:
1046         av_image_copy_plane(buf, in->pitch,
1047                             frame->data[0], frame->linesize[0],
1048                             frame->width, frame->height);
1049         buf += off;
1050
1051         av_image_copy_plane(buf, in->pitch,
1052                             frame->data[1], frame->linesize[1],
1053                             frame->width, frame->height);
1054         buf += off;
1055
1056         av_image_copy_plane(buf, in->pitch,
1057                             frame->data[2], frame->linesize[2],
1058                             frame->width, frame->height);
1059         break;
1060     default:
1061         return AVERROR_BUG;
1062     }
1063
1064     return 0;
1065 }
1066
1067 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1068 {
1069     NVENCContext               *ctx = avctx->priv_data;
1070     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1071     int i;
1072
1073     if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1074         for (i = 0; i < ctx->nb_registered_frames; i++) {
1075             if (!ctx->registered_frames[i].mapped) {
1076                 if (ctx->registered_frames[i].regptr) {
1077                     nv->nvEncUnregisterResource(ctx->nvenc_ctx,
1078                                                 ctx->registered_frames[i].regptr);
1079                     ctx->registered_frames[i].regptr = NULL;
1080                 }
1081                 return i;
1082             }
1083         }
1084     } else {
1085         return ctx->nb_registered_frames++;
1086     }
1087
1088     av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1089     return AVERROR(ENOMEM);
1090 }
1091
1092 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1093 {
1094     NVENCContext               *ctx = avctx->priv_data;
1095     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1096     AVHWFramesContext   *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1097     NV_ENC_REGISTER_RESOURCE reg;
1098     int i, idx, ret;
1099
1100     for (i = 0; i < ctx->nb_registered_frames; i++) {
1101         if (ctx->registered_frames[i].ptr == (CUdeviceptr)frame->data[0])
1102             return i;
1103     }
1104
1105     idx = nvenc_find_free_reg_resource(avctx);
1106     if (idx < 0)
1107         return idx;
1108
1109     reg.version            = NV_ENC_REGISTER_RESOURCE_VER;
1110     reg.resourceType       = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1111     reg.width              = frames_ctx->width;
1112     reg.height             = frames_ctx->height;
1113     reg.bufferFormat       = ctx->frames[0].format;
1114     reg.pitch              = frame->linesize[0];
1115     reg.resourceToRegister = frame->data[0];
1116
1117     ret = nv->nvEncRegisterResource(ctx->nvenc_ctx, &reg);
1118     if (ret != NV_ENC_SUCCESS) {
1119         nvenc_print_error(avctx, ret, "Error registering an input resource");
1120         return AVERROR_UNKNOWN;
1121     }
1122
1123     ctx->registered_frames[idx].ptr    = (CUdeviceptr)frame->data[0];
1124     ctx->registered_frames[idx].regptr = reg.registeredResource;
1125     return idx;
1126 }
1127
1128 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1129                               NVENCFrame *nvenc_frame)
1130 {
1131     NVENCContext *ctx               = avctx->priv_data;
1132     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1133     int ret;
1134
1135     if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1136         int reg_idx;
1137
1138         ret = nvenc_register_frame(avctx, frame);
1139         if (ret < 0) {
1140             av_log(avctx, AV_LOG_ERROR, "Could not register an input CUDA frame\n");
1141             return ret;
1142         }
1143         reg_idx = ret;
1144
1145         ret = av_frame_ref(nvenc_frame->in_ref, frame);
1146         if (ret < 0)
1147             return ret;
1148
1149         nvenc_frame->in_map.version            = NV_ENC_MAP_INPUT_RESOURCE_VER;
1150         nvenc_frame->in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1151
1152         ret = nv->nvEncMapInputResource(ctx->nvenc_ctx, &nvenc_frame->in_map);
1153         if (ret != NV_ENC_SUCCESS) {
1154             av_frame_unref(nvenc_frame->in_ref);
1155             return nvenc_print_error(avctx, ret, "Error mapping an input resource");
1156         }
1157
1158         ctx->registered_frames[reg_idx].mapped = 1;
1159         nvenc_frame->reg_idx                   = reg_idx;
1160         nvenc_frame->in                        = nvenc_frame->in_map.mappedResource;
1161     } else {
1162         NV_ENC_LOCK_INPUT_BUFFER params = { 0 };
1163
1164         params.version     = NV_ENC_LOCK_INPUT_BUFFER_VER;
1165         params.inputBuffer = nvenc_frame->in;
1166
1167         ret = nv->nvEncLockInputBuffer(ctx->nvenc_ctx, &params);
1168         if (ret != NV_ENC_SUCCESS)
1169             return nvenc_print_error(avctx, ret, "Cannot lock the buffer");
1170
1171         ret = nvenc_copy_frame(&params, frame);
1172         if (ret < 0) {
1173             nv->nvEncUnlockInputBuffer(ctx->nvenc_ctx, nvenc_frame->in);
1174             return ret;
1175         }
1176
1177         ret = nv->nvEncUnlockInputBuffer(ctx->nvenc_ctx, nvenc_frame->in);
1178         if (ret != NV_ENC_SUCCESS)
1179             return nvenc_print_error(avctx, ret, "Cannot unlock the buffer");
1180     }
1181
1182     return 0;
1183 }
1184
1185 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1186                                             NV_ENC_PIC_PARAMS *params)
1187 {
1188     NVENCContext *ctx = avctx->priv_data;
1189
1190     switch (avctx->codec->id) {
1191     case AV_CODEC_ID_H264:
1192         params->codecPicParams.h264PicParams.sliceMode =
1193             ctx->config.encodeCodecConfig.h264Config.sliceMode;
1194         params->codecPicParams.h264PicParams.sliceModeData =
1195             ctx->config.encodeCodecConfig.h264Config.sliceModeData;
1196         break;
1197     case AV_CODEC_ID_HEVC:
1198         params->codecPicParams.hevcPicParams.sliceMode =
1199             ctx->config.encodeCodecConfig.hevcConfig.sliceMode;
1200         params->codecPicParams.hevcPicParams.sliceModeData =
1201             ctx->config.encodeCodecConfig.hevcConfig.sliceModeData;
1202         break;
1203     }
1204 }
1205
1206 static inline int nvenc_enqueue_timestamp(AVFifoBuffer *f, int64_t pts)
1207 {
1208     return av_fifo_generic_write(f, &pts, sizeof(pts), NULL);
1209 }
1210
1211 static inline int nvenc_dequeue_timestamp(AVFifoBuffer *f, int64_t *pts)
1212 {
1213     return av_fifo_generic_read(f, pts, sizeof(*pts), NULL);
1214 }
1215
1216 static int nvenc_set_timestamp(AVCodecContext *avctx,
1217                                NV_ENC_LOCK_BITSTREAM *params,
1218                                AVPacket *pkt)
1219 {
1220     NVENCContext *ctx = avctx->priv_data;
1221
1222     pkt->pts      = params->outputTimeStamp;
1223     pkt->duration = params->outputDuration;
1224
1225     /* generate the first dts by linearly extrapolating the
1226      * first two pts values to the past */
1227     if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
1228         ctx->initial_pts[1] != AV_NOPTS_VALUE) {
1229         int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
1230         int64_t delta;
1231
1232         if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
1233             (ts0 > 0 && ts1 < INT64_MIN + ts0))
1234             return AVERROR(ERANGE);
1235         delta = ts1 - ts0;
1236
1237         if ((delta < 0 && ts0 > INT64_MAX + delta) ||
1238             (delta > 0 && ts0 < INT64_MIN + delta))
1239             return AVERROR(ERANGE);
1240         pkt->dts = ts0 - delta;
1241
1242         ctx->first_packet_output = 1;
1243         return 0;
1244     }
1245     return nvenc_dequeue_timestamp(ctx->timestamps, &pkt->dts);
1246 }
1247
1248 static int nvenc_get_output(AVCodecContext *avctx, AVPacket *pkt)
1249 {
1250     NVENCContext *ctx               = avctx->priv_data;
1251     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1252     NV_ENC_LOCK_BITSTREAM params    = { 0 };
1253     NVENCFrame *frame;
1254     int ret;
1255
1256     ret = av_fifo_generic_read(ctx->ready, &frame, sizeof(frame), NULL);
1257     if (ret)
1258         return ret;
1259
1260     params.version         = NV_ENC_LOCK_BITSTREAM_VER;
1261     params.outputBitstream = frame->out;
1262
1263     ret = nv->nvEncLockBitstream(ctx->nvenc_ctx, &params);
1264     if (ret < 0)
1265         return nvenc_print_error(avctx, ret, "Cannot lock the bitstream");
1266
1267     ret = ff_alloc_packet(pkt, params.bitstreamSizeInBytes);
1268     if (ret < 0)
1269         return ret;
1270
1271     memcpy(pkt->data, params.bitstreamBufferPtr, pkt->size);
1272
1273     ret = nv->nvEncUnlockBitstream(ctx->nvenc_ctx, frame->out);
1274     if (ret < 0)
1275         return nvenc_print_error(avctx, ret, "Cannot unlock the bitstream");
1276
1277     if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1278         nv->nvEncUnmapInputResource(ctx->nvenc_ctx, frame->in_map.mappedResource);
1279         av_frame_unref(frame->in_ref);
1280         ctx->registered_frames[frame->reg_idx].mapped = 0;
1281
1282         frame->in = NULL;
1283     }
1284
1285     frame->locked = 0;
1286
1287     ret = nvenc_set_timestamp(avctx, &params, pkt);
1288     if (ret < 0)
1289         return ret;
1290
1291     switch (params.pictureType) {
1292     case NV_ENC_PIC_TYPE_IDR:
1293         pkt->flags |= AV_PKT_FLAG_KEY;
1294 #if FF_API_CODED_FRAME
1295 FF_DISABLE_DEPRECATION_WARNINGS
1296     case NV_ENC_PIC_TYPE_INTRA_REFRESH:
1297     case NV_ENC_PIC_TYPE_I:
1298         avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
1299         break;
1300     case NV_ENC_PIC_TYPE_P:
1301         avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
1302         break;
1303     case NV_ENC_PIC_TYPE_B:
1304         avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;
1305         break;
1306     case NV_ENC_PIC_TYPE_BI:
1307         avctx->coded_frame->pict_type = AV_PICTURE_TYPE_BI;
1308         break;
1309 FF_ENABLE_DEPRECATION_WARNINGS
1310 #endif
1311     }
1312
1313     return 0;
1314 }
1315
1316 static int output_ready(AVCodecContext *avctx, int flush)
1317 {
1318     NVENCContext *ctx = avctx->priv_data;
1319     int nb_ready, nb_pending;
1320
1321     /* when B-frames are enabled, we wait for two initial timestamps to
1322      * calculate the first dts */
1323     if (!flush && avctx->max_b_frames > 0 &&
1324         (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
1325         return 0;
1326
1327     nb_ready   = av_fifo_size(ctx->ready)   / sizeof(NVENCFrame*);
1328     nb_pending = av_fifo_size(ctx->pending) / sizeof(NVENCFrame*);
1329     if (flush)
1330         return nb_ready > 0;
1331     return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
1332 }
1333
1334 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1335                           const AVFrame *frame, int *got_packet)
1336 {
1337     NVENCContext *ctx               = avctx->priv_data;
1338     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1339     NV_ENC_PIC_PARAMS params        = { 0 };
1340     NVENCFrame         *nvenc_frame = NULL;
1341     int enc_ret, ret;
1342
1343     params.version = NV_ENC_PIC_PARAMS_VER;
1344
1345     if (frame) {
1346         nvenc_frame = get_free_frame(ctx);
1347         if (!nvenc_frame) {
1348             av_log(avctx, AV_LOG_ERROR, "No free surfaces\n");
1349             return AVERROR_BUG;
1350         }
1351
1352         ret = nvenc_upload_frame(avctx, frame, nvenc_frame);
1353         if (ret < 0)
1354             return ret;
1355
1356         params.inputBuffer     = nvenc_frame->in;
1357         params.bufferFmt       = nvenc_frame->format;
1358         params.inputWidth      = frame->width;
1359         params.inputHeight     = frame->height;
1360         params.outputBitstream = nvenc_frame->out;
1361         params.inputTimeStamp  = frame->pts;
1362
1363         if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1364             if (frame->top_field_first)
1365                 params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
1366             else
1367                 params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
1368         } else {
1369             params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1370         }
1371
1372         nvenc_codec_specific_pic_params(avctx, &params);
1373
1374         ret = nvenc_enqueue_timestamp(ctx->timestamps, frame->pts);
1375         if (ret < 0)
1376             return ret;
1377
1378         if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
1379             ctx->initial_pts[0] = frame->pts;
1380         else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
1381             ctx->initial_pts[1] = frame->pts;
1382     } else {
1383         params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1384     }
1385
1386     enc_ret = nv->nvEncEncodePicture(ctx->nvenc_ctx, &params);
1387     if (enc_ret != NV_ENC_SUCCESS &&
1388         enc_ret != NV_ENC_ERR_NEED_MORE_INPUT)
1389         return nvenc_print_error(avctx, enc_ret, "Error encoding the frame");
1390
1391     if (nvenc_frame) {
1392         ret = av_fifo_generic_write(ctx->pending, &nvenc_frame, sizeof(nvenc_frame), NULL);
1393         if (ret < 0)
1394             return ret;
1395     }
1396
1397     /* all the pending buffers are now ready for output */
1398     if (enc_ret == NV_ENC_SUCCESS) {
1399         while (av_fifo_size(ctx->pending) > 0) {
1400             av_fifo_generic_read(ctx->pending, &nvenc_frame, sizeof(nvenc_frame), NULL);
1401             av_fifo_generic_write(ctx->ready,  &nvenc_frame, sizeof(nvenc_frame), NULL);
1402         }
1403     }
1404
1405     if (output_ready(avctx, !frame)) {
1406         ret = nvenc_get_output(avctx, pkt);
1407         if (ret < 0)
1408             return ret;
1409         *got_packet = 1;
1410     } else {
1411         *got_packet = 0;
1412     }
1413
1414     return 0;
1415 }