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