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