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