]> git.sesse.net Git - ffmpeg/blob - libavcodec/nvenc.c
avcodec/nvenc: add test for Temporal AQ support
[ffmpeg] / libavcodec / nvenc.c
1 /*
2  * H.264/HEVC hardware encoding using nvidia nvenc
3  * Copyright (c) 2016 Timo Rothenpieler <timo@rothenpieler.org>
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "config.h"
23
24 #if defined(_WIN32) || defined(__CYGWIN__)
25 # define CUDA_LIBNAME "nvcuda.dll"
26 # if ARCH_X86_64
27 #  define NVENC_LIBNAME "nvEncodeAPI64.dll"
28 # else
29 #  define NVENC_LIBNAME "nvEncodeAPI.dll"
30 # endif
31 #else
32 # define CUDA_LIBNAME "libcuda.so.1"
33 # define NVENC_LIBNAME "libnvidia-encode.so.1"
34 #endif
35
36 #if defined(_WIN32)
37 #include <windows.h>
38
39 #define dlopen(filename, flags) LoadLibrary(TEXT(filename))
40 #define dlsym(handle, symbol)   GetProcAddress(handle, symbol)
41 #define dlclose(handle)         FreeLibrary(handle)
42 #else
43 #include <dlfcn.h>
44 #endif
45
46 #include "libavutil/hwcontext.h"
47 #include "libavutil/imgutils.h"
48 #include "libavutil/avassert.h"
49 #include "libavutil/mem.h"
50 #include "internal.h"
51 #include "nvenc.h"
52
53 #define NVENC_CAP 0x30
54 #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR ||               \
55                     rc == NV_ENC_PARAMS_RC_2_PASS_QUALITY ||    \
56                     rc == NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP)
57
58 #define LOAD_LIBRARY(l, path)                   \
59     do {                                        \
60         if (!((l) = dlopen(path, RTLD_LAZY))) { \
61             av_log(avctx, AV_LOG_ERROR,         \
62                    "Cannot load %s\n",          \
63                    path);                       \
64             return AVERROR_UNKNOWN;             \
65         }                                       \
66     } while (0)
67
68 #define LOAD_SYMBOL(fun, lib, symbol)        \
69     do {                                     \
70         if (!((fun) = dlsym(lib, symbol))) { \
71             av_log(avctx, AV_LOG_ERROR,      \
72                    "Cannot load %s\n",       \
73                    symbol);                  \
74             return AVERROR_UNKNOWN;          \
75         }                                    \
76     } while (0)
77
78 const enum AVPixelFormat ff_nvenc_pix_fmts[] = {
79     AV_PIX_FMT_YUV420P,
80     AV_PIX_FMT_NV12,
81     AV_PIX_FMT_P010,
82     AV_PIX_FMT_YUV444P,
83     AV_PIX_FMT_YUV444P16,
84     AV_PIX_FMT_0RGB32,
85     AV_PIX_FMT_0BGR32,
86 #if CONFIG_CUDA
87     AV_PIX_FMT_CUDA,
88 #endif
89     AV_PIX_FMT_NONE
90 };
91
92 #define IS_10BIT(pix_fmt) (pix_fmt == AV_PIX_FMT_P010 ||    \
93                            pix_fmt == AV_PIX_FMT_YUV444P16)
94
95 #define IS_YUV444(pix_fmt) (pix_fmt == AV_PIX_FMT_YUV444P || \
96                             pix_fmt == AV_PIX_FMT_YUV444P16)
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_BUFFER_TOO_SMALL, "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     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
160     PNVENCODEAPIGETMAXSUPPORTEDVERSION nvenc_get_max_ver;
161     PNVENCODEAPICREATEINSTANCE nvenc_create_instance;
162     NVENCSTATUS err;
163     uint32_t nvenc_max_ver;
164
165 #if CONFIG_CUDA
166     dl_fn->cu_init                      = cuInit;
167     dl_fn->cu_device_get_count          = cuDeviceGetCount;
168     dl_fn->cu_device_get                = cuDeviceGet;
169     dl_fn->cu_device_get_name           = cuDeviceGetName;
170     dl_fn->cu_device_compute_capability = cuDeviceComputeCapability;
171     dl_fn->cu_ctx_create                = cuCtxCreate_v2;
172     dl_fn->cu_ctx_pop_current           = cuCtxPopCurrent_v2;
173     dl_fn->cu_ctx_destroy               = cuCtxDestroy_v2;
174 #else
175     LOAD_LIBRARY(dl_fn->cuda, CUDA_LIBNAME);
176
177     LOAD_SYMBOL(dl_fn->cu_init, dl_fn->cuda, "cuInit");
178     LOAD_SYMBOL(dl_fn->cu_device_get_count, dl_fn->cuda, "cuDeviceGetCount");
179     LOAD_SYMBOL(dl_fn->cu_device_get, dl_fn->cuda, "cuDeviceGet");
180     LOAD_SYMBOL(dl_fn->cu_device_get_name, dl_fn->cuda, "cuDeviceGetName");
181     LOAD_SYMBOL(dl_fn->cu_device_compute_capability, dl_fn->cuda,
182                 "cuDeviceComputeCapability");
183     LOAD_SYMBOL(dl_fn->cu_ctx_create, dl_fn->cuda, "cuCtxCreate_v2");
184     LOAD_SYMBOL(dl_fn->cu_ctx_pop_current, dl_fn->cuda, "cuCtxPopCurrent_v2");
185     LOAD_SYMBOL(dl_fn->cu_ctx_destroy, dl_fn->cuda, "cuCtxDestroy_v2");
186 #endif
187
188     LOAD_LIBRARY(dl_fn->nvenc, NVENC_LIBNAME);
189
190     LOAD_SYMBOL(nvenc_get_max_ver, dl_fn->nvenc,
191                 "NvEncodeAPIGetMaxSupportedVersion");
192     LOAD_SYMBOL(nvenc_create_instance, dl_fn->nvenc,
193                 "NvEncodeAPICreateInstance");
194
195     err = nvenc_get_max_ver(&nvenc_max_ver);
196     if (err != NV_ENC_SUCCESS)
197         return nvenc_print_error(avctx, err, "Failed to query nvenc max version");
198
199     av_log(avctx, AV_LOG_VERBOSE, "Loaded Nvenc version %d.%d\n", nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
200
201     if ((NVENCAPI_MAJOR_VERSION << 4 | NVENCAPI_MINOR_VERSION) > nvenc_max_ver) {
202         av_log(avctx, AV_LOG_ERROR, "Driver does not support the required nvenc API version. "
203                "Required: %d.%d Found: %d.%d\n",
204                NVENCAPI_MAJOR_VERSION, NVENCAPI_MINOR_VERSION,
205                nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
206         return AVERROR(ENOSYS);
207     }
208
209     dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
210
211     err = nvenc_create_instance(&dl_fn->nvenc_funcs);
212     if (err != NV_ENC_SUCCESS)
213         return nvenc_print_error(avctx, err, "Failed to create nvenc instance");
214
215     av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
216
217     return 0;
218 }
219
220 static av_cold int nvenc_open_session(AVCodecContext *avctx)
221 {
222     NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
223     NvencContext *ctx = avctx->priv_data;
224     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
225     NVENCSTATUS ret;
226
227     params.version    = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
228     params.apiVersion = NVENCAPI_VERSION;
229     params.device     = ctx->cu_context;
230     params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
231
232     ret = p_nvenc->nvEncOpenEncodeSessionEx(&params, &ctx->nvencoder);
233     if (ret != NV_ENC_SUCCESS) {
234         ctx->nvencoder = NULL;
235         return nvenc_print_error(avctx, ret, "OpenEncodeSessionEx failed");
236     }
237
238     return 0;
239 }
240
241 static int nvenc_check_codec_support(AVCodecContext *avctx)
242 {
243     NvencContext *ctx = avctx->priv_data;
244     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
245     int i, ret, count = 0;
246     GUID *guids = NULL;
247
248     ret = p_nvenc->nvEncGetEncodeGUIDCount(ctx->nvencoder, &count);
249
250     if (ret != NV_ENC_SUCCESS || !count)
251         return AVERROR(ENOSYS);
252
253     guids = av_malloc(count * sizeof(GUID));
254     if (!guids)
255         return AVERROR(ENOMEM);
256
257     ret = p_nvenc->nvEncGetEncodeGUIDs(ctx->nvencoder, guids, count, &count);
258     if (ret != NV_ENC_SUCCESS) {
259         ret = AVERROR(ENOSYS);
260         goto fail;
261     }
262
263     ret = AVERROR(ENOSYS);
264     for (i = 0; i < count; i++) {
265         if (!memcmp(&guids[i], &ctx->init_encode_params.encodeGUID, sizeof(*guids))) {
266             ret = 0;
267             break;
268         }
269     }
270
271 fail:
272     av_free(guids);
273
274     return ret;
275 }
276
277 static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
278 {
279     NvencContext *ctx = avctx->priv_data;
280     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
281     NV_ENC_CAPS_PARAM params        = { 0 };
282     int ret, val = 0;
283
284     params.version     = NV_ENC_CAPS_PARAM_VER;
285     params.capsToQuery = cap;
286
287     ret = p_nvenc->nvEncGetEncodeCaps(ctx->nvencoder, ctx->init_encode_params.encodeGUID, &params, &val);
288
289     if (ret == NV_ENC_SUCCESS)
290         return val;
291     return 0;
292 }
293
294 static int nvenc_check_capabilities(AVCodecContext *avctx)
295 {
296     NvencContext *ctx = avctx->priv_data;
297     int ret;
298
299     ret = nvenc_check_codec_support(avctx);
300     if (ret < 0) {
301         av_log(avctx, AV_LOG_VERBOSE, "Codec not supported\n");
302         return ret;
303     }
304
305     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
306     if (IS_YUV444(ctx->data_pix_fmt) && ret <= 0) {
307         av_log(avctx, AV_LOG_VERBOSE, "YUV444P not supported\n");
308         return AVERROR(ENOSYS);
309     }
310
311     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOSSLESS_ENCODE);
312     if (ctx->preset >= PRESET_LOSSLESS_DEFAULT && ret <= 0) {
313         av_log(avctx, AV_LOG_VERBOSE, "Lossless encoding not supported\n");
314         return AVERROR(ENOSYS);
315     }
316
317     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
318     if (ret < avctx->width) {
319         av_log(avctx, AV_LOG_VERBOSE, "Width %d exceeds %d\n",
320                avctx->width, ret);
321         return AVERROR(ENOSYS);
322     }
323
324     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
325     if (ret < avctx->height) {
326         av_log(avctx, AV_LOG_VERBOSE, "Height %d exceeds %d\n",
327                avctx->height, ret);
328         return AVERROR(ENOSYS);
329     }
330
331     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
332     if (ret < avctx->max_b_frames) {
333         av_log(avctx, AV_LOG_VERBOSE, "Max B-frames %d exceed %d\n",
334                avctx->max_b_frames, ret);
335
336         return AVERROR(ENOSYS);
337     }
338
339     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_FIELD_ENCODING);
340     if (ret < 1 && avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
341         av_log(avctx, AV_LOG_VERBOSE,
342                "Interlaced encoding is not supported. Supported level: %d\n",
343                ret);
344         return AVERROR(ENOSYS);
345     }
346
347     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_10BIT_ENCODE);
348     if (IS_10BIT(ctx->data_pix_fmt) && ret <= 0) {
349         av_log(avctx, AV_LOG_VERBOSE, "10 bit encode not supported\n");
350         return AVERROR(ENOSYS);
351     }
352
353     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOOKAHEAD);
354     if (ctx->rc_lookahead > 0 && ret <= 0) {
355         av_log(avctx, AV_LOG_VERBOSE, "RC lookahead not supported\n");
356         return AVERROR(ENOSYS);
357     }
358
359     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_TEMPORAL_AQ);
360     if (ctx->temporal_aq > 0 && ret <= 0) {
361         av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ not supported\n");
362         return AVERROR(ENOSYS);
363     }
364
365     return 0;
366 }
367
368 static av_cold int nvenc_check_device(AVCodecContext *avctx, int idx)
369 {
370     NvencContext *ctx = avctx->priv_data;
371     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
372     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
373     char name[128] = { 0};
374     int major, minor, ret;
375     CUresult cu_res;
376     CUdevice cu_device;
377     CUcontext dummy;
378     int loglevel = AV_LOG_VERBOSE;
379
380     if (ctx->device == LIST_DEVICES)
381         loglevel = AV_LOG_INFO;
382
383     cu_res = dl_fn->cu_device_get(&cu_device, idx);
384     if (cu_res != CUDA_SUCCESS) {
385         av_log(avctx, AV_LOG_ERROR,
386                "Cannot access the CUDA device %d\n",
387                idx);
388         return -1;
389     }
390
391     cu_res = dl_fn->cu_device_get_name(name, sizeof(name), cu_device);
392     if (cu_res != CUDA_SUCCESS)
393         return -1;
394
395     cu_res = dl_fn->cu_device_compute_capability(&major, &minor, cu_device);
396     if (cu_res != CUDA_SUCCESS)
397         return -1;
398
399     av_log(avctx, loglevel, "[ GPU #%d - < %s > has Compute SM %d.%d ]\n", idx, name, major, minor);
400     if (((major << 4) | minor) < NVENC_CAP) {
401         av_log(avctx, loglevel, "does not support NVENC\n");
402         goto fail;
403     }
404
405     cu_res = dl_fn->cu_ctx_create(&ctx->cu_context_internal, 0, cu_device);
406     if (cu_res != CUDA_SUCCESS) {
407         av_log(avctx, AV_LOG_FATAL, "Failed creating CUDA context for NVENC: 0x%x\n", (int)cu_res);
408         goto fail;
409     }
410
411     ctx->cu_context = ctx->cu_context_internal;
412
413     cu_res = dl_fn->cu_ctx_pop_current(&dummy);
414     if (cu_res != CUDA_SUCCESS) {
415         av_log(avctx, AV_LOG_FATAL, "Failed popping CUDA context: 0x%x\n", (int)cu_res);
416         goto fail2;
417     }
418
419     if ((ret = nvenc_open_session(avctx)) < 0)
420         goto fail2;
421
422     if ((ret = nvenc_check_capabilities(avctx)) < 0)
423         goto fail3;
424
425     av_log(avctx, loglevel, "supports NVENC\n");
426
427     dl_fn->nvenc_device_count++;
428
429     if (ctx->device == dl_fn->nvenc_device_count - 1 || ctx->device == ANY_DEVICE)
430         return 0;
431
432 fail3:
433     p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
434     ctx->nvencoder = NULL;
435
436 fail2:
437     dl_fn->cu_ctx_destroy(ctx->cu_context_internal);
438     ctx->cu_context_internal = NULL;
439
440 fail:
441     return AVERROR(ENOSYS);
442 }
443
444 static av_cold int nvenc_setup_device(AVCodecContext *avctx)
445 {
446     NvencContext *ctx = avctx->priv_data;
447     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
448
449     switch (avctx->codec->id) {
450     case AV_CODEC_ID_H264:
451         ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
452         break;
453     case AV_CODEC_ID_HEVC:
454         ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
455         break;
456     default:
457         return AVERROR_BUG;
458     }
459
460     if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
461 #if CONFIG_CUDA
462         AVHWFramesContext   *frames_ctx;
463         AVCUDADeviceContext *device_hwctx;
464         int ret;
465
466         if (!avctx->hw_frames_ctx)
467             return AVERROR(EINVAL);
468
469         frames_ctx   = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
470         device_hwctx = frames_ctx->device_ctx->hwctx;
471
472         ctx->cu_context = device_hwctx->cuda_ctx;
473
474         ret = nvenc_open_session(avctx);
475         if (ret < 0)
476             return ret;
477
478         ret = nvenc_check_capabilities(avctx);
479         if (ret < 0) {
480             av_log(avctx, AV_LOG_FATAL, "Provided device doesn't support required NVENC features\n");
481             return ret;
482         }
483 #else
484         return AVERROR_BUG;
485 #endif
486     } else {
487         int i, nb_devices = 0;
488
489         if ((dl_fn->cu_init(0)) != CUDA_SUCCESS) {
490             av_log(avctx, AV_LOG_ERROR,
491                    "Cannot init CUDA\n");
492             return AVERROR_UNKNOWN;
493         }
494
495         if ((dl_fn->cu_device_get_count(&nb_devices)) != CUDA_SUCCESS) {
496             av_log(avctx, AV_LOG_ERROR,
497                    "Cannot enumerate the CUDA devices\n");
498             return AVERROR_UNKNOWN;
499         }
500
501         if (!nb_devices) {
502             av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
503                 return AVERROR_EXTERNAL;
504         }
505
506         av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", nb_devices);
507
508         dl_fn->nvenc_device_count = 0;
509         for (i = 0; i < nb_devices; ++i) {
510             if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
511                 return 0;
512         }
513
514         if (ctx->device == LIST_DEVICES)
515             return AVERROR_EXIT;
516
517         if (!dl_fn->nvenc_device_count) {
518             av_log(avctx, AV_LOG_FATAL, "No NVENC capable devices found\n");
519             return AVERROR_EXTERNAL;
520         }
521
522         av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->device, dl_fn->nvenc_device_count);
523         return AVERROR(EINVAL);
524     }
525
526     return 0;
527 }
528
529 typedef struct GUIDTuple {
530     const GUID guid;
531     int flags;
532 } GUIDTuple;
533
534 #define PRESET_ALIAS(alias, name, ...) \
535     [PRESET_ ## alias] = { NV_ENC_PRESET_ ## name ## _GUID, __VA_ARGS__ }
536
537 #define PRESET(name, ...) PRESET_ALIAS(name, name, __VA_ARGS__)
538
539 static void nvenc_map_preset(NvencContext *ctx)
540 {
541     GUIDTuple presets[] = {
542         PRESET(DEFAULT),
543         PRESET(HP),
544         PRESET(HQ),
545         PRESET(BD),
546         PRESET_ALIAS(SLOW,   HQ,    NVENC_TWO_PASSES),
547         PRESET_ALIAS(MEDIUM, HQ,    NVENC_ONE_PASS),
548         PRESET_ALIAS(FAST,   HP,    NVENC_ONE_PASS),
549         PRESET(LOW_LATENCY_DEFAULT, NVENC_LOWLATENCY),
550         PRESET(LOW_LATENCY_HP,      NVENC_LOWLATENCY),
551         PRESET(LOW_LATENCY_HQ,      NVENC_LOWLATENCY),
552         PRESET(LOSSLESS_DEFAULT,    NVENC_LOSSLESS),
553         PRESET(LOSSLESS_HP,         NVENC_LOSSLESS),
554     };
555
556     GUIDTuple *t = &presets[ctx->preset];
557
558     ctx->init_encode_params.presetGUID = t->guid;
559     ctx->flags = t->flags;
560 }
561
562 #undef PRESET
563 #undef PRESET_ALIAS
564
565 static av_cold void set_constqp(AVCodecContext *avctx)
566 {
567     NvencContext *ctx = avctx->priv_data;
568     NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
569
570     rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
571     rc->constQP.qpInterB = avctx->global_quality;
572     rc->constQP.qpInterP = avctx->global_quality;
573     rc->constQP.qpIntra = avctx->global_quality;
574
575     avctx->qmin = -1;
576     avctx->qmax = -1;
577 }
578
579 static av_cold void set_vbr(AVCodecContext *avctx)
580 {
581     NvencContext *ctx = avctx->priv_data;
582     NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
583     int qp_inter_p;
584
585     if (avctx->qmin >= 0 && avctx->qmax >= 0) {
586         rc->enableMinQP = 1;
587         rc->enableMaxQP = 1;
588
589         rc->minQP.qpInterB = avctx->qmin;
590         rc->minQP.qpInterP = avctx->qmin;
591         rc->minQP.qpIntra = avctx->qmin;
592
593         rc->maxQP.qpInterB = avctx->qmax;
594         rc->maxQP.qpInterP = avctx->qmax;
595         rc->maxQP.qpIntra = avctx->qmax;
596
597         qp_inter_p = (avctx->qmax + 3 * avctx->qmin) / 4; // biased towards Qmin
598     } else if (avctx->qmin >= 0) {
599         rc->enableMinQP = 1;
600
601         rc->minQP.qpInterB = avctx->qmin;
602         rc->minQP.qpInterP = avctx->qmin;
603         rc->minQP.qpIntra = avctx->qmin;
604
605         qp_inter_p = avctx->qmin;
606     } else {
607         qp_inter_p = 26; // default to 26
608     }
609
610     rc->enableInitialRCQP = 1;
611     rc->initialRCQP.qpInterP  = qp_inter_p;
612
613     if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
614         rc->initialRCQP.qpIntra = av_clip(
615             qp_inter_p * fabs(avctx->i_quant_factor) + avctx->i_quant_offset, 0, 51);
616         rc->initialRCQP.qpInterB = av_clip(
617             qp_inter_p * fabs(avctx->b_quant_factor) + avctx->b_quant_offset, 0, 51);
618     } else {
619         rc->initialRCQP.qpIntra = qp_inter_p;
620         rc->initialRCQP.qpInterB = qp_inter_p;
621     }
622 }
623
624 static av_cold void set_lossless(AVCodecContext *avctx)
625 {
626     NvencContext *ctx = avctx->priv_data;
627     NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
628
629     rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
630     rc->constQP.qpInterB = 0;
631     rc->constQP.qpInterP = 0;
632     rc->constQP.qpIntra = 0;
633
634     avctx->qmin = -1;
635     avctx->qmax = -1;
636 }
637
638 static void nvenc_override_rate_control(AVCodecContext *avctx)
639 {
640     NvencContext *ctx    = avctx->priv_data;
641     NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
642
643     switch (ctx->rc) {
644     case NV_ENC_PARAMS_RC_CONSTQP:
645         if (avctx->global_quality <= 0) {
646             av_log(avctx, AV_LOG_WARNING,
647                    "The constant quality rate-control requires "
648                    "the 'global_quality' option set.\n");
649             return;
650         }
651         set_constqp(avctx);
652         return;
653     case NV_ENC_PARAMS_RC_2_PASS_VBR:
654     case NV_ENC_PARAMS_RC_VBR:
655         if (avctx->qmin < 0 && avctx->qmax < 0) {
656             av_log(avctx, AV_LOG_WARNING,
657                    "The variable bitrate rate-control requires "
658                    "the 'qmin' and/or 'qmax' option set.\n");
659             set_vbr(avctx);
660             return;
661         }
662     case NV_ENC_PARAMS_RC_VBR_MINQP:
663         if (avctx->qmin < 0) {
664             av_log(avctx, AV_LOG_WARNING,
665                    "The variable bitrate rate-control requires "
666                    "the 'qmin' option set.\n");
667             set_vbr(avctx);
668             return;
669         }
670         set_vbr(avctx);
671         break;
672     case NV_ENC_PARAMS_RC_CBR:
673     case NV_ENC_PARAMS_RC_2_PASS_QUALITY:
674     case NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP:
675         break;
676     }
677
678     rc->rateControlMode = ctx->rc;
679 }
680
681 static av_cold void nvenc_setup_rate_control(AVCodecContext *avctx)
682 {
683     NvencContext *ctx = avctx->priv_data;
684
685     if (avctx->bit_rate > 0) {
686         ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
687     } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
688         ctx->encode_config.rcParams.maxBitRate = ctx->encode_config.rcParams.averageBitRate;
689     }
690
691     if (avctx->rc_max_rate > 0)
692         ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
693
694     if (ctx->rc < 0) {
695         if (ctx->flags & NVENC_ONE_PASS)
696             ctx->twopass = 0;
697         if (ctx->flags & NVENC_TWO_PASSES)
698             ctx->twopass = 1;
699
700         if (ctx->twopass < 0)
701             ctx->twopass = (ctx->flags & NVENC_LOWLATENCY) != 0;
702
703         if (ctx->cbr) {
704             if (ctx->twopass) {
705                 ctx->rc = NV_ENC_PARAMS_RC_2_PASS_QUALITY;
706             } else {
707                 ctx->rc = NV_ENC_PARAMS_RC_CBR;
708             }
709         } else if (avctx->global_quality > 0) {
710             ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
711         } else if (ctx->twopass) {
712             ctx->rc = NV_ENC_PARAMS_RC_2_PASS_VBR;
713         } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
714             ctx->rc = NV_ENC_PARAMS_RC_VBR_MINQP;
715         }
716     }
717
718     if (ctx->flags & NVENC_LOSSLESS) {
719         set_lossless(avctx);
720     } else if (ctx->rc >= 0) {
721         nvenc_override_rate_control(avctx);
722     } else {
723         ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
724         set_vbr(avctx);
725     }
726
727     if (avctx->rc_buffer_size > 0) {
728         ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
729     } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
730         ctx->encode_config.rcParams.vbvBufferSize = 2 * ctx->encode_config.rcParams.averageBitRate;
731     }
732
733     if (ctx->aq) {
734         ctx->encode_config.rcParams.enableAQ   = 1;
735         ctx->encode_config.rcParams.aqStrength = ctx->aq_strength;
736         av_log(avctx, AV_LOG_VERBOSE, "AQ enabled.\n");
737     }
738
739     if (ctx->temporal_aq) {
740         ctx->encode_config.rcParams.enableTemporalAQ = 1;
741         av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ enabled.\n");
742     }
743
744     if (ctx->rc_lookahead) {
745         int lkd_bound = FFMIN(ctx->nb_surfaces, ctx->async_depth) -
746                         ctx->encode_config.frameIntervalP - 4;
747
748         if (lkd_bound < 0) {
749             av_log(avctx, AV_LOG_WARNING,
750                    "Lookahead not enabled. Increase buffer delay (-delay).\n");
751         } else {
752             ctx->encode_config.rcParams.enableLookahead = 1;
753             ctx->encode_config.rcParams.lookaheadDepth  = av_clip(ctx->rc_lookahead, 0, lkd_bound);
754             ctx->encode_config.rcParams.disableIadapt   = ctx->no_scenecut;
755             ctx->encode_config.rcParams.disableBadapt   = !ctx->b_adapt;
756             av_log(avctx, AV_LOG_VERBOSE,
757                    "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",
758                    ctx->encode_config.rcParams.lookaheadDepth,
759                    ctx->encode_config.rcParams.disableIadapt ? "disabled" : "enabled",
760                    ctx->encode_config.rcParams.disableBadapt ? "disabled" : "enabled");
761         }
762     }
763
764     if (ctx->strict_gop) {
765         ctx->encode_config.rcParams.strictGOPTarget = 1;
766         av_log(avctx, AV_LOG_VERBOSE, "Strict GOP target enabled.\n");
767     }
768
769     if (ctx->nonref_p)
770         ctx->encode_config.rcParams.enableNonRefP = 1;
771
772     if (ctx->zerolatency)
773         ctx->encode_config.rcParams.zeroReorderDelay = 1;
774
775     if (ctx->quality)
776         ctx->encode_config.rcParams.targetQuality = ctx->quality;
777 }
778
779 static av_cold int nvenc_setup_h264_config(AVCodecContext *avctx)
780 {
781     NvencContext *ctx                      = avctx->priv_data;
782     NV_ENC_CONFIG *cc                      = &ctx->encode_config;
783     NV_ENC_CONFIG_H264 *h264               = &cc->encodeCodecConfig.h264Config;
784     NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
785
786     vui->colourMatrix = avctx->colorspace;
787     vui->colourPrimaries = avctx->color_primaries;
788     vui->transferCharacteristics = avctx->color_trc;
789     vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
790         || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
791
792     vui->colourDescriptionPresentFlag =
793         (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
794
795     vui->videoSignalTypePresentFlag =
796         (vui->colourDescriptionPresentFlag
797         || vui->videoFormat != 5
798         || vui->videoFullRangeFlag != 0);
799
800     h264->sliceMode = 3;
801     h264->sliceModeData = 1;
802
803     h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
804     h264->repeatSPSPPS  = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
805     h264->outputAUD     = 1;
806
807     if (avctx->refs >= 0) {
808         /* 0 means "let the hardware decide" */
809         h264->maxNumRefFrames = avctx->refs;
810     }
811     if (avctx->gop_size >= 0) {
812         h264->idrPeriod = cc->gopLength;
813     }
814
815     if (IS_CBR(cc->rcParams.rateControlMode)) {
816         h264->outputBufferingPeriodSEI = 1;
817         h264->outputPictureTimingSEI   = 1;
818     }
819
820     if (cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_2_PASS_QUALITY ||
821         cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP ||
822         cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_2_PASS_VBR) {
823         h264->adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
824         h264->fmoMode = NV_ENC_H264_FMO_DISABLE;
825     }
826
827     if (ctx->flags & NVENC_LOSSLESS) {
828         h264->qpPrimeYZeroTransformBypassFlag = 1;
829     } else {
830         switch(ctx->profile) {
831         case NV_ENC_H264_PROFILE_BASELINE:
832             cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
833             avctx->profile = FF_PROFILE_H264_BASELINE;
834             break;
835         case NV_ENC_H264_PROFILE_MAIN:
836             cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
837             avctx->profile = FF_PROFILE_H264_MAIN;
838             break;
839         case NV_ENC_H264_PROFILE_HIGH:
840             cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
841             avctx->profile = FF_PROFILE_H264_HIGH;
842             break;
843         case NV_ENC_H264_PROFILE_HIGH_444P:
844             cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
845             avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
846             break;
847         }
848     }
849
850     // force setting profile as high444p if input is AV_PIX_FMT_YUV444P
851     if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P) {
852         cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
853         avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
854     }
855
856     h264->chromaFormatIDC = avctx->profile == FF_PROFILE_H264_HIGH_444_PREDICTIVE ? 3 : 1;
857
858     h264->level = ctx->level;
859
860     return 0;
861 }
862
863 static av_cold int nvenc_setup_hevc_config(AVCodecContext *avctx)
864 {
865     NvencContext *ctx                      = avctx->priv_data;
866     NV_ENC_CONFIG *cc                      = &ctx->encode_config;
867     NV_ENC_CONFIG_HEVC *hevc               = &cc->encodeCodecConfig.hevcConfig;
868     NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
869
870     vui->colourMatrix = avctx->colorspace;
871     vui->colourPrimaries = avctx->color_primaries;
872     vui->transferCharacteristics = avctx->color_trc;
873     vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
874         || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
875
876     vui->colourDescriptionPresentFlag =
877         (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
878
879     vui->videoSignalTypePresentFlag =
880         (vui->colourDescriptionPresentFlag
881         || vui->videoFormat != 5
882         || vui->videoFullRangeFlag != 0);
883
884     hevc->sliceMode = 3;
885     hevc->sliceModeData = 1;
886
887     hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
888     hevc->repeatSPSPPS  = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
889     hevc->outputAUD     = 1;
890
891     if (avctx->refs >= 0) {
892         /* 0 means "let the hardware decide" */
893         hevc->maxNumRefFramesInDPB = avctx->refs;
894     }
895     if (avctx->gop_size >= 0) {
896         hevc->idrPeriod = cc->gopLength;
897     }
898
899     if (IS_CBR(cc->rcParams.rateControlMode)) {
900         hevc->outputBufferingPeriodSEI = 1;
901         hevc->outputPictureTimingSEI   = 1;
902     }
903
904     switch(ctx->profile) {
905     case NV_ENC_HEVC_PROFILE_MAIN:
906         cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
907         avctx->profile = FF_PROFILE_HEVC_MAIN;
908         break;
909     case NV_ENC_HEVC_PROFILE_MAIN_10:
910         cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
911         avctx->profile = FF_PROFILE_HEVC_MAIN_10;
912         break;
913     case NV_ENC_HEVC_PROFILE_REXT:
914         cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
915         avctx->profile = FF_PROFILE_HEVC_REXT;
916         break;
917     }
918
919     // force setting profile as main10 if input is 10 bit
920     if (IS_10BIT(ctx->data_pix_fmt)) {
921         cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
922         avctx->profile = FF_PROFILE_HEVC_MAIN_10;
923     }
924
925     // force setting profile as rext if input is yuv444
926     if (IS_YUV444(ctx->data_pix_fmt)) {
927         cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
928         avctx->profile = FF_PROFILE_HEVC_REXT;
929     }
930
931     hevc->chromaFormatIDC = IS_YUV444(ctx->data_pix_fmt) ? 3 : 1;
932
933     hevc->pixelBitDepthMinus8 = IS_10BIT(ctx->data_pix_fmt) ? 2 : 0;
934
935     hevc->level = ctx->level;
936
937     hevc->tier = ctx->tier;
938
939     return 0;
940 }
941
942 static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx)
943 {
944     switch (avctx->codec->id) {
945     case AV_CODEC_ID_H264:
946         return nvenc_setup_h264_config(avctx);
947     case AV_CODEC_ID_HEVC:
948         return nvenc_setup_hevc_config(avctx);
949     /* Earlier switch/case will return if unknown codec is passed. */
950     }
951
952     return 0;
953 }
954
955 static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
956 {
957     NvencContext *ctx = avctx->priv_data;
958     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
959     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
960
961     NV_ENC_PRESET_CONFIG preset_config = { 0 };
962     NVENCSTATUS nv_status = NV_ENC_SUCCESS;
963     AVCPBProperties *cpb_props;
964     int res = 0;
965     int dw, dh;
966
967     ctx->encode_config.version = NV_ENC_CONFIG_VER;
968     ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
969
970     ctx->init_encode_params.encodeHeight = avctx->height;
971     ctx->init_encode_params.encodeWidth = avctx->width;
972
973     ctx->init_encode_params.encodeConfig = &ctx->encode_config;
974
975     nvenc_map_preset(ctx);
976
977     preset_config.version = NV_ENC_PRESET_CONFIG_VER;
978     preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
979
980     nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder,
981                                                     ctx->init_encode_params.encodeGUID,
982                                                     ctx->init_encode_params.presetGUID,
983                                                     &preset_config);
984     if (nv_status != NV_ENC_SUCCESS)
985         return nvenc_print_error(avctx, nv_status, "Cannot get the preset configuration");
986
987     memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
988
989     ctx->encode_config.version = NV_ENC_CONFIG_VER;
990
991     if (avctx->sample_aspect_ratio.num && avctx->sample_aspect_ratio.den &&
992         (avctx->sample_aspect_ratio.num != 1 || avctx->sample_aspect_ratio.num != 1)) {
993         av_reduce(&dw, &dh,
994                   avctx->width * avctx->sample_aspect_ratio.num,
995                   avctx->height * avctx->sample_aspect_ratio.den,
996                   1024 * 1024);
997         ctx->init_encode_params.darHeight = dh;
998         ctx->init_encode_params.darWidth = dw;
999     } else {
1000         ctx->init_encode_params.darHeight = avctx->height;
1001         ctx->init_encode_params.darWidth = avctx->width;
1002     }
1003
1004     // De-compensate for hardware, dubiously, trying to compensate for
1005     // playback at 704 pixel width.
1006     if (avctx->width == 720 &&
1007         (avctx->height == 480 || avctx->height == 576)) {
1008         av_reduce(&dw, &dh,
1009                   ctx->init_encode_params.darWidth * 44,
1010                   ctx->init_encode_params.darHeight * 45,
1011                   1024 * 1024);
1012         ctx->init_encode_params.darHeight = dh;
1013         ctx->init_encode_params.darWidth = dw;
1014     }
1015
1016     ctx->init_encode_params.frameRateNum = avctx->time_base.den;
1017     ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
1018
1019     ctx->init_encode_params.enableEncodeAsync = 0;
1020     ctx->init_encode_params.enablePTD = 1;
1021
1022     if (avctx->gop_size > 0) {
1023         if (avctx->max_b_frames >= 0) {
1024             /* 0 is intra-only, 1 is I/P only, 2 is one B-Frame, 3 two B-frames, and so on. */
1025             ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
1026         }
1027
1028         ctx->encode_config.gopLength = avctx->gop_size;
1029     } else if (avctx->gop_size == 0) {
1030         ctx->encode_config.frameIntervalP = 0;
1031         ctx->encode_config.gopLength = 1;
1032     }
1033
1034     ctx->initial_pts[0] = AV_NOPTS_VALUE;
1035     ctx->initial_pts[1] = AV_NOPTS_VALUE;
1036
1037     nvenc_setup_rate_control(avctx);
1038
1039     if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1040         ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
1041     } else {
1042         ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
1043     }
1044
1045     res = nvenc_setup_codec_config(avctx);
1046     if (res)
1047         return res;
1048
1049     nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
1050     if (nv_status != NV_ENC_SUCCESS) {
1051         return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
1052     }
1053
1054     if (ctx->encode_config.frameIntervalP > 1)
1055         avctx->has_b_frames = 2;
1056
1057     if (ctx->encode_config.rcParams.averageBitRate > 0)
1058         avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
1059
1060     cpb_props = ff_add_cpb_side_data(avctx);
1061     if (!cpb_props)
1062         return AVERROR(ENOMEM);
1063     cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
1064     cpb_props->avg_bitrate = avctx->bit_rate;
1065     cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
1066
1067     return 0;
1068 }
1069
1070 static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
1071 {
1072     NvencContext *ctx = avctx->priv_data;
1073     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1074     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1075
1076     NVENCSTATUS nv_status;
1077     NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
1078     allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1079
1080     switch (ctx->data_pix_fmt) {
1081     case AV_PIX_FMT_YUV420P:
1082         ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_YV12_PL;
1083         break;
1084
1085     case AV_PIX_FMT_NV12:
1086         ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_NV12_PL;
1087         break;
1088
1089     case AV_PIX_FMT_P010:
1090         ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1091         break;
1092
1093     case AV_PIX_FMT_YUV444P:
1094         ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_YUV444_PL;
1095         break;
1096
1097     case AV_PIX_FMT_YUV444P16:
1098         ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1099         break;
1100
1101     case AV_PIX_FMT_0RGB32:
1102         ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_ARGB;
1103         break;
1104
1105     case AV_PIX_FMT_0BGR32:
1106         ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_ABGR;
1107         break;
1108
1109     default:
1110         av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format\n");
1111         return AVERROR(EINVAL);
1112     }
1113
1114     if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1115         ctx->surfaces[idx].in_ref = av_frame_alloc();
1116         if (!ctx->surfaces[idx].in_ref)
1117             return AVERROR(ENOMEM);
1118     } else {
1119         NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1120         allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1121         allocSurf.width = (avctx->width + 31) & ~31;
1122         allocSurf.height = (avctx->height + 31) & ~31;
1123         allocSurf.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
1124         allocSurf.bufferFmt = ctx->surfaces[idx].format;
1125
1126         nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
1127         if (nv_status != NV_ENC_SUCCESS) {
1128             return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
1129         }
1130
1131         ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
1132         ctx->surfaces[idx].width = allocSurf.width;
1133         ctx->surfaces[idx].height = allocSurf.height;
1134     }
1135
1136     ctx->surfaces[idx].lockCount = 0;
1137
1138     /* 1MB is large enough to hold most output frames.
1139      * NVENC increases this automaticaly if it is not enough. */
1140     allocOut.size = 1024 * 1024;
1141
1142     allocOut.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
1143
1144     nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
1145     if (nv_status != NV_ENC_SUCCESS) {
1146         int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
1147         if (avctx->pix_fmt != AV_PIX_FMT_CUDA)
1148             p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
1149         av_frame_free(&ctx->surfaces[idx].in_ref);
1150         return err;
1151     }
1152
1153     ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1154     ctx->surfaces[idx].size = allocOut.size;
1155
1156     return 0;
1157 }
1158
1159 static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx)
1160 {
1161     NvencContext *ctx = avctx->priv_data;
1162     int i, res;
1163     int num_mbs = ((avctx->width + 15) >> 4) * ((avctx->height + 15) >> 4);
1164     ctx->nb_surfaces = FFMAX((num_mbs >= 8160) ? 32 : 48,
1165                              ctx->nb_surfaces);
1166     ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
1167
1168
1169     ctx->surfaces = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->surfaces));
1170     if (!ctx->surfaces)
1171         return AVERROR(ENOMEM);
1172
1173     ctx->timestamp_list = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
1174     if (!ctx->timestamp_list)
1175         return AVERROR(ENOMEM);
1176     ctx->output_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1177     if (!ctx->output_surface_queue)
1178         return AVERROR(ENOMEM);
1179     ctx->output_surface_ready_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1180     if (!ctx->output_surface_ready_queue)
1181         return AVERROR(ENOMEM);
1182
1183     for (i = 0; i < ctx->nb_surfaces; i++) {
1184         if ((res = nvenc_alloc_surface(avctx, i)) < 0)
1185             return res;
1186     }
1187
1188     return 0;
1189 }
1190
1191 static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
1192 {
1193     NvencContext *ctx = avctx->priv_data;
1194     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1195     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1196
1197     NVENCSTATUS nv_status;
1198     uint32_t outSize = 0;
1199     char tmpHeader[256];
1200     NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1201     payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1202
1203     payload.spsppsBuffer = tmpHeader;
1204     payload.inBufferSize = sizeof(tmpHeader);
1205     payload.outSPSPPSPayloadSize = &outSize;
1206
1207     nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
1208     if (nv_status != NV_ENC_SUCCESS) {
1209         return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
1210     }
1211
1212     avctx->extradata_size = outSize;
1213     avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
1214
1215     if (!avctx->extradata) {
1216         return AVERROR(ENOMEM);
1217     }
1218
1219     memcpy(avctx->extradata, tmpHeader, outSize);
1220
1221     return 0;
1222 }
1223
1224 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
1225 {
1226     NvencContext *ctx               = avctx->priv_data;
1227     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1228     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1229     int i;
1230
1231     /* the encoder has to be flushed before it can be closed */
1232     if (ctx->nvencoder) {
1233         NV_ENC_PIC_PARAMS params        = { .version        = NV_ENC_PIC_PARAMS_VER,
1234                                             .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
1235
1236         p_nvenc->nvEncEncodePicture(ctx->nvencoder, &params);
1237     }
1238
1239     av_fifo_freep(&ctx->timestamp_list);
1240     av_fifo_freep(&ctx->output_surface_ready_queue);
1241     av_fifo_freep(&ctx->output_surface_queue);
1242
1243     if (ctx->surfaces && avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1244         for (i = 0; i < ctx->nb_surfaces; ++i) {
1245             if (ctx->surfaces[i].input_surface) {
1246                  p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->surfaces[i].in_map.mappedResource);
1247             }
1248         }
1249         for (i = 0; i < ctx->nb_registered_frames; i++) {
1250             if (ctx->registered_frames[i].regptr)
1251                 p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1252         }
1253         ctx->nb_registered_frames = 0;
1254     }
1255
1256     if (ctx->surfaces) {
1257         for (i = 0; i < ctx->nb_surfaces; ++i) {
1258             if (avctx->pix_fmt != AV_PIX_FMT_CUDA)
1259                 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
1260             av_frame_free(&ctx->surfaces[i].in_ref);
1261             p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
1262         }
1263     }
1264     av_freep(&ctx->surfaces);
1265     ctx->nb_surfaces = 0;
1266
1267     if (ctx->nvencoder)
1268         p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1269     ctx->nvencoder = NULL;
1270
1271     if (ctx->cu_context_internal)
1272         dl_fn->cu_ctx_destroy(ctx->cu_context_internal);
1273     ctx->cu_context = ctx->cu_context_internal = NULL;
1274
1275     if (dl_fn->nvenc)
1276         dlclose(dl_fn->nvenc);
1277     dl_fn->nvenc = NULL;
1278
1279     dl_fn->nvenc_device_count = 0;
1280
1281 #if !CONFIG_CUDA
1282     if (dl_fn->cuda)
1283         dlclose(dl_fn->cuda);
1284     dl_fn->cuda = NULL;
1285 #endif
1286
1287     dl_fn->cu_init = NULL;
1288     dl_fn->cu_device_get_count = NULL;
1289     dl_fn->cu_device_get = NULL;
1290     dl_fn->cu_device_get_name = NULL;
1291     dl_fn->cu_device_compute_capability = NULL;
1292     dl_fn->cu_ctx_create = NULL;
1293     dl_fn->cu_ctx_pop_current = NULL;
1294     dl_fn->cu_ctx_destroy = NULL;
1295
1296     av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
1297
1298     return 0;
1299 }
1300
1301 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
1302 {
1303     NvencContext *ctx = avctx->priv_data;
1304     int ret;
1305
1306     if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1307         AVHWFramesContext *frames_ctx;
1308         if (!avctx->hw_frames_ctx) {
1309             av_log(avctx, AV_LOG_ERROR,
1310                    "hw_frames_ctx must be set when using GPU frames as input\n");
1311             return AVERROR(EINVAL);
1312         }
1313         frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1314         ctx->data_pix_fmt = frames_ctx->sw_format;
1315     } else {
1316         ctx->data_pix_fmt = avctx->pix_fmt;
1317     }
1318
1319     if ((ret = nvenc_load_libraries(avctx)) < 0)
1320         return ret;
1321
1322     if ((ret = nvenc_setup_device(avctx)) < 0)
1323         return ret;
1324
1325     if ((ret = nvenc_setup_encoder(avctx)) < 0)
1326         return ret;
1327
1328     if ((ret = nvenc_setup_surfaces(avctx)) < 0)
1329         return ret;
1330
1331     if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1332         if ((ret = nvenc_setup_extradata(avctx)) < 0)
1333             return ret;
1334     }
1335
1336     return 0;
1337 }
1338
1339 static NvencSurface *get_free_frame(NvencContext *ctx)
1340 {
1341     int i;
1342
1343     for (i = 0; i < ctx->nb_surfaces; ++i) {
1344         if (!ctx->surfaces[i].lockCount) {
1345             ctx->surfaces[i].lockCount = 1;
1346             return &ctx->surfaces[i];
1347         }
1348     }
1349
1350     return NULL;
1351 }
1352
1353 static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *nv_surface,
1354             NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params, const AVFrame *frame)
1355 {
1356     int dst_linesize[4] = {
1357         lock_buffer_params->pitch,
1358         lock_buffer_params->pitch,
1359         lock_buffer_params->pitch,
1360         lock_buffer_params->pitch
1361     };
1362     uint8_t *dst_data[4];
1363     int ret;
1364
1365     if (frame->format == AV_PIX_FMT_YUV420P)
1366         dst_linesize[1] = dst_linesize[2] >>= 1;
1367
1368     ret = av_image_fill_pointers(dst_data, frame->format, nv_surface->height,
1369                                  lock_buffer_params->bufferDataPtr, dst_linesize);
1370     if (ret < 0)
1371         return ret;
1372
1373     if (frame->format == AV_PIX_FMT_YUV420P)
1374         FFSWAP(uint8_t*, dst_data[1], dst_data[2]);
1375
1376     av_image_copy(dst_data, dst_linesize,
1377                   (const uint8_t**)frame->data, frame->linesize, frame->format,
1378                   avctx->width, avctx->height);
1379
1380     return 0;
1381 }
1382
1383 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1384 {
1385     NvencContext *ctx = avctx->priv_data;
1386     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1387     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1388
1389     int i;
1390
1391     if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1392         for (i = 0; i < ctx->nb_registered_frames; i++) {
1393             if (!ctx->registered_frames[i].mapped) {
1394                 if (ctx->registered_frames[i].regptr) {
1395                     p_nvenc->nvEncUnregisterResource(ctx->nvencoder,
1396                                                 ctx->registered_frames[i].regptr);
1397                     ctx->registered_frames[i].regptr = NULL;
1398                 }
1399                 return i;
1400             }
1401         }
1402     } else {
1403         return ctx->nb_registered_frames++;
1404     }
1405
1406     av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1407     return AVERROR(ENOMEM);
1408 }
1409
1410 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1411 {
1412     NvencContext *ctx = avctx->priv_data;
1413     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1414     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1415
1416     AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1417     NV_ENC_REGISTER_RESOURCE reg;
1418     int i, idx, ret;
1419
1420     for (i = 0; i < ctx->nb_registered_frames; i++) {
1421         if (ctx->registered_frames[i].ptr == (CUdeviceptr)frame->data[0])
1422             return i;
1423     }
1424
1425     idx = nvenc_find_free_reg_resource(avctx);
1426     if (idx < 0)
1427         return idx;
1428
1429     reg.version            = NV_ENC_REGISTER_RESOURCE_VER;
1430     reg.resourceType       = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1431     reg.width              = frames_ctx->width;
1432     reg.height             = frames_ctx->height;
1433     reg.bufferFormat       = ctx->surfaces[0].format;
1434     reg.pitch              = frame->linesize[0];
1435     reg.resourceToRegister = frame->data[0];
1436
1437     ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, &reg);
1438     if (ret != NV_ENC_SUCCESS) {
1439         nvenc_print_error(avctx, ret, "Error registering an input resource");
1440         return AVERROR_UNKNOWN;
1441     }
1442
1443     ctx->registered_frames[idx].ptr    = (CUdeviceptr)frame->data[0];
1444     ctx->registered_frames[idx].regptr = reg.registeredResource;
1445     return idx;
1446 }
1447
1448 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1449                                       NvencSurface *nvenc_frame)
1450 {
1451     NvencContext *ctx = avctx->priv_data;
1452     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1453     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1454
1455     int res;
1456     NVENCSTATUS nv_status;
1457
1458     if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1459         int reg_idx = nvenc_register_frame(avctx, frame);
1460         if (reg_idx < 0) {
1461             av_log(avctx, AV_LOG_ERROR, "Could not register an input CUDA frame\n");
1462             return reg_idx;
1463         }
1464
1465         res = av_frame_ref(nvenc_frame->in_ref, frame);
1466         if (res < 0)
1467             return res;
1468
1469         nvenc_frame->in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1470         nvenc_frame->in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1471         nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &nvenc_frame->in_map);
1472         if (nv_status != NV_ENC_SUCCESS) {
1473             av_frame_unref(nvenc_frame->in_ref);
1474             return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
1475         }
1476
1477         ctx->registered_frames[reg_idx].mapped = 1;
1478         nvenc_frame->reg_idx                   = reg_idx;
1479         nvenc_frame->input_surface             = nvenc_frame->in_map.mappedResource;
1480         nvenc_frame->pitch                     = frame->linesize[0];
1481         return 0;
1482     } else {
1483         NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1484
1485         lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1486         lockBufferParams.inputBuffer = nvenc_frame->input_surface;
1487
1488         nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
1489         if (nv_status != NV_ENC_SUCCESS) {
1490             return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
1491         }
1492
1493         nvenc_frame->pitch = lockBufferParams.pitch;
1494         res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
1495
1496         nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
1497         if (nv_status != NV_ENC_SUCCESS) {
1498             return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
1499         }
1500
1501         return res;
1502     }
1503 }
1504
1505 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1506                                             NV_ENC_PIC_PARAMS *params)
1507 {
1508     NvencContext *ctx = avctx->priv_data;
1509
1510     switch (avctx->codec->id) {
1511     case AV_CODEC_ID_H264:
1512         params->codecPicParams.h264PicParams.sliceMode =
1513             ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1514         params->codecPicParams.h264PicParams.sliceModeData =
1515             ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1516       break;
1517     case AV_CODEC_ID_HEVC:
1518         params->codecPicParams.hevcPicParams.sliceMode =
1519             ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1520         params->codecPicParams.hevcPicParams.sliceModeData =
1521             ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1522         break;
1523     }
1524 }
1525
1526 static inline void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
1527 {
1528     av_fifo_generic_write(queue, &timestamp, sizeof(timestamp), NULL);
1529 }
1530
1531 static inline int64_t timestamp_queue_dequeue(AVFifoBuffer* queue)
1532 {
1533     int64_t timestamp = AV_NOPTS_VALUE;
1534     if (av_fifo_size(queue) > 0)
1535         av_fifo_generic_read(queue, &timestamp, sizeof(timestamp), NULL);
1536
1537     return timestamp;
1538 }
1539
1540 static int nvenc_set_timestamp(AVCodecContext *avctx,
1541                                NV_ENC_LOCK_BITSTREAM *params,
1542                                AVPacket *pkt)
1543 {
1544     NvencContext *ctx = avctx->priv_data;
1545
1546     pkt->pts = params->outputTimeStamp;
1547
1548     /* generate the first dts by linearly extrapolating the
1549      * first two pts values to the past */
1550     if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
1551         ctx->initial_pts[1] != AV_NOPTS_VALUE) {
1552         int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
1553         int64_t delta;
1554
1555         if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
1556             (ts0 > 0 && ts1 < INT64_MIN + ts0))
1557             return AVERROR(ERANGE);
1558         delta = ts1 - ts0;
1559
1560         if ((delta < 0 && ts0 > INT64_MAX + delta) ||
1561             (delta > 0 && ts0 < INT64_MIN + delta))
1562             return AVERROR(ERANGE);
1563         pkt->dts = ts0 - delta;
1564
1565         ctx->first_packet_output = 1;
1566         return 0;
1567     }
1568
1569     pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
1570
1571     return 0;
1572 }
1573
1574 static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
1575 {
1576     NvencContext *ctx = avctx->priv_data;
1577     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1578     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1579
1580     uint32_t slice_mode_data;
1581     uint32_t *slice_offsets = NULL;
1582     NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1583     NVENCSTATUS nv_status;
1584     int res = 0;
1585
1586     enum AVPictureType pict_type;
1587
1588     switch (avctx->codec->id) {
1589     case AV_CODEC_ID_H264:
1590       slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1591       break;
1592     case AV_CODEC_ID_H265:
1593       slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1594       break;
1595     default:
1596       av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
1597       res = AVERROR(EINVAL);
1598       goto error;
1599     }
1600     slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
1601
1602     if (!slice_offsets)
1603         goto error;
1604
1605     lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1606
1607     lock_params.doNotWait = 0;
1608     lock_params.outputBitstream = tmpoutsurf->output_surface;
1609     lock_params.sliceOffsets = slice_offsets;
1610
1611     nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
1612     if (nv_status != NV_ENC_SUCCESS) {
1613         res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
1614         goto error;
1615     }
1616
1617     if (res = ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes,0)) {
1618         p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1619         goto error;
1620     }
1621
1622     memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1623
1624     nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1625     if (nv_status != NV_ENC_SUCCESS)
1626         nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
1627
1628
1629     if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1630         p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, tmpoutsurf->in_map.mappedResource);
1631         av_frame_unref(tmpoutsurf->in_ref);
1632         ctx->registered_frames[tmpoutsurf->reg_idx].mapped = 0;
1633
1634         tmpoutsurf->input_surface = NULL;
1635     }
1636
1637     switch (lock_params.pictureType) {
1638     case NV_ENC_PIC_TYPE_IDR:
1639         pkt->flags |= AV_PKT_FLAG_KEY;
1640     case NV_ENC_PIC_TYPE_I:
1641         pict_type = AV_PICTURE_TYPE_I;
1642         break;
1643     case NV_ENC_PIC_TYPE_P:
1644         pict_type = AV_PICTURE_TYPE_P;
1645         break;
1646     case NV_ENC_PIC_TYPE_B:
1647         pict_type = AV_PICTURE_TYPE_B;
1648         break;
1649     case NV_ENC_PIC_TYPE_BI:
1650         pict_type = AV_PICTURE_TYPE_BI;
1651         break;
1652     default:
1653         av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
1654         av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
1655         res = AVERROR_EXTERNAL;
1656         goto error;
1657     }
1658
1659 #if FF_API_CODED_FRAME
1660 FF_DISABLE_DEPRECATION_WARNINGS
1661     avctx->coded_frame->pict_type = pict_type;
1662 FF_ENABLE_DEPRECATION_WARNINGS
1663 #endif
1664
1665     ff_side_data_set_encoder_stats(pkt,
1666         (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
1667
1668     res = nvenc_set_timestamp(avctx, &lock_params, pkt);
1669     if (res < 0)
1670         goto error2;
1671
1672     av_free(slice_offsets);
1673
1674     return 0;
1675
1676 error:
1677     timestamp_queue_dequeue(ctx->timestamp_list);
1678
1679 error2:
1680     av_free(slice_offsets);
1681
1682     return res;
1683 }
1684
1685 static int output_ready(AVCodecContext *avctx, int flush)
1686 {
1687     NvencContext *ctx = avctx->priv_data;
1688     int nb_ready, nb_pending;
1689
1690     /* when B-frames are enabled, we wait for two initial timestamps to
1691      * calculate the first dts */
1692     if (!flush && avctx->max_b_frames > 0 &&
1693         (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
1694         return 0;
1695
1696     nb_ready   = av_fifo_size(ctx->output_surface_ready_queue)   / sizeof(NvencSurface*);
1697     nb_pending = av_fifo_size(ctx->output_surface_queue)         / sizeof(NvencSurface*);
1698     if (flush)
1699         return nb_ready > 0;
1700     return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
1701 }
1702
1703 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1704                           const AVFrame *frame, int *got_packet)
1705 {
1706     NVENCSTATUS nv_status;
1707     NvencSurface *tmpoutsurf, *inSurf;
1708     int res;
1709
1710     NvencContext *ctx = avctx->priv_data;
1711     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1712     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1713
1714     NV_ENC_PIC_PARAMS pic_params = { 0 };
1715     pic_params.version = NV_ENC_PIC_PARAMS_VER;
1716
1717     if (frame) {
1718         inSurf = get_free_frame(ctx);
1719         if (!inSurf) {
1720             av_log(avctx, AV_LOG_ERROR, "No free surfaces\n");
1721             return AVERROR_BUG;
1722         }
1723
1724         res = nvenc_upload_frame(avctx, frame, inSurf);
1725         if (res) {
1726             inSurf->lockCount = 0;
1727             return res;
1728         }
1729
1730         pic_params.inputBuffer = inSurf->input_surface;
1731         pic_params.bufferFmt = inSurf->format;
1732         pic_params.inputWidth = avctx->width;
1733         pic_params.inputHeight = avctx->height;
1734         pic_params.inputPitch = inSurf->pitch;
1735         pic_params.outputBitstream = inSurf->output_surface;
1736
1737         if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1738             if (frame->top_field_first)
1739                 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
1740             else
1741                 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
1742         } else {
1743             pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1744         }
1745
1746         if (ctx->forced_idr >= 0 && frame->pict_type == AV_PICTURE_TYPE_I) {
1747             pic_params.encodePicFlags =
1748                 ctx->forced_idr ? NV_ENC_PIC_FLAG_FORCEIDR : NV_ENC_PIC_FLAG_FORCEINTRA;
1749         } else {
1750             pic_params.encodePicFlags = 0;
1751         }
1752
1753         pic_params.inputTimeStamp = frame->pts;
1754
1755         nvenc_codec_specific_pic_params(avctx, &pic_params);
1756     } else {
1757         pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1758     }
1759
1760     nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
1761     if (nv_status != NV_ENC_SUCCESS &&
1762         nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
1763         return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
1764
1765     if (frame) {
1766         av_fifo_generic_write(ctx->output_surface_queue, &inSurf, sizeof(inSurf), NULL);
1767         timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
1768
1769         if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
1770             ctx->initial_pts[0] = frame->pts;
1771         else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
1772             ctx->initial_pts[1] = frame->pts;
1773     }
1774
1775     /* all the pending buffers are now ready for output */
1776     if (nv_status == NV_ENC_SUCCESS) {
1777         while (av_fifo_size(ctx->output_surface_queue) > 0) {
1778             av_fifo_generic_read(ctx->output_surface_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
1779             av_fifo_generic_write(ctx->output_surface_ready_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
1780         }
1781     }
1782
1783     if (output_ready(avctx, !frame)) {
1784         av_fifo_generic_read(ctx->output_surface_ready_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
1785
1786         res = process_output_surface(avctx, pkt, tmpoutsurf);
1787
1788         if (res)
1789             return res;
1790
1791         av_assert0(tmpoutsurf->lockCount);
1792         tmpoutsurf->lockCount--;
1793
1794         *got_packet = 1;
1795     } else {
1796         *got_packet = 0;
1797     }
1798
1799     return 0;
1800 }