OSDN Git Service

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