OSDN Git Service

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