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