]> git.sesse.net Git - ffmpeg/blob - libavcodec/nvenc.c
avformat/alp: fix handling of TUN files
[ffmpeg] / libavcodec / nvenc.c
1 /*
2  * H.264/HEVC hardware encoding using nvidia nvenc
3  * Copyright (c) 2016 Timo Rothenpieler <timo@rothenpieler.org>
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "config.h"
23
24 #include "nvenc.h"
25 #include "hevc_sei.h"
26
27 #include "libavutil/hwcontext_cuda.h"
28 #include "libavutil/hwcontext.h"
29 #include "libavutil/cuda_check.h"
30 #include "libavutil/imgutils.h"
31 #include "libavutil/avassert.h"
32 #include "libavutil/mem.h"
33 #include "libavutil/pixdesc.h"
34 #include "atsc_a53.h"
35 #include "encode.h"
36 #include "internal.h"
37 #include "packet_internal.h"
38
39 #define CHECK_CU(x) FF_CUDA_CHECK_DL(avctx, dl_fn->cuda_dl, x)
40
41 #define NVENC_CAP 0x30
42 #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR ||             \
43                     rc == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ || \
44                     rc == NV_ENC_PARAMS_RC_CBR_HQ)
45
46 #ifdef NVENC_HAVE_NEW_PRESETS
47 #define IS_SDK10_PRESET(p) ((p) >= PRESET_P1 && (p) <= PRESET_P7)
48 #else
49 #define IS_SDK10_PRESET(p) 0
50 #endif
51
52 const enum AVPixelFormat ff_nvenc_pix_fmts[] = {
53     AV_PIX_FMT_YUV420P,
54     AV_PIX_FMT_NV12,
55     AV_PIX_FMT_P010,
56     AV_PIX_FMT_YUV444P,
57     AV_PIX_FMT_P016,      // Truncated to 10bits
58     AV_PIX_FMT_YUV444P16, // Truncated to 10bits
59     AV_PIX_FMT_0RGB32,
60     AV_PIX_FMT_0BGR32,
61     AV_PIX_FMT_CUDA,
62 #if CONFIG_D3D11VA
63     AV_PIX_FMT_D3D11,
64 #endif
65     AV_PIX_FMT_NONE
66 };
67
68 const AVCodecHWConfigInternal *ff_nvenc_hw_configs[] = {
69     HW_CONFIG_ENCODER_FRAMES(CUDA,  CUDA),
70     HW_CONFIG_ENCODER_DEVICE(NONE,  CUDA),
71 #if CONFIG_D3D11VA
72     HW_CONFIG_ENCODER_FRAMES(D3D11, D3D11VA),
73     HW_CONFIG_ENCODER_DEVICE(NONE,  D3D11VA),
74 #endif
75     NULL,
76 };
77
78 #define IS_10BIT(pix_fmt)  (pix_fmt == AV_PIX_FMT_P010    || \
79                             pix_fmt == AV_PIX_FMT_P016    || \
80                             pix_fmt == AV_PIX_FMT_YUV444P16)
81
82 #define IS_YUV444(pix_fmt) (pix_fmt == AV_PIX_FMT_YUV444P || \
83                             pix_fmt == AV_PIX_FMT_YUV444P16)
84
85 static const struct {
86     NVENCSTATUS nverr;
87     int         averr;
88     const char *desc;
89 } nvenc_errors[] = {
90     { NV_ENC_SUCCESS,                      0,                "success"                  },
91     { NV_ENC_ERR_NO_ENCODE_DEVICE,         AVERROR(ENOENT),  "no encode device"         },
92     { NV_ENC_ERR_UNSUPPORTED_DEVICE,       AVERROR(ENOSYS),  "unsupported device"       },
93     { NV_ENC_ERR_INVALID_ENCODERDEVICE,    AVERROR(EINVAL),  "invalid encoder device"   },
94     { NV_ENC_ERR_INVALID_DEVICE,           AVERROR(EINVAL),  "invalid device"           },
95     { NV_ENC_ERR_DEVICE_NOT_EXIST,         AVERROR(EIO),     "device does not exist"    },
96     { NV_ENC_ERR_INVALID_PTR,              AVERROR(EFAULT),  "invalid ptr"              },
97     { NV_ENC_ERR_INVALID_EVENT,            AVERROR(EINVAL),  "invalid event"            },
98     { NV_ENC_ERR_INVALID_PARAM,            AVERROR(EINVAL),  "invalid param"            },
99     { NV_ENC_ERR_INVALID_CALL,             AVERROR(EINVAL),  "invalid call"             },
100     { NV_ENC_ERR_OUT_OF_MEMORY,            AVERROR(ENOMEM),  "out of memory"            },
101     { NV_ENC_ERR_ENCODER_NOT_INITIALIZED,  AVERROR(EINVAL),  "encoder not initialized"  },
102     { NV_ENC_ERR_UNSUPPORTED_PARAM,        AVERROR(ENOSYS),  "unsupported param"        },
103     { NV_ENC_ERR_LOCK_BUSY,                AVERROR(EAGAIN),  "lock busy"                },
104     { NV_ENC_ERR_NOT_ENOUGH_BUFFER,        AVERROR_BUFFER_TOO_SMALL, "not enough buffer"},
105     { NV_ENC_ERR_INVALID_VERSION,          AVERROR(EINVAL),  "invalid version"          },
106     { NV_ENC_ERR_MAP_FAILED,               AVERROR(EIO),     "map failed"               },
107     { NV_ENC_ERR_NEED_MORE_INPUT,          AVERROR(EAGAIN),  "need more input"          },
108     { NV_ENC_ERR_ENCODER_BUSY,             AVERROR(EAGAIN),  "encoder busy"             },
109     { NV_ENC_ERR_EVENT_NOT_REGISTERD,      AVERROR(EBADF),   "event not registered"     },
110     { NV_ENC_ERR_GENERIC,                  AVERROR_UNKNOWN,  "generic error"            },
111     { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY,  AVERROR(EINVAL),  "incompatible client key"  },
112     { NV_ENC_ERR_UNIMPLEMENTED,            AVERROR(ENOSYS),  "unimplemented"            },
113     { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO),     "resource register failed" },
114     { NV_ENC_ERR_RESOURCE_NOT_REGISTERED,  AVERROR(EBADF),   "resource not registered"  },
115     { NV_ENC_ERR_RESOURCE_NOT_MAPPED,      AVERROR(EBADF),   "resource not mapped"      },
116 };
117
118 static int nvenc_map_error(NVENCSTATUS err, const char **desc)
119 {
120     int i;
121     for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
122         if (nvenc_errors[i].nverr == err) {
123             if (desc)
124                 *desc = nvenc_errors[i].desc;
125             return nvenc_errors[i].averr;
126         }
127     }
128     if (desc)
129         *desc = "unknown error";
130     return AVERROR_UNKNOWN;
131 }
132
133 static int nvenc_print_error(AVCodecContext *avctx, NVENCSTATUS err,
134                              const char *error_string)
135 {
136     const char *desc;
137     const char *details = "(no details)";
138     int ret = nvenc_map_error(err, &desc);
139
140 #ifdef NVENC_HAVE_GETLASTERRORSTRING
141     NvencContext *ctx = avctx->priv_data;
142     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
143
144     if (p_nvenc && ctx->nvencoder)
145         details = p_nvenc->nvEncGetLastErrorString(ctx->nvencoder);
146 #endif
147
148     av_log(avctx, AV_LOG_ERROR, "%s: %s (%d): %s\n", error_string, desc, err, details);
149
150     return ret;
151 }
152
153 static void nvenc_print_driver_requirement(AVCodecContext *avctx, int level)
154 {
155 #if NVENCAPI_CHECK_VERSION(11, 1)
156     const char *minver = "(unknown)";
157 #elif NVENCAPI_CHECK_VERSION(11, 0)
158 # if defined(_WIN32) || defined(__CYGWIN__)
159     const char *minver = "456.71";
160 # else
161     const char *minver = "455.28";
162 # endif
163 #elif NVENCAPI_CHECK_VERSION(10, 0)
164 # if defined(_WIN32) || defined(__CYGWIN__)
165     const char *minver = "450.51";
166 # else
167     const char *minver = "445.87";
168 # endif
169 #elif NVENCAPI_CHECK_VERSION(9, 1)
170 # if defined(_WIN32) || defined(__CYGWIN__)
171     const char *minver = "436.15";
172 # else
173     const char *minver = "435.21";
174 # endif
175 #elif NVENCAPI_CHECK_VERSION(9, 0)
176 # if defined(_WIN32) || defined(__CYGWIN__)
177     const char *minver = "418.81";
178 # else
179     const char *minver = "418.30";
180 # endif
181 #elif NVENCAPI_CHECK_VERSION(8, 2)
182 # if defined(_WIN32) || defined(__CYGWIN__)
183     const char *minver = "397.93";
184 # else
185     const char *minver = "396.24";
186 #endif
187 #elif NVENCAPI_CHECK_VERSION(8, 1)
188 # if defined(_WIN32) || defined(__CYGWIN__)
189     const char *minver = "390.77";
190 # else
191     const char *minver = "390.25";
192 # endif
193 #else
194 # if defined(_WIN32) || defined(__CYGWIN__)
195     const char *minver = "378.66";
196 # else
197     const char *minver = "378.13";
198 # endif
199 #endif
200     av_log(avctx, level, "The minimum required Nvidia driver for nvenc is %s or newer\n", minver);
201 }
202
203 static av_cold int nvenc_load_libraries(AVCodecContext *avctx)
204 {
205     NvencContext *ctx            = avctx->priv_data;
206     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
207     NVENCSTATUS err;
208     uint32_t nvenc_max_ver;
209     int ret;
210
211     ret = cuda_load_functions(&dl_fn->cuda_dl, avctx);
212     if (ret < 0)
213         return ret;
214
215     ret = nvenc_load_functions(&dl_fn->nvenc_dl, avctx);
216     if (ret < 0) {
217         nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
218         return ret;
219     }
220
221     err = dl_fn->nvenc_dl->NvEncodeAPIGetMaxSupportedVersion(&nvenc_max_ver);
222     if (err != NV_ENC_SUCCESS)
223         return nvenc_print_error(avctx, err, "Failed to query nvenc max version");
224
225     av_log(avctx, AV_LOG_VERBOSE, "Loaded Nvenc version %d.%d\n", nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
226
227     if ((NVENCAPI_MAJOR_VERSION << 4 | NVENCAPI_MINOR_VERSION) > nvenc_max_ver) {
228         av_log(avctx, AV_LOG_ERROR, "Driver does not support the required nvenc API version. "
229                "Required: %d.%d Found: %d.%d\n",
230                NVENCAPI_MAJOR_VERSION, NVENCAPI_MINOR_VERSION,
231                nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
232         nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
233         return AVERROR(ENOSYS);
234     }
235
236     dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
237
238     err = dl_fn->nvenc_dl->NvEncodeAPICreateInstance(&dl_fn->nvenc_funcs);
239     if (err != NV_ENC_SUCCESS)
240         return nvenc_print_error(avctx, err, "Failed to create nvenc instance");
241
242     av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
243
244     return 0;
245 }
246
247 static int nvenc_push_context(AVCodecContext *avctx)
248 {
249     NvencContext *ctx            = avctx->priv_data;
250     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
251
252     if (ctx->d3d11_device)
253         return 0;
254
255     return CHECK_CU(dl_fn->cuda_dl->cuCtxPushCurrent(ctx->cu_context));
256 }
257
258 static int nvenc_pop_context(AVCodecContext *avctx)
259 {
260     NvencContext *ctx            = avctx->priv_data;
261     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
262     CUcontext dummy;
263
264     if (ctx->d3d11_device)
265         return 0;
266
267     return CHECK_CU(dl_fn->cuda_dl->cuCtxPopCurrent(&dummy));
268 }
269
270 static av_cold int nvenc_open_session(AVCodecContext *avctx)
271 {
272     NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
273     NvencContext *ctx = avctx->priv_data;
274     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
275     NVENCSTATUS ret;
276
277     params.version    = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
278     params.apiVersion = NVENCAPI_VERSION;
279     if (ctx->d3d11_device) {
280         params.device     = ctx->d3d11_device;
281         params.deviceType = NV_ENC_DEVICE_TYPE_DIRECTX;
282     } else {
283         params.device     = ctx->cu_context;
284         params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
285     }
286
287     ret = p_nvenc->nvEncOpenEncodeSessionEx(&params, &ctx->nvencoder);
288     if (ret != NV_ENC_SUCCESS) {
289         ctx->nvencoder = NULL;
290         return nvenc_print_error(avctx, ret, "OpenEncodeSessionEx failed");
291     }
292
293     return 0;
294 }
295
296 static int nvenc_check_codec_support(AVCodecContext *avctx)
297 {
298     NvencContext *ctx                    = avctx->priv_data;
299     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
300     int i, ret, count = 0;
301     GUID *guids = NULL;
302
303     ret = p_nvenc->nvEncGetEncodeGUIDCount(ctx->nvencoder, &count);
304
305     if (ret != NV_ENC_SUCCESS || !count)
306         return AVERROR(ENOSYS);
307
308     guids = av_malloc(count * sizeof(GUID));
309     if (!guids)
310         return AVERROR(ENOMEM);
311
312     ret = p_nvenc->nvEncGetEncodeGUIDs(ctx->nvencoder, guids, count, &count);
313     if (ret != NV_ENC_SUCCESS) {
314         ret = AVERROR(ENOSYS);
315         goto fail;
316     }
317
318     ret = AVERROR(ENOSYS);
319     for (i = 0; i < count; i++) {
320         if (!memcmp(&guids[i], &ctx->init_encode_params.encodeGUID, sizeof(*guids))) {
321             ret = 0;
322             break;
323         }
324     }
325
326 fail:
327     av_free(guids);
328
329     return ret;
330 }
331
332 static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
333 {
334     NvencContext *ctx = avctx->priv_data;
335     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
336     NV_ENC_CAPS_PARAM params        = { 0 };
337     int ret, val = 0;
338
339     params.version     = NV_ENC_CAPS_PARAM_VER;
340     params.capsToQuery = cap;
341
342     ret = p_nvenc->nvEncGetEncodeCaps(ctx->nvencoder, ctx->init_encode_params.encodeGUID, &params, &val);
343
344     if (ret == NV_ENC_SUCCESS)
345         return val;
346     return 0;
347 }
348
349 static int nvenc_check_capabilities(AVCodecContext *avctx)
350 {
351     NvencContext *ctx = avctx->priv_data;
352     int ret;
353
354     ret = nvenc_check_codec_support(avctx);
355     if (ret < 0) {
356         av_log(avctx, AV_LOG_WARNING, "Codec not supported\n");
357         return ret;
358     }
359
360     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
361     if (IS_YUV444(ctx->data_pix_fmt) && ret <= 0) {
362         av_log(avctx, AV_LOG_WARNING, "YUV444P not supported\n");
363         return AVERROR(ENOSYS);
364     }
365
366     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOSSLESS_ENCODE);
367     if (ctx->preset >= PRESET_LOSSLESS_DEFAULT && ret <= 0) {
368         av_log(avctx, AV_LOG_WARNING, "Lossless encoding not supported\n");
369         return AVERROR(ENOSYS);
370     }
371
372     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
373     if (ret < avctx->width) {
374         av_log(avctx, AV_LOG_WARNING, "Width %d exceeds %d\n",
375                avctx->width, ret);
376         return AVERROR(ENOSYS);
377     }
378
379     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
380     if (ret < avctx->height) {
381         av_log(avctx, AV_LOG_WARNING, "Height %d exceeds %d\n",
382                avctx->height, ret);
383         return AVERROR(ENOSYS);
384     }
385
386     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
387     if (ret < avctx->max_b_frames) {
388         av_log(avctx, AV_LOG_WARNING, "Max B-frames %d exceed %d\n",
389                avctx->max_b_frames, ret);
390
391         return AVERROR(ENOSYS);
392     }
393
394     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_FIELD_ENCODING);
395     if (ret < 1 && avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
396         av_log(avctx, AV_LOG_WARNING,
397                "Interlaced encoding is not supported. Supported level: %d\n",
398                ret);
399         return AVERROR(ENOSYS);
400     }
401
402     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_10BIT_ENCODE);
403     if (IS_10BIT(ctx->data_pix_fmt) && ret <= 0) {
404         av_log(avctx, AV_LOG_WARNING, "10 bit encode not supported\n");
405         return AVERROR(ENOSYS);
406     }
407
408     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOOKAHEAD);
409     if (ctx->rc_lookahead > 0 && ret <= 0) {
410         av_log(avctx, AV_LOG_WARNING, "RC lookahead not supported\n");
411         return AVERROR(ENOSYS);
412     }
413
414     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_TEMPORAL_AQ);
415     if (ctx->temporal_aq > 0 && ret <= 0) {
416         av_log(avctx, AV_LOG_WARNING, "Temporal AQ not supported\n");
417         return AVERROR(ENOSYS);
418     }
419
420     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_WEIGHTED_PREDICTION);
421     if (ctx->weighted_pred > 0 && ret <= 0) {
422         av_log (avctx, AV_LOG_WARNING, "Weighted Prediction not supported\n");
423         return AVERROR(ENOSYS);
424     }
425
426     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_CABAC);
427     if (ctx->coder == NV_ENC_H264_ENTROPY_CODING_MODE_CABAC && ret <= 0) {
428         av_log(avctx, AV_LOG_WARNING, "CABAC entropy coding not supported\n");
429         return AVERROR(ENOSYS);
430     }
431
432 #ifdef NVENC_HAVE_BFRAME_REF_MODE
433     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_BFRAME_REF_MODE);
434     if (ctx->b_ref_mode == NV_ENC_BFRAME_REF_MODE_EACH && ret != 1 && ret != 3) {
435         av_log(avctx, AV_LOG_WARNING, "Each B frame as reference is not supported\n");
436         return AVERROR(ENOSYS);
437     } else if (ctx->b_ref_mode != NV_ENC_BFRAME_REF_MODE_DISABLED && ret == 0) {
438         av_log(avctx, AV_LOG_WARNING, "B frames as references are not supported\n");
439         return AVERROR(ENOSYS);
440     }
441 #else
442     if (ctx->b_ref_mode != 0) {
443         av_log(avctx, AV_LOG_WARNING, "B frames as references need SDK 8.1 at build time\n");
444         return AVERROR(ENOSYS);
445     }
446 #endif
447
448 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
449     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_MULTIPLE_REF_FRAMES);
450     if(avctx->refs != NV_ENC_NUM_REF_FRAMES_AUTOSELECT && ret <= 0) {
451         av_log(avctx, AV_LOG_WARNING, "Multiple reference frames are not supported by the device\n");
452         return AVERROR(ENOSYS);
453     }
454 #else
455     if(avctx->refs != 0) {
456         av_log(avctx, AV_LOG_WARNING, "Multiple reference frames need SDK 9.1 at build time\n");
457         return AVERROR(ENOSYS);
458     }
459 #endif
460
461     ctx->support_dyn_bitrate = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_DYN_BITRATE_CHANGE);
462
463     return 0;
464 }
465
466 static av_cold int nvenc_check_device(AVCodecContext *avctx, int idx)
467 {
468     NvencContext *ctx = avctx->priv_data;
469     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
470     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
471     char name[128] = { 0};
472     int major, minor, ret;
473     CUdevice cu_device;
474     int loglevel = AV_LOG_VERBOSE;
475
476     if (ctx->device == LIST_DEVICES)
477         loglevel = AV_LOG_INFO;
478
479     ret = CHECK_CU(dl_fn->cuda_dl->cuDeviceGet(&cu_device, idx));
480     if (ret < 0)
481         return ret;
482
483     ret = CHECK_CU(dl_fn->cuda_dl->cuDeviceGetName(name, sizeof(name), cu_device));
484     if (ret < 0)
485         return ret;
486
487     ret = CHECK_CU(dl_fn->cuda_dl->cuDeviceComputeCapability(&major, &minor, cu_device));
488     if (ret < 0)
489         return ret;
490
491     av_log(avctx, loglevel, "[ GPU #%d - < %s > has Compute SM %d.%d ]\n", idx, name, major, minor);
492     if (((major << 4) | minor) < NVENC_CAP) {
493         av_log(avctx, loglevel, "does not support NVENC\n");
494         goto fail;
495     }
496
497     if (ctx->device != idx && ctx->device != ANY_DEVICE)
498         return -1;
499
500     ret = CHECK_CU(dl_fn->cuda_dl->cuCtxCreate(&ctx->cu_context_internal, 0, cu_device));
501     if (ret < 0)
502         goto fail;
503
504     ctx->cu_context = ctx->cu_context_internal;
505     ctx->cu_stream = NULL;
506
507     if ((ret = nvenc_pop_context(avctx)) < 0)
508         goto fail2;
509
510     if ((ret = nvenc_open_session(avctx)) < 0)
511         goto fail2;
512
513     if ((ret = nvenc_check_capabilities(avctx)) < 0)
514         goto fail3;
515
516     av_log(avctx, loglevel, "supports NVENC\n");
517
518     dl_fn->nvenc_device_count++;
519
520     if (ctx->device == idx || ctx->device == ANY_DEVICE)
521         return 0;
522
523 fail3:
524     if ((ret = nvenc_push_context(avctx)) < 0)
525         return ret;
526
527     p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
528     ctx->nvencoder = NULL;
529
530     if ((ret = nvenc_pop_context(avctx)) < 0)
531         return ret;
532
533 fail2:
534     CHECK_CU(dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal));
535     ctx->cu_context_internal = NULL;
536
537 fail:
538     return AVERROR(ENOSYS);
539 }
540
541 static av_cold int nvenc_setup_device(AVCodecContext *avctx)
542 {
543     NvencContext *ctx            = avctx->priv_data;
544     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
545
546     switch (avctx->codec->id) {
547     case AV_CODEC_ID_H264:
548         ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
549         break;
550     case AV_CODEC_ID_HEVC:
551         ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
552         break;
553     default:
554         return AVERROR_BUG;
555     }
556
557     if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11 || avctx->hw_frames_ctx || avctx->hw_device_ctx) {
558         AVHWFramesContext   *frames_ctx;
559         AVHWDeviceContext   *hwdev_ctx;
560         AVCUDADeviceContext *cuda_device_hwctx = NULL;
561 #if CONFIG_D3D11VA
562         AVD3D11VADeviceContext *d3d11_device_hwctx = NULL;
563 #endif
564         int ret;
565
566         if (avctx->hw_frames_ctx) {
567             frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
568             if (frames_ctx->format == AV_PIX_FMT_CUDA)
569                 cuda_device_hwctx = frames_ctx->device_ctx->hwctx;
570 #if CONFIG_D3D11VA
571             else if (frames_ctx->format == AV_PIX_FMT_D3D11)
572                 d3d11_device_hwctx = frames_ctx->device_ctx->hwctx;
573 #endif
574             else
575                 return AVERROR(EINVAL);
576         } else if (avctx->hw_device_ctx) {
577             hwdev_ctx = (AVHWDeviceContext*)avctx->hw_device_ctx->data;
578             if (hwdev_ctx->type == AV_HWDEVICE_TYPE_CUDA)
579                 cuda_device_hwctx = hwdev_ctx->hwctx;
580 #if CONFIG_D3D11VA
581             else if (hwdev_ctx->type == AV_HWDEVICE_TYPE_D3D11VA)
582                 d3d11_device_hwctx = hwdev_ctx->hwctx;
583 #endif
584             else
585                 return AVERROR(EINVAL);
586         } else {
587             return AVERROR(EINVAL);
588         }
589
590         if (cuda_device_hwctx) {
591             ctx->cu_context = cuda_device_hwctx->cuda_ctx;
592             ctx->cu_stream = cuda_device_hwctx->stream;
593         }
594 #if CONFIG_D3D11VA
595         else if (d3d11_device_hwctx) {
596             ctx->d3d11_device = d3d11_device_hwctx->device;
597             ID3D11Device_AddRef(ctx->d3d11_device);
598         }
599 #endif
600
601         ret = nvenc_open_session(avctx);
602         if (ret < 0)
603             return ret;
604
605         ret = nvenc_check_capabilities(avctx);
606         if (ret < 0) {
607             av_log(avctx, AV_LOG_FATAL, "Provided device doesn't support required NVENC features\n");
608             return ret;
609         }
610     } else {
611         int i, nb_devices = 0;
612
613         if (CHECK_CU(dl_fn->cuda_dl->cuInit(0)) < 0)
614             return AVERROR_UNKNOWN;
615
616         if (CHECK_CU(dl_fn->cuda_dl->cuDeviceGetCount(&nb_devices)) < 0)
617             return AVERROR_UNKNOWN;
618
619         if (!nb_devices) {
620             av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
621                 return AVERROR_EXTERNAL;
622         }
623
624         av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", nb_devices);
625
626         dl_fn->nvenc_device_count = 0;
627         for (i = 0; i < nb_devices; ++i) {
628             if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
629                 return 0;
630         }
631
632         if (ctx->device == LIST_DEVICES)
633             return AVERROR_EXIT;
634
635         if (!dl_fn->nvenc_device_count) {
636             av_log(avctx, AV_LOG_FATAL, "No capable devices found\n");
637             return AVERROR_EXTERNAL;
638         }
639
640         av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->device, nb_devices);
641         return AVERROR(EINVAL);
642     }
643
644     return 0;
645 }
646
647 typedef struct GUIDTuple {
648     const GUID guid;
649     int flags;
650 } GUIDTuple;
651
652 #define PRESET_ALIAS(alias, name, ...) \
653     [PRESET_ ## alias] = { NV_ENC_PRESET_ ## name ## _GUID, __VA_ARGS__ }
654
655 #define PRESET(name, ...) PRESET_ALIAS(name, name, __VA_ARGS__)
656
657 static void nvenc_map_preset(NvencContext *ctx)
658 {
659     GUIDTuple presets[] = {
660 #ifdef NVENC_HAVE_NEW_PRESETS
661         PRESET(P1),
662         PRESET(P2),
663         PRESET(P3),
664         PRESET(P4),
665         PRESET(P5),
666         PRESET(P6),
667         PRESET(P7),
668         PRESET_ALIAS(SLOW,   P7, NVENC_TWO_PASSES),
669         PRESET_ALIAS(MEDIUM, P4, NVENC_ONE_PASS),
670         PRESET_ALIAS(FAST,   P1, NVENC_ONE_PASS),
671         // Compat aliases
672         PRESET_ALIAS(DEFAULT,             P4, NVENC_DEPRECATED_PRESET),
673         PRESET_ALIAS(HP,                  P1, NVENC_DEPRECATED_PRESET),
674         PRESET_ALIAS(HQ,                  P7, NVENC_DEPRECATED_PRESET),
675         PRESET_ALIAS(BD,                  P5, NVENC_DEPRECATED_PRESET),
676         PRESET_ALIAS(LOW_LATENCY_DEFAULT, P4, NVENC_DEPRECATED_PRESET | NVENC_LOWLATENCY),
677         PRESET_ALIAS(LOW_LATENCY_HP,      P1, NVENC_DEPRECATED_PRESET | NVENC_LOWLATENCY),
678         PRESET_ALIAS(LOW_LATENCY_HQ,      P7, NVENC_DEPRECATED_PRESET | NVENC_LOWLATENCY),
679         PRESET_ALIAS(LOSSLESS_DEFAULT,    P4, NVENC_DEPRECATED_PRESET | NVENC_LOSSLESS),
680         PRESET_ALIAS(LOSSLESS_HP,         P1, NVENC_DEPRECATED_PRESET | NVENC_LOSSLESS),
681 #else
682         PRESET(DEFAULT),
683         PRESET(HP),
684         PRESET(HQ),
685         PRESET(BD),
686         PRESET_ALIAS(SLOW,   HQ,    NVENC_TWO_PASSES),
687         PRESET_ALIAS(MEDIUM, HQ,    NVENC_ONE_PASS),
688         PRESET_ALIAS(FAST,   HP,    NVENC_ONE_PASS),
689         PRESET(LOW_LATENCY_DEFAULT, NVENC_LOWLATENCY),
690         PRESET(LOW_LATENCY_HP,      NVENC_LOWLATENCY),
691         PRESET(LOW_LATENCY_HQ,      NVENC_LOWLATENCY),
692         PRESET(LOSSLESS_DEFAULT,    NVENC_LOSSLESS),
693         PRESET(LOSSLESS_HP,         NVENC_LOSSLESS),
694 #endif
695     };
696
697     GUIDTuple *t = &presets[ctx->preset];
698
699     ctx->init_encode_params.presetGUID = t->guid;
700     ctx->flags = t->flags;
701 }
702
703 #undef PRESET
704 #undef PRESET_ALIAS
705
706 static av_cold void set_constqp(AVCodecContext *avctx)
707 {
708     NvencContext *ctx = avctx->priv_data;
709     NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
710
711     rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
712
713     if (ctx->init_qp_p >= 0) {
714         rc->constQP.qpInterP = ctx->init_qp_p;
715         if (ctx->init_qp_i >= 0 && ctx->init_qp_b >= 0) {
716             rc->constQP.qpIntra = ctx->init_qp_i;
717             rc->constQP.qpInterB = ctx->init_qp_b;
718         } else if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
719             rc->constQP.qpIntra = av_clip(
720                 rc->constQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
721             rc->constQP.qpInterB = av_clip(
722                 rc->constQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
723         } else {
724             rc->constQP.qpIntra = rc->constQP.qpInterP;
725             rc->constQP.qpInterB = rc->constQP.qpInterP;
726         }
727     } else if (ctx->cqp >= 0) {
728         rc->constQP.qpInterP = rc->constQP.qpInterB = rc->constQP.qpIntra = ctx->cqp;
729         if (avctx->b_quant_factor != 0.0)
730             rc->constQP.qpInterB = av_clip(ctx->cqp * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
731         if (avctx->i_quant_factor != 0.0)
732             rc->constQP.qpIntra = av_clip(ctx->cqp * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
733     }
734
735     avctx->qmin = -1;
736     avctx->qmax = -1;
737 }
738
739 static av_cold void set_vbr(AVCodecContext *avctx)
740 {
741     NvencContext *ctx = avctx->priv_data;
742     NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
743     int qp_inter_p;
744
745     if (avctx->qmin >= 0 && avctx->qmax >= 0) {
746         rc->enableMinQP = 1;
747         rc->enableMaxQP = 1;
748
749         rc->minQP.qpInterB = avctx->qmin;
750         rc->minQP.qpInterP = avctx->qmin;
751         rc->minQP.qpIntra  = avctx->qmin;
752
753         rc->maxQP.qpInterB = avctx->qmax;
754         rc->maxQP.qpInterP = avctx->qmax;
755         rc->maxQP.qpIntra = avctx->qmax;
756
757         qp_inter_p = (avctx->qmax + 3 * avctx->qmin) / 4; // biased towards Qmin
758     } else if (avctx->qmin >= 0) {
759         rc->enableMinQP = 1;
760
761         rc->minQP.qpInterB = avctx->qmin;
762         rc->minQP.qpInterP = avctx->qmin;
763         rc->minQP.qpIntra = avctx->qmin;
764
765         qp_inter_p = avctx->qmin;
766     } else {
767         qp_inter_p = 26; // default to 26
768     }
769
770     rc->enableInitialRCQP = 1;
771
772     if (ctx->init_qp_p < 0) {
773         rc->initialRCQP.qpInterP  = qp_inter_p;
774     } else {
775         rc->initialRCQP.qpInterP = ctx->init_qp_p;
776     }
777
778     if (ctx->init_qp_i < 0) {
779         if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
780             rc->initialRCQP.qpIntra = av_clip(
781                 rc->initialRCQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
782         } else {
783             rc->initialRCQP.qpIntra = rc->initialRCQP.qpInterP;
784         }
785     } else {
786         rc->initialRCQP.qpIntra = ctx->init_qp_i;
787     }
788
789     if (ctx->init_qp_b < 0) {
790         if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
791             rc->initialRCQP.qpInterB = av_clip(
792                 rc->initialRCQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
793         } else {
794             rc->initialRCQP.qpInterB = rc->initialRCQP.qpInterP;
795         }
796     } else {
797         rc->initialRCQP.qpInterB = ctx->init_qp_b;
798     }
799 }
800
801 static av_cold void set_lossless(AVCodecContext *avctx)
802 {
803     NvencContext *ctx = avctx->priv_data;
804     NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
805
806     rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
807     rc->constQP.qpInterB = 0;
808     rc->constQP.qpInterP = 0;
809     rc->constQP.qpIntra  = 0;
810
811     avctx->qmin = -1;
812     avctx->qmax = -1;
813 }
814
815 static void nvenc_override_rate_control(AVCodecContext *avctx)
816 {
817     NvencContext *ctx    = avctx->priv_data;
818     NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
819
820     switch (ctx->rc) {
821     case NV_ENC_PARAMS_RC_CONSTQP:
822         set_constqp(avctx);
823         return;
824     case NV_ENC_PARAMS_RC_VBR_MINQP:
825         if (avctx->qmin < 0) {
826             av_log(avctx, AV_LOG_WARNING,
827                    "The variable bitrate rate-control requires "
828                    "the 'qmin' option set.\n");
829             set_vbr(avctx);
830             return;
831         }
832         /* fall through */
833     case NV_ENC_PARAMS_RC_VBR_HQ:
834     case NV_ENC_PARAMS_RC_VBR:
835         set_vbr(avctx);
836         break;
837     case NV_ENC_PARAMS_RC_CBR:
838     case NV_ENC_PARAMS_RC_CBR_HQ:
839     case NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ:
840         break;
841     }
842
843     rc->rateControlMode = ctx->rc;
844 }
845
846 static av_cold int nvenc_recalc_surfaces(AVCodecContext *avctx)
847 {
848     NvencContext *ctx = avctx->priv_data;
849     // default minimum of 4 surfaces
850     // multiply by 2 for number of NVENCs on gpu (hardcode to 2)
851     // another multiply by 2 to avoid blocking next PBB group
852     int nb_surfaces = FFMAX(4, ctx->encode_config.frameIntervalP * 2 * 2);
853
854     // lookahead enabled
855     if (ctx->rc_lookahead > 0) {
856         // +1 is to account for lkd_bound calculation later
857         // +4 is to allow sufficient pipelining with lookahead
858         nb_surfaces = FFMAX(1, FFMAX(nb_surfaces, ctx->rc_lookahead + ctx->encode_config.frameIntervalP + 1 + 4));
859         if (nb_surfaces > ctx->nb_surfaces && ctx->nb_surfaces > 0)
860         {
861             av_log(avctx, AV_LOG_WARNING,
862                    "Defined rc_lookahead requires more surfaces, "
863                    "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
864         }
865         ctx->nb_surfaces = FFMAX(nb_surfaces, ctx->nb_surfaces);
866     } else {
867         if (ctx->encode_config.frameIntervalP > 1 && ctx->nb_surfaces < nb_surfaces && ctx->nb_surfaces > 0)
868         {
869             av_log(avctx, AV_LOG_WARNING,
870                    "Defined b-frame requires more surfaces, "
871                    "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
872             ctx->nb_surfaces = FFMAX(ctx->nb_surfaces, nb_surfaces);
873         }
874         else if (ctx->nb_surfaces <= 0)
875             ctx->nb_surfaces = nb_surfaces;
876         // otherwise use user specified value
877     }
878
879     ctx->nb_surfaces = FFMAX(1, FFMIN(MAX_REGISTERED_FRAMES, ctx->nb_surfaces));
880     ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
881
882     return 0;
883 }
884
885 static av_cold void nvenc_setup_rate_control(AVCodecContext *avctx)
886 {
887     NvencContext *ctx = avctx->priv_data;
888
889     if (avctx->global_quality > 0)
890         av_log(avctx, AV_LOG_WARNING, "Using global_quality with nvenc is deprecated. Use qp instead.\n");
891
892     if (ctx->cqp < 0 && avctx->global_quality > 0)
893         ctx->cqp = avctx->global_quality;
894
895     if (avctx->bit_rate > 0) {
896         ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
897     } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
898         ctx->encode_config.rcParams.maxBitRate = ctx->encode_config.rcParams.averageBitRate;
899     }
900
901     if (avctx->rc_max_rate > 0)
902         ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
903
904 #ifdef NVENC_HAVE_MULTIPASS
905     ctx->encode_config.rcParams.multiPass = ctx->multipass;
906
907     if (ctx->flags & NVENC_ONE_PASS)
908         ctx->encode_config.rcParams.multiPass = NV_ENC_MULTI_PASS_DISABLED;
909     if (ctx->flags & NVENC_TWO_PASSES || ctx->twopass)
910         ctx->encode_config.rcParams.multiPass = NV_ENC_TWO_PASS_FULL_RESOLUTION;
911
912     if (ctx->rc < 0) {
913         if (ctx->cbr) {
914             ctx->rc = NV_ENC_PARAMS_RC_CBR;
915         } else if (ctx->cqp >= 0) {
916             ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
917         } else {
918             ctx->rc = NV_ENC_PARAMS_RC_VBR;
919         }
920     }
921 #else
922     if (ctx->rc < 0) {
923         if (ctx->flags & NVENC_ONE_PASS)
924             ctx->twopass = 0;
925         if (ctx->flags & NVENC_TWO_PASSES)
926             ctx->twopass = 1;
927
928         if (ctx->twopass < 0)
929             ctx->twopass = (ctx->flags & NVENC_LOWLATENCY) != 0;
930
931         if (ctx->cbr) {
932             if (ctx->twopass) {
933                 ctx->rc = NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ;
934             } else {
935                 ctx->rc = NV_ENC_PARAMS_RC_CBR;
936             }
937         } else if (ctx->cqp >= 0) {
938             ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
939         } else if (ctx->twopass) {
940             ctx->rc = NV_ENC_PARAMS_RC_VBR_HQ;
941         } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
942             ctx->rc = NV_ENC_PARAMS_RC_VBR_MINQP;
943         }
944     }
945 #endif
946
947     if (ctx->rc >= 0 && ctx->rc & RC_MODE_DEPRECATED) {
948         av_log(avctx, AV_LOG_WARNING, "Specified rc mode is deprecated.\n");
949         av_log(avctx, AV_LOG_WARNING, "Use -rc constqp/cbr/vbr, -tune and -multipass instead.\n");
950
951         ctx->rc &= ~RC_MODE_DEPRECATED;
952     }
953
954 #ifdef NVENC_HAVE_LDKFS
955     if (ctx->ldkfs)
956          ctx->encode_config.rcParams.lowDelayKeyFrameScale = ctx->ldkfs;
957 #endif
958
959     if (ctx->flags & NVENC_LOSSLESS) {
960         set_lossless(avctx);
961     } else if (ctx->rc >= 0) {
962         nvenc_override_rate_control(avctx);
963     } else {
964         ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
965         set_vbr(avctx);
966     }
967
968     if (avctx->rc_buffer_size > 0) {
969         ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
970     } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
971         avctx->rc_buffer_size = ctx->encode_config.rcParams.vbvBufferSize = 2 * ctx->encode_config.rcParams.averageBitRate;
972     }
973
974     if (ctx->aq) {
975         ctx->encode_config.rcParams.enableAQ   = 1;
976         ctx->encode_config.rcParams.aqStrength = ctx->aq_strength;
977         av_log(avctx, AV_LOG_VERBOSE, "AQ enabled.\n");
978     }
979
980     if (ctx->temporal_aq) {
981         ctx->encode_config.rcParams.enableTemporalAQ = 1;
982         av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ enabled.\n");
983     }
984
985     if (ctx->rc_lookahead > 0) {
986         int lkd_bound = FFMIN(ctx->nb_surfaces, ctx->async_depth) -
987                         ctx->encode_config.frameIntervalP - 4;
988
989         if (lkd_bound < 0) {
990             av_log(avctx, AV_LOG_WARNING,
991                    "Lookahead not enabled. Increase buffer delay (-delay).\n");
992         } else {
993             ctx->encode_config.rcParams.enableLookahead = 1;
994             ctx->encode_config.rcParams.lookaheadDepth  = av_clip(ctx->rc_lookahead, 0, lkd_bound);
995             ctx->encode_config.rcParams.disableIadapt   = ctx->no_scenecut;
996             ctx->encode_config.rcParams.disableBadapt   = !ctx->b_adapt;
997             av_log(avctx, AV_LOG_VERBOSE,
998                    "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",
999                    ctx->encode_config.rcParams.lookaheadDepth,
1000                    ctx->encode_config.rcParams.disableIadapt ? "disabled" : "enabled",
1001                    ctx->encode_config.rcParams.disableBadapt ? "disabled" : "enabled");
1002         }
1003     }
1004
1005     if (ctx->strict_gop) {
1006         ctx->encode_config.rcParams.strictGOPTarget = 1;
1007         av_log(avctx, AV_LOG_VERBOSE, "Strict GOP target enabled.\n");
1008     }
1009
1010     if (ctx->nonref_p)
1011         ctx->encode_config.rcParams.enableNonRefP = 1;
1012
1013     if (ctx->zerolatency)
1014         ctx->encode_config.rcParams.zeroReorderDelay = 1;
1015
1016     if (ctx->quality) {
1017         //convert from float to fixed point 8.8
1018         int tmp_quality = (int)(ctx->quality * 256.0f);
1019         ctx->encode_config.rcParams.targetQuality = (uint8_t)(tmp_quality >> 8);
1020         ctx->encode_config.rcParams.targetQualityLSB = (uint8_t)(tmp_quality & 0xff);
1021
1022         av_log(avctx, AV_LOG_VERBOSE, "CQ(%d) mode enabled.\n", tmp_quality);
1023
1024         //CQ mode shall discard avg bitrate & honor max bitrate;
1025         ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate = 0;
1026         ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
1027     }
1028 }
1029
1030 static av_cold int nvenc_setup_h264_config(AVCodecContext *avctx)
1031 {
1032     NvencContext *ctx                      = avctx->priv_data;
1033     NV_ENC_CONFIG *cc                      = &ctx->encode_config;
1034     NV_ENC_CONFIG_H264 *h264               = &cc->encodeCodecConfig.h264Config;
1035     NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
1036
1037     vui->colourMatrix = avctx->colorspace;
1038     vui->colourPrimaries = avctx->color_primaries;
1039     vui->transferCharacteristics = avctx->color_trc;
1040     vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
1041         || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
1042
1043     vui->colourDescriptionPresentFlag =
1044         (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
1045
1046     vui->videoSignalTypePresentFlag =
1047         (vui->colourDescriptionPresentFlag
1048         || vui->videoFormat != 5
1049         || vui->videoFullRangeFlag != 0);
1050
1051     h264->sliceMode = 3;
1052     h264->sliceModeData = 1;
1053
1054     h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
1055     h264->repeatSPSPPS  = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
1056     h264->outputAUD     = ctx->aud;
1057
1058     if (ctx->dpb_size >= 0) {
1059         /* 0 means "let the hardware decide" */
1060         h264->maxNumRefFrames = ctx->dpb_size;
1061     }
1062     if (avctx->gop_size >= 0) {
1063         h264->idrPeriod = cc->gopLength;
1064     }
1065
1066     if (IS_CBR(cc->rcParams.rateControlMode)) {
1067         h264->outputBufferingPeriodSEI = 1;
1068     }
1069
1070     h264->outputPictureTimingSEI = 1;
1071
1072     if (cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ ||
1073         cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_HQ ||
1074         cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_VBR_HQ) {
1075         h264->adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
1076         h264->fmoMode = NV_ENC_H264_FMO_DISABLE;
1077     }
1078
1079     if (ctx->flags & NVENC_LOSSLESS) {
1080         h264->qpPrimeYZeroTransformBypassFlag = 1;
1081     } else {
1082         switch(ctx->profile) {
1083         case NV_ENC_H264_PROFILE_BASELINE:
1084             cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
1085             avctx->profile = FF_PROFILE_H264_BASELINE;
1086             break;
1087         case NV_ENC_H264_PROFILE_MAIN:
1088             cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
1089             avctx->profile = FF_PROFILE_H264_MAIN;
1090             break;
1091         case NV_ENC_H264_PROFILE_HIGH:
1092             cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
1093             avctx->profile = FF_PROFILE_H264_HIGH;
1094             break;
1095         case NV_ENC_H264_PROFILE_HIGH_444P:
1096             cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1097             avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
1098             break;
1099         }
1100     }
1101
1102     // force setting profile as high444p if input is AV_PIX_FMT_YUV444P
1103     if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P) {
1104         cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1105         avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
1106     }
1107
1108     h264->chromaFormatIDC = avctx->profile == FF_PROFILE_H264_HIGH_444_PREDICTIVE ? 3 : 1;
1109
1110     h264->level = ctx->level;
1111
1112     if (ctx->coder >= 0)
1113         h264->entropyCodingMode = ctx->coder;
1114
1115 #ifdef NVENC_HAVE_BFRAME_REF_MODE
1116     h264->useBFramesAsRef = ctx->b_ref_mode;
1117 #endif
1118
1119 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
1120     h264->numRefL0 = avctx->refs;
1121     h264->numRefL1 = avctx->refs;
1122 #endif
1123
1124     return 0;
1125 }
1126
1127 static av_cold int nvenc_setup_hevc_config(AVCodecContext *avctx)
1128 {
1129     NvencContext *ctx                      = avctx->priv_data;
1130     NV_ENC_CONFIG *cc                      = &ctx->encode_config;
1131     NV_ENC_CONFIG_HEVC *hevc               = &cc->encodeCodecConfig.hevcConfig;
1132     NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
1133
1134     vui->colourMatrix = avctx->colorspace;
1135     vui->colourPrimaries = avctx->color_primaries;
1136     vui->transferCharacteristics = avctx->color_trc;
1137     vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
1138         || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
1139
1140     vui->colourDescriptionPresentFlag =
1141         (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
1142
1143     vui->videoSignalTypePresentFlag =
1144         (vui->colourDescriptionPresentFlag
1145         || vui->videoFormat != 5
1146         || vui->videoFullRangeFlag != 0);
1147
1148     hevc->sliceMode = 3;
1149     hevc->sliceModeData = 1;
1150
1151     hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
1152     hevc->repeatSPSPPS  = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
1153     hevc->outputAUD     = ctx->aud;
1154
1155     if (ctx->dpb_size >= 0) {
1156         /* 0 means "let the hardware decide" */
1157         hevc->maxNumRefFramesInDPB = ctx->dpb_size;
1158     }
1159     if (avctx->gop_size >= 0) {
1160         hevc->idrPeriod = cc->gopLength;
1161     }
1162
1163     if (IS_CBR(cc->rcParams.rateControlMode)) {
1164         hevc->outputBufferingPeriodSEI = 1;
1165     }
1166
1167     hevc->outputPictureTimingSEI = 1;
1168
1169     switch (ctx->profile) {
1170     case NV_ENC_HEVC_PROFILE_MAIN:
1171         cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
1172         avctx->profile  = FF_PROFILE_HEVC_MAIN;
1173         break;
1174     case NV_ENC_HEVC_PROFILE_MAIN_10:
1175         cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1176         avctx->profile  = FF_PROFILE_HEVC_MAIN_10;
1177         break;
1178     case NV_ENC_HEVC_PROFILE_REXT:
1179         cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1180         avctx->profile  = FF_PROFILE_HEVC_REXT;
1181         break;
1182     }
1183
1184     // force setting profile as main10 if input is 10 bit
1185     if (IS_10BIT(ctx->data_pix_fmt)) {
1186         cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1187         avctx->profile = FF_PROFILE_HEVC_MAIN_10;
1188     }
1189
1190     // force setting profile as rext if input is yuv444
1191     if (IS_YUV444(ctx->data_pix_fmt)) {
1192         cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1193         avctx->profile = FF_PROFILE_HEVC_REXT;
1194     }
1195
1196     hevc->chromaFormatIDC = IS_YUV444(ctx->data_pix_fmt) ? 3 : 1;
1197
1198     hevc->pixelBitDepthMinus8 = IS_10BIT(ctx->data_pix_fmt) ? 2 : 0;
1199
1200     hevc->level = ctx->level;
1201
1202     hevc->tier = ctx->tier;
1203
1204 #ifdef NVENC_HAVE_HEVC_BFRAME_REF_MODE
1205     hevc->useBFramesAsRef = ctx->b_ref_mode;
1206 #endif
1207
1208 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
1209     hevc->numRefL0 = avctx->refs;
1210     hevc->numRefL1 = avctx->refs;
1211 #endif
1212
1213     return 0;
1214 }
1215
1216 static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx)
1217 {
1218     switch (avctx->codec->id) {
1219     case AV_CODEC_ID_H264:
1220         return nvenc_setup_h264_config(avctx);
1221     case AV_CODEC_ID_HEVC:
1222         return nvenc_setup_hevc_config(avctx);
1223     /* Earlier switch/case will return if unknown codec is passed. */
1224     }
1225
1226     return 0;
1227 }
1228
1229 static void compute_dar(AVCodecContext *avctx, int *dw, int *dh) {
1230     int sw, sh;
1231
1232     sw = avctx->width;
1233     sh = avctx->height;
1234
1235     if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0) {
1236         sw *= avctx->sample_aspect_ratio.num;
1237         sh *= avctx->sample_aspect_ratio.den;
1238     }
1239
1240     av_reduce(dw, dh, sw, sh, 1024 * 1024);
1241 }
1242
1243 static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
1244 {
1245     NvencContext *ctx = avctx->priv_data;
1246     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1247     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1248
1249     NV_ENC_PRESET_CONFIG preset_config = { 0 };
1250     NVENCSTATUS nv_status = NV_ENC_SUCCESS;
1251     AVCPBProperties *cpb_props;
1252     int res = 0;
1253     int dw, dh;
1254
1255     ctx->encode_config.version = NV_ENC_CONFIG_VER;
1256     ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
1257
1258     ctx->init_encode_params.encodeHeight = avctx->height;
1259     ctx->init_encode_params.encodeWidth = avctx->width;
1260
1261     ctx->init_encode_params.encodeConfig = &ctx->encode_config;
1262
1263     nvenc_map_preset(ctx);
1264
1265     if (ctx->flags & NVENC_DEPRECATED_PRESET)
1266         av_log(avctx, AV_LOG_WARNING, "The selected preset is deprecated. Use p1 to p7 + -tune or fast/medium/slow.\n");
1267
1268     preset_config.version = NV_ENC_PRESET_CONFIG_VER;
1269     preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
1270
1271     if (IS_SDK10_PRESET(ctx->preset)) {
1272 #ifdef NVENC_HAVE_NEW_PRESETS
1273         ctx->init_encode_params.tuningInfo = ctx->tuning_info;
1274
1275         if (ctx->flags & NVENC_LOWLATENCY)
1276             ctx->init_encode_params.tuningInfo = NV_ENC_TUNING_INFO_LOW_LATENCY;
1277
1278         nv_status = p_nvenc->nvEncGetEncodePresetConfigEx(ctx->nvencoder,
1279             ctx->init_encode_params.encodeGUID,
1280             ctx->init_encode_params.presetGUID,
1281             ctx->init_encode_params.tuningInfo,
1282             &preset_config);
1283 #endif
1284     } else {
1285 #ifdef NVENC_HAVE_NEW_PRESETS
1286         // Turn off tuning info parameter if older presets are on
1287         ctx->init_encode_params.tuningInfo = 0;
1288 #endif
1289
1290         nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder,
1291             ctx->init_encode_params.encodeGUID,
1292             ctx->init_encode_params.presetGUID,
1293             &preset_config);
1294     }
1295     if (nv_status != NV_ENC_SUCCESS)
1296         return nvenc_print_error(avctx, nv_status, "Cannot get the preset configuration");
1297
1298     memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
1299
1300     ctx->encode_config.version = NV_ENC_CONFIG_VER;
1301
1302     compute_dar(avctx, &dw, &dh);
1303     ctx->init_encode_params.darHeight = dh;
1304     ctx->init_encode_params.darWidth = dw;
1305
1306     if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {
1307         ctx->init_encode_params.frameRateNum = avctx->framerate.num;
1308         ctx->init_encode_params.frameRateDen = avctx->framerate.den;
1309     } else {
1310         ctx->init_encode_params.frameRateNum = avctx->time_base.den;
1311         ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
1312     }
1313
1314     ctx->init_encode_params.enableEncodeAsync = 0;
1315     ctx->init_encode_params.enablePTD = 1;
1316
1317 #ifdef NVENC_HAVE_NEW_PRESETS
1318     /* If lookahead isn't set from CLI, use value from preset.
1319      * P6 & P7 presets may enable lookahead for better quality.
1320      * */
1321     if (ctx->rc_lookahead == 0 && ctx->encode_config.rcParams.enableLookahead)
1322         ctx->rc_lookahead = ctx->encode_config.rcParams.lookaheadDepth;
1323
1324     if (ctx->init_encode_params.tuningInfo == NV_ENC_TUNING_INFO_LOSSLESS)
1325         ctx->flags |= NVENC_LOSSLESS;
1326 #endif
1327
1328     if (ctx->weighted_pred == 1)
1329         ctx->init_encode_params.enableWeightedPrediction = 1;
1330
1331     if (ctx->bluray_compat) {
1332         ctx->aud = 1;
1333         ctx->dpb_size = FFMIN(FFMAX(avctx->refs, 0), 6);
1334         avctx->max_b_frames = FFMIN(avctx->max_b_frames, 3);
1335         switch (avctx->codec->id) {
1336         case AV_CODEC_ID_H264:
1337             /* maximum level depends on used resolution */
1338             break;
1339         case AV_CODEC_ID_HEVC:
1340             ctx->level = NV_ENC_LEVEL_HEVC_51;
1341             ctx->tier = NV_ENC_TIER_HEVC_HIGH;
1342             break;
1343         }
1344     }
1345
1346     if (avctx->gop_size > 0) {
1347         if (avctx->max_b_frames >= 0) {
1348             /* 0 is intra-only, 1 is I/P only, 2 is one B-Frame, 3 two B-frames, and so on. */
1349             ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
1350         }
1351
1352         ctx->encode_config.gopLength = avctx->gop_size;
1353     } else if (avctx->gop_size == 0) {
1354         ctx->encode_config.frameIntervalP = 0;
1355         ctx->encode_config.gopLength = 1;
1356     }
1357
1358     nvenc_recalc_surfaces(avctx);
1359
1360     nvenc_setup_rate_control(avctx);
1361
1362     if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1363         ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
1364     } else {
1365         ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
1366     }
1367
1368     res = nvenc_setup_codec_config(avctx);
1369     if (res)
1370         return res;
1371
1372     res = nvenc_push_context(avctx);
1373     if (res < 0)
1374         return res;
1375
1376     nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
1377     if (nv_status != NV_ENC_SUCCESS) {
1378         nvenc_pop_context(avctx);
1379         return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
1380     }
1381
1382 #ifdef NVENC_HAVE_CUSTREAM_PTR
1383     if (ctx->cu_context) {
1384         nv_status = p_nvenc->nvEncSetIOCudaStreams(ctx->nvencoder, &ctx->cu_stream, &ctx->cu_stream);
1385         if (nv_status != NV_ENC_SUCCESS) {
1386             nvenc_pop_context(avctx);
1387             return nvenc_print_error(avctx, nv_status, "SetIOCudaStreams failed");
1388         }
1389     }
1390 #endif
1391
1392     res = nvenc_pop_context(avctx);
1393     if (res < 0)
1394         return res;
1395
1396     if (ctx->encode_config.frameIntervalP > 1)
1397         avctx->has_b_frames = 2;
1398
1399     if (ctx->encode_config.rcParams.averageBitRate > 0)
1400         avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
1401
1402     cpb_props = ff_add_cpb_side_data(avctx);
1403     if (!cpb_props)
1404         return AVERROR(ENOMEM);
1405     cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
1406     cpb_props->avg_bitrate = avctx->bit_rate;
1407     cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
1408
1409     return 0;
1410 }
1411
1412 static NV_ENC_BUFFER_FORMAT nvenc_map_buffer_format(enum AVPixelFormat pix_fmt)
1413 {
1414     switch (pix_fmt) {
1415     case AV_PIX_FMT_YUV420P:
1416         return NV_ENC_BUFFER_FORMAT_YV12_PL;
1417     case AV_PIX_FMT_NV12:
1418         return NV_ENC_BUFFER_FORMAT_NV12_PL;
1419     case AV_PIX_FMT_P010:
1420     case AV_PIX_FMT_P016:
1421         return NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1422     case AV_PIX_FMT_YUV444P:
1423         return NV_ENC_BUFFER_FORMAT_YUV444_PL;
1424     case AV_PIX_FMT_YUV444P16:
1425         return NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1426     case AV_PIX_FMT_0RGB32:
1427         return NV_ENC_BUFFER_FORMAT_ARGB;
1428     case AV_PIX_FMT_0BGR32:
1429         return NV_ENC_BUFFER_FORMAT_ABGR;
1430     default:
1431         return NV_ENC_BUFFER_FORMAT_UNDEFINED;
1432     }
1433 }
1434
1435 static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
1436 {
1437     NvencContext *ctx = avctx->priv_data;
1438     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1439     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1440     NvencSurface* tmp_surface = &ctx->surfaces[idx];
1441
1442     NVENCSTATUS nv_status;
1443     NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
1444     allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1445
1446     if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1447         ctx->surfaces[idx].in_ref = av_frame_alloc();
1448         if (!ctx->surfaces[idx].in_ref)
1449             return AVERROR(ENOMEM);
1450     } else {
1451         NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1452
1453         ctx->surfaces[idx].format = nvenc_map_buffer_format(ctx->data_pix_fmt);
1454         if (ctx->surfaces[idx].format == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1455             av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1456                    av_get_pix_fmt_name(ctx->data_pix_fmt));
1457             return AVERROR(EINVAL);
1458         }
1459
1460         allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1461         allocSurf.width = avctx->width;
1462         allocSurf.height = avctx->height;
1463         allocSurf.bufferFmt = ctx->surfaces[idx].format;
1464
1465         nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
1466         if (nv_status != NV_ENC_SUCCESS) {
1467             return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
1468         }
1469
1470         ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
1471         ctx->surfaces[idx].width = allocSurf.width;
1472         ctx->surfaces[idx].height = allocSurf.height;
1473     }
1474
1475     nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
1476     if (nv_status != NV_ENC_SUCCESS) {
1477         int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
1478         if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
1479             p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
1480         av_frame_free(&ctx->surfaces[idx].in_ref);
1481         return err;
1482     }
1483
1484     ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1485
1486     av_fifo_generic_write(ctx->unused_surface_queue, &tmp_surface, sizeof(tmp_surface), NULL);
1487
1488     return 0;
1489 }
1490
1491 static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx)
1492 {
1493     NvencContext *ctx = avctx->priv_data;
1494     int i, res = 0, res2;
1495
1496     ctx->surfaces = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->surfaces));
1497     if (!ctx->surfaces)
1498         return AVERROR(ENOMEM);
1499
1500     ctx->timestamp_list = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
1501     if (!ctx->timestamp_list)
1502         return AVERROR(ENOMEM);
1503
1504     ctx->unused_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1505     if (!ctx->unused_surface_queue)
1506         return AVERROR(ENOMEM);
1507
1508     ctx->output_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1509     if (!ctx->output_surface_queue)
1510         return AVERROR(ENOMEM);
1511     ctx->output_surface_ready_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1512     if (!ctx->output_surface_ready_queue)
1513         return AVERROR(ENOMEM);
1514
1515     res = nvenc_push_context(avctx);
1516     if (res < 0)
1517         return res;
1518
1519     for (i = 0; i < ctx->nb_surfaces; i++) {
1520         if ((res = nvenc_alloc_surface(avctx, i)) < 0)
1521             goto fail;
1522     }
1523
1524 fail:
1525     res2 = nvenc_pop_context(avctx);
1526     if (res2 < 0)
1527         return res2;
1528
1529     return res;
1530 }
1531
1532 static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
1533 {
1534     NvencContext *ctx = avctx->priv_data;
1535     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1536     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1537
1538     NVENCSTATUS nv_status;
1539     uint32_t outSize = 0;
1540     char tmpHeader[256];
1541     NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1542     payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1543
1544     payload.spsppsBuffer = tmpHeader;
1545     payload.inBufferSize = sizeof(tmpHeader);
1546     payload.outSPSPPSPayloadSize = &outSize;
1547
1548     nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
1549     if (nv_status != NV_ENC_SUCCESS) {
1550         return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
1551     }
1552
1553     avctx->extradata_size = outSize;
1554     avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
1555
1556     if (!avctx->extradata) {
1557         return AVERROR(ENOMEM);
1558     }
1559
1560     memcpy(avctx->extradata, tmpHeader, outSize);
1561
1562     return 0;
1563 }
1564
1565 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
1566 {
1567     NvencContext *ctx               = avctx->priv_data;
1568     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1569     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1570     int i, res;
1571
1572     /* the encoder has to be flushed before it can be closed */
1573     if (ctx->nvencoder) {
1574         NV_ENC_PIC_PARAMS params        = { .version        = NV_ENC_PIC_PARAMS_VER,
1575                                             .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
1576
1577         res = nvenc_push_context(avctx);
1578         if (res < 0)
1579             return res;
1580
1581         p_nvenc->nvEncEncodePicture(ctx->nvencoder, &params);
1582     }
1583
1584     av_fifo_freep(&ctx->timestamp_list);
1585     av_fifo_freep(&ctx->output_surface_ready_queue);
1586     av_fifo_freep(&ctx->output_surface_queue);
1587     av_fifo_freep(&ctx->unused_surface_queue);
1588
1589     if (ctx->surfaces && (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11)) {
1590         for (i = 0; i < ctx->nb_registered_frames; i++) {
1591             if (ctx->registered_frames[i].mapped)
1592                 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[i].in_map.mappedResource);
1593             if (ctx->registered_frames[i].regptr)
1594                 p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1595         }
1596         ctx->nb_registered_frames = 0;
1597     }
1598
1599     if (ctx->surfaces) {
1600         for (i = 0; i < ctx->nb_surfaces; ++i) {
1601             if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
1602                 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
1603             av_frame_free(&ctx->surfaces[i].in_ref);
1604             p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
1605         }
1606     }
1607     av_freep(&ctx->surfaces);
1608     ctx->nb_surfaces = 0;
1609
1610     av_frame_free(&ctx->frame);
1611
1612     if (ctx->nvencoder) {
1613         p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1614
1615         res = nvenc_pop_context(avctx);
1616         if (res < 0)
1617             return res;
1618     }
1619     ctx->nvencoder = NULL;
1620
1621     if (ctx->cu_context_internal)
1622         CHECK_CU(dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal));
1623     ctx->cu_context = ctx->cu_context_internal = NULL;
1624
1625 #if CONFIG_D3D11VA
1626     if (ctx->d3d11_device) {
1627         ID3D11Device_Release(ctx->d3d11_device);
1628         ctx->d3d11_device = NULL;
1629     }
1630 #endif
1631
1632     nvenc_free_functions(&dl_fn->nvenc_dl);
1633     cuda_free_functions(&dl_fn->cuda_dl);
1634
1635     dl_fn->nvenc_device_count = 0;
1636
1637     av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
1638
1639     return 0;
1640 }
1641
1642 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
1643 {
1644     NvencContext *ctx = avctx->priv_data;
1645     int ret;
1646
1647     if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1648         AVHWFramesContext *frames_ctx;
1649         if (!avctx->hw_frames_ctx) {
1650             av_log(avctx, AV_LOG_ERROR,
1651                    "hw_frames_ctx must be set when using GPU frames as input\n");
1652             return AVERROR(EINVAL);
1653         }
1654         frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1655         if (frames_ctx->format != avctx->pix_fmt) {
1656             av_log(avctx, AV_LOG_ERROR,
1657                    "hw_frames_ctx must match the GPU frame type\n");
1658             return AVERROR(EINVAL);
1659         }
1660         ctx->data_pix_fmt = frames_ctx->sw_format;
1661     } else {
1662         ctx->data_pix_fmt = avctx->pix_fmt;
1663     }
1664
1665     ctx->frame = av_frame_alloc();
1666     if (!ctx->frame)
1667         return AVERROR(ENOMEM);
1668
1669     if ((ret = nvenc_load_libraries(avctx)) < 0)
1670         return ret;
1671
1672     if ((ret = nvenc_setup_device(avctx)) < 0)
1673         return ret;
1674
1675     if ((ret = nvenc_setup_encoder(avctx)) < 0)
1676         return ret;
1677
1678     if ((ret = nvenc_setup_surfaces(avctx)) < 0)
1679         return ret;
1680
1681     if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1682         if ((ret = nvenc_setup_extradata(avctx)) < 0)
1683             return ret;
1684     }
1685
1686     return 0;
1687 }
1688
1689 static NvencSurface *get_free_frame(NvencContext *ctx)
1690 {
1691     NvencSurface *tmp_surf;
1692
1693     if (!(av_fifo_size(ctx->unused_surface_queue) > 0))
1694         // queue empty
1695         return NULL;
1696
1697     av_fifo_generic_read(ctx->unused_surface_queue, &tmp_surf, sizeof(tmp_surf), NULL);
1698     return tmp_surf;
1699 }
1700
1701 static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *nv_surface,
1702             NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params, const AVFrame *frame)
1703 {
1704     int dst_linesize[4] = {
1705         lock_buffer_params->pitch,
1706         lock_buffer_params->pitch,
1707         lock_buffer_params->pitch,
1708         lock_buffer_params->pitch
1709     };
1710     uint8_t *dst_data[4];
1711     int ret;
1712
1713     if (frame->format == AV_PIX_FMT_YUV420P)
1714         dst_linesize[1] = dst_linesize[2] >>= 1;
1715
1716     ret = av_image_fill_pointers(dst_data, frame->format, nv_surface->height,
1717                                  lock_buffer_params->bufferDataPtr, dst_linesize);
1718     if (ret < 0)
1719         return ret;
1720
1721     if (frame->format == AV_PIX_FMT_YUV420P)
1722         FFSWAP(uint8_t*, dst_data[1], dst_data[2]);
1723
1724     av_image_copy(dst_data, dst_linesize,
1725                   (const uint8_t**)frame->data, frame->linesize, frame->format,
1726                   avctx->width, avctx->height);
1727
1728     return 0;
1729 }
1730
1731 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1732 {
1733     NvencContext *ctx = avctx->priv_data;
1734     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1735     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1736     NVENCSTATUS nv_status;
1737
1738     int i, first_round;
1739
1740     if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1741         for (first_round = 1; first_round >= 0; first_round--) {
1742             for (i = 0; i < ctx->nb_registered_frames; i++) {
1743                 if (!ctx->registered_frames[i].mapped) {
1744                     if (ctx->registered_frames[i].regptr) {
1745                         if (first_round)
1746                             continue;
1747                         nv_status = p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1748                         if (nv_status != NV_ENC_SUCCESS)
1749                             return nvenc_print_error(avctx, nv_status, "Failed unregistering unused input resource");
1750                         ctx->registered_frames[i].ptr = NULL;
1751                         ctx->registered_frames[i].regptr = NULL;
1752                     }
1753                     return i;
1754                 }
1755             }
1756         }
1757     } else {
1758         return ctx->nb_registered_frames++;
1759     }
1760
1761     av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1762     return AVERROR(ENOMEM);
1763 }
1764
1765 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1766 {
1767     NvencContext *ctx = avctx->priv_data;
1768     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1769     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1770
1771     AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frame->hw_frames_ctx->data;
1772     NV_ENC_REGISTER_RESOURCE reg;
1773     int i, idx, ret;
1774
1775     for (i = 0; i < ctx->nb_registered_frames; i++) {
1776         if (avctx->pix_fmt == AV_PIX_FMT_CUDA && ctx->registered_frames[i].ptr == frame->data[0])
1777             return i;
1778         else if (avctx->pix_fmt == AV_PIX_FMT_D3D11 && ctx->registered_frames[i].ptr == frame->data[0] && ctx->registered_frames[i].ptr_index == (intptr_t)frame->data[1])
1779             return i;
1780     }
1781
1782     idx = nvenc_find_free_reg_resource(avctx);
1783     if (idx < 0)
1784         return idx;
1785
1786     reg.version            = NV_ENC_REGISTER_RESOURCE_VER;
1787     reg.width              = frames_ctx->width;
1788     reg.height             = frames_ctx->height;
1789     reg.pitch              = frame->linesize[0];
1790     reg.resourceToRegister = frame->data[0];
1791
1792     if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1793         reg.resourceType   = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1794     }
1795     else if (avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1796         reg.resourceType     = NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX;
1797         reg.subResourceIndex = (intptr_t)frame->data[1];
1798     }
1799
1800     reg.bufferFormat       = nvenc_map_buffer_format(frames_ctx->sw_format);
1801     if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1802         av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1803                av_get_pix_fmt_name(frames_ctx->sw_format));
1804         return AVERROR(EINVAL);
1805     }
1806
1807     ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, &reg);
1808     if (ret != NV_ENC_SUCCESS) {
1809         nvenc_print_error(avctx, ret, "Error registering an input resource");
1810         return AVERROR_UNKNOWN;
1811     }
1812
1813     ctx->registered_frames[idx].ptr       = frame->data[0];
1814     ctx->registered_frames[idx].ptr_index = reg.subResourceIndex;
1815     ctx->registered_frames[idx].regptr    = reg.registeredResource;
1816     return idx;
1817 }
1818
1819 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1820                                       NvencSurface *nvenc_frame)
1821 {
1822     NvencContext *ctx = avctx->priv_data;
1823     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1824     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1825
1826     int res;
1827     NVENCSTATUS nv_status;
1828
1829     if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1830         int reg_idx = nvenc_register_frame(avctx, frame);
1831         if (reg_idx < 0) {
1832             av_log(avctx, AV_LOG_ERROR, "Could not register an input HW frame\n");
1833             return reg_idx;
1834         }
1835
1836         res = av_frame_ref(nvenc_frame->in_ref, frame);
1837         if (res < 0)
1838             return res;
1839
1840         if (!ctx->registered_frames[reg_idx].mapped) {
1841             ctx->registered_frames[reg_idx].in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1842             ctx->registered_frames[reg_idx].in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1843             nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &ctx->registered_frames[reg_idx].in_map);
1844             if (nv_status != NV_ENC_SUCCESS) {
1845                 av_frame_unref(nvenc_frame->in_ref);
1846                 return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
1847             }
1848         }
1849
1850         ctx->registered_frames[reg_idx].mapped += 1;
1851
1852         nvenc_frame->reg_idx                   = reg_idx;
1853         nvenc_frame->input_surface             = ctx->registered_frames[reg_idx].in_map.mappedResource;
1854         nvenc_frame->format                    = ctx->registered_frames[reg_idx].in_map.mappedBufferFmt;
1855         nvenc_frame->pitch                     = frame->linesize[0];
1856
1857         return 0;
1858     } else {
1859         NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1860
1861         lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1862         lockBufferParams.inputBuffer = nvenc_frame->input_surface;
1863
1864         nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
1865         if (nv_status != NV_ENC_SUCCESS) {
1866             return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
1867         }
1868
1869         nvenc_frame->pitch = lockBufferParams.pitch;
1870         res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
1871
1872         nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
1873         if (nv_status != NV_ENC_SUCCESS) {
1874             return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
1875         }
1876
1877         return res;
1878     }
1879 }
1880
1881 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1882                                             NV_ENC_PIC_PARAMS *params,
1883                                             NV_ENC_SEI_PAYLOAD *sei_data,
1884                                             int sei_count)
1885 {
1886     NvencContext *ctx = avctx->priv_data;
1887
1888     switch (avctx->codec->id) {
1889     case AV_CODEC_ID_H264:
1890         params->codecPicParams.h264PicParams.sliceMode =
1891             ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1892         params->codecPicParams.h264PicParams.sliceModeData =
1893             ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1894         if (sei_count > 0) {
1895             params->codecPicParams.h264PicParams.seiPayloadArray = sei_data;
1896             params->codecPicParams.h264PicParams.seiPayloadArrayCnt = sei_count;
1897         }
1898
1899       break;
1900     case AV_CODEC_ID_HEVC:
1901         params->codecPicParams.hevcPicParams.sliceMode =
1902             ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1903         params->codecPicParams.hevcPicParams.sliceModeData =
1904             ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1905         if (sei_count > 0) {
1906             params->codecPicParams.hevcPicParams.seiPayloadArray = sei_data;
1907             params->codecPicParams.hevcPicParams.seiPayloadArrayCnt = sei_count;
1908         }
1909
1910         break;
1911     }
1912 }
1913
1914 static inline void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
1915 {
1916     av_fifo_generic_write(queue, &timestamp, sizeof(timestamp), NULL);
1917 }
1918
1919 static inline int64_t timestamp_queue_dequeue(AVFifoBuffer* queue)
1920 {
1921     int64_t timestamp = AV_NOPTS_VALUE;
1922     if (av_fifo_size(queue) > 0)
1923         av_fifo_generic_read(queue, &timestamp, sizeof(timestamp), NULL);
1924
1925     return timestamp;
1926 }
1927
1928 static int nvenc_set_timestamp(AVCodecContext *avctx,
1929                                NV_ENC_LOCK_BITSTREAM *params,
1930                                AVPacket *pkt)
1931 {
1932     NvencContext *ctx = avctx->priv_data;
1933
1934     pkt->pts = params->outputTimeStamp;
1935     pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
1936
1937     pkt->dts -= FFMAX(avctx->max_b_frames, 0) * FFMIN(avctx->ticks_per_frame, 1);
1938
1939     return 0;
1940 }
1941
1942 static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
1943 {
1944     NvencContext *ctx = avctx->priv_data;
1945     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1946     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1947
1948     uint32_t slice_mode_data;
1949     uint32_t *slice_offsets = NULL;
1950     NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1951     NVENCSTATUS nv_status;
1952     int res = 0;
1953
1954     enum AVPictureType pict_type;
1955
1956     switch (avctx->codec->id) {
1957     case AV_CODEC_ID_H264:
1958       slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1959       break;
1960     case AV_CODEC_ID_H265:
1961       slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1962       break;
1963     default:
1964       av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
1965       res = AVERROR(EINVAL);
1966       goto error;
1967     }
1968     slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
1969
1970     if (!slice_offsets) {
1971         res = AVERROR(ENOMEM);
1972         goto error;
1973     }
1974
1975     lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1976
1977     lock_params.doNotWait = 0;
1978     lock_params.outputBitstream = tmpoutsurf->output_surface;
1979     lock_params.sliceOffsets = slice_offsets;
1980
1981     nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
1982     if (nv_status != NV_ENC_SUCCESS) {
1983         res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
1984         goto error;
1985     }
1986
1987     res = av_new_packet(pkt, lock_params.bitstreamSizeInBytes);
1988
1989     if (res < 0) {
1990         p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1991         goto error;
1992     }
1993
1994     memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1995
1996     nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1997     if (nv_status != NV_ENC_SUCCESS) {
1998         res = nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
1999         goto error;
2000     }
2001
2002
2003     if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
2004         ctx->registered_frames[tmpoutsurf->reg_idx].mapped -= 1;
2005         if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped == 0) {
2006             nv_status = p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[tmpoutsurf->reg_idx].in_map.mappedResource);
2007             if (nv_status != NV_ENC_SUCCESS) {
2008                 res = nvenc_print_error(avctx, nv_status, "Failed unmapping input resource");
2009                 goto error;
2010             }
2011         } else if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped < 0) {
2012             res = AVERROR_BUG;
2013             goto error;
2014         }
2015
2016         av_frame_unref(tmpoutsurf->in_ref);
2017
2018         tmpoutsurf->input_surface = NULL;
2019     }
2020
2021     switch (lock_params.pictureType) {
2022     case NV_ENC_PIC_TYPE_IDR:
2023         pkt->flags |= AV_PKT_FLAG_KEY;
2024     case NV_ENC_PIC_TYPE_I:
2025         pict_type = AV_PICTURE_TYPE_I;
2026         break;
2027     case NV_ENC_PIC_TYPE_P:
2028         pict_type = AV_PICTURE_TYPE_P;
2029         break;
2030     case NV_ENC_PIC_TYPE_B:
2031         pict_type = AV_PICTURE_TYPE_B;
2032         break;
2033     case NV_ENC_PIC_TYPE_BI:
2034         pict_type = AV_PICTURE_TYPE_BI;
2035         break;
2036     default:
2037         av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
2038         av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
2039         res = AVERROR_EXTERNAL;
2040         goto error;
2041     }
2042
2043 #if FF_API_CODED_FRAME
2044 FF_DISABLE_DEPRECATION_WARNINGS
2045     avctx->coded_frame->pict_type = pict_type;
2046 FF_ENABLE_DEPRECATION_WARNINGS
2047 #endif
2048
2049     ff_side_data_set_encoder_stats(pkt,
2050         (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
2051
2052     res = nvenc_set_timestamp(avctx, &lock_params, pkt);
2053     if (res < 0)
2054         goto error2;
2055
2056     av_free(slice_offsets);
2057
2058     return 0;
2059
2060 error:
2061     timestamp_queue_dequeue(ctx->timestamp_list);
2062
2063 error2:
2064     av_free(slice_offsets);
2065
2066     return res;
2067 }
2068
2069 static int output_ready(AVCodecContext *avctx, int flush)
2070 {
2071     NvencContext *ctx = avctx->priv_data;
2072     int nb_ready, nb_pending;
2073
2074     nb_ready   = av_fifo_size(ctx->output_surface_ready_queue)   / sizeof(NvencSurface*);
2075     nb_pending = av_fifo_size(ctx->output_surface_queue)         / sizeof(NvencSurface*);
2076     if (flush)
2077         return nb_ready > 0;
2078     return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
2079 }
2080
2081 static void reconfig_encoder(AVCodecContext *avctx, const AVFrame *frame)
2082 {
2083     NvencContext *ctx = avctx->priv_data;
2084     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
2085     NVENCSTATUS ret;
2086
2087     NV_ENC_RECONFIGURE_PARAMS params = { 0 };
2088     int needs_reconfig = 0;
2089     int needs_encode_config = 0;
2090     int reconfig_bitrate = 0, reconfig_dar = 0;
2091     int dw, dh;
2092
2093     params.version = NV_ENC_RECONFIGURE_PARAMS_VER;
2094     params.reInitEncodeParams = ctx->init_encode_params;
2095
2096     compute_dar(avctx, &dw, &dh);
2097     if (dw != ctx->init_encode_params.darWidth || dh != ctx->init_encode_params.darHeight) {
2098         av_log(avctx, AV_LOG_VERBOSE,
2099                "aspect ratio change (DAR): %d:%d -> %d:%d\n",
2100                ctx->init_encode_params.darWidth,
2101                ctx->init_encode_params.darHeight, dw, dh);
2102
2103         params.reInitEncodeParams.darHeight = dh;
2104         params.reInitEncodeParams.darWidth = dw;
2105
2106         needs_reconfig = 1;
2107         reconfig_dar = 1;
2108     }
2109
2110     if (ctx->rc != NV_ENC_PARAMS_RC_CONSTQP && ctx->support_dyn_bitrate) {
2111         if (avctx->bit_rate > 0 && params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate != avctx->bit_rate) {
2112             av_log(avctx, AV_LOG_VERBOSE,
2113                    "avg bitrate change: %d -> %d\n",
2114                    params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate,
2115                    (uint32_t)avctx->bit_rate);
2116
2117             params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate = avctx->bit_rate;
2118             reconfig_bitrate = 1;
2119         }
2120
2121         if (avctx->rc_max_rate > 0 && ctx->encode_config.rcParams.maxBitRate != avctx->rc_max_rate) {
2122             av_log(avctx, AV_LOG_VERBOSE,
2123                    "max bitrate change: %d -> %d\n",
2124                    params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate,
2125                    (uint32_t)avctx->rc_max_rate);
2126
2127             params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate = avctx->rc_max_rate;
2128             reconfig_bitrate = 1;
2129         }
2130
2131         if (avctx->rc_buffer_size > 0 && ctx->encode_config.rcParams.vbvBufferSize != avctx->rc_buffer_size) {
2132             av_log(avctx, AV_LOG_VERBOSE,
2133                    "vbv buffer size change: %d -> %d\n",
2134                    params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize,
2135                    avctx->rc_buffer_size);
2136
2137             params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize = avctx->rc_buffer_size;
2138             reconfig_bitrate = 1;
2139         }
2140
2141         if (reconfig_bitrate) {
2142             params.resetEncoder = 1;
2143             params.forceIDR = 1;
2144
2145             needs_encode_config = 1;
2146             needs_reconfig = 1;
2147         }
2148     }
2149
2150     if (!needs_encode_config)
2151         params.reInitEncodeParams.encodeConfig = NULL;
2152
2153     if (needs_reconfig) {
2154         ret = p_nvenc->nvEncReconfigureEncoder(ctx->nvencoder, &params);
2155         if (ret != NV_ENC_SUCCESS) {
2156             nvenc_print_error(avctx, ret, "failed to reconfigure nvenc");
2157         } else {
2158             if (reconfig_dar) {
2159                 ctx->init_encode_params.darHeight = dh;
2160                 ctx->init_encode_params.darWidth = dw;
2161             }
2162
2163             if (reconfig_bitrate) {
2164                 ctx->encode_config.rcParams.averageBitRate = params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate;
2165                 ctx->encode_config.rcParams.maxBitRate = params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate;
2166                 ctx->encode_config.rcParams.vbvBufferSize = params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize;
2167             }
2168
2169         }
2170     }
2171 }
2172
2173 static int nvenc_send_frame(AVCodecContext *avctx, const AVFrame *frame)
2174 {
2175     NVENCSTATUS nv_status;
2176     NvencSurface *tmp_out_surf, *in_surf;
2177     int res, res2;
2178     NV_ENC_SEI_PAYLOAD sei_data[8];
2179     int sei_count = 0;
2180     int i;
2181
2182     NvencContext *ctx = avctx->priv_data;
2183     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
2184     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
2185
2186     NV_ENC_PIC_PARAMS pic_params = { 0 };
2187     pic_params.version = NV_ENC_PIC_PARAMS_VER;
2188
2189     if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
2190         return AVERROR(EINVAL);
2191
2192     if (frame && frame->buf[0]) {
2193         in_surf = get_free_frame(ctx);
2194         if (!in_surf)
2195             return AVERROR(EAGAIN);
2196
2197         res = nvenc_push_context(avctx);
2198         if (res < 0)
2199             return res;
2200
2201         reconfig_encoder(avctx, frame);
2202
2203         res = nvenc_upload_frame(avctx, frame, in_surf);
2204
2205         res2 = nvenc_pop_context(avctx);
2206         if (res2 < 0)
2207             return res2;
2208
2209         if (res)
2210             return res;
2211
2212         pic_params.inputBuffer = in_surf->input_surface;
2213         pic_params.bufferFmt = in_surf->format;
2214         pic_params.inputWidth = in_surf->width;
2215         pic_params.inputHeight = in_surf->height;
2216         pic_params.inputPitch = in_surf->pitch;
2217         pic_params.outputBitstream = in_surf->output_surface;
2218
2219         if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
2220             if (frame->top_field_first)
2221                 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
2222             else
2223                 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
2224         } else {
2225             pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
2226         }
2227
2228         if (ctx->forced_idr >= 0 && frame->pict_type == AV_PICTURE_TYPE_I) {
2229             pic_params.encodePicFlags =
2230                 ctx->forced_idr ? NV_ENC_PIC_FLAG_FORCEIDR : NV_ENC_PIC_FLAG_FORCEINTRA;
2231         } else {
2232             pic_params.encodePicFlags = 0;
2233         }
2234
2235         pic_params.inputTimeStamp = frame->pts;
2236
2237         if (ctx->a53_cc && av_frame_get_side_data(frame, AV_FRAME_DATA_A53_CC)) {
2238             void *a53_data = NULL;
2239             size_t a53_size = 0;
2240
2241             if (ff_alloc_a53_sei(frame, 0, (void**)&a53_data, &a53_size) < 0) {
2242                 av_log(ctx, AV_LOG_ERROR, "Not enough memory for closed captions, skipping\n");
2243             }
2244
2245             if (a53_data) {
2246                 sei_data[sei_count].payloadSize = (uint32_t)a53_size;
2247                 sei_data[sei_count].payloadType = 4;
2248                 sei_data[sei_count].payload = (uint8_t*)a53_data;
2249                 sei_count ++;
2250             }
2251         }
2252
2253         if (ctx->s12m_tc && av_frame_get_side_data(frame, AV_FRAME_DATA_S12M_TIMECODE)) {
2254             void *tc_data = NULL;
2255             size_t tc_size = 0;
2256
2257             if (ff_alloc_timecode_sei(frame, avctx->framerate, 0, (void**)&tc_data, &tc_size) < 0) {
2258                 av_log(ctx, AV_LOG_ERROR, "Not enough memory for timecode sei, skipping\n");
2259             }
2260
2261             if (tc_data) {
2262                 sei_data[sei_count].payloadSize = (uint32_t)tc_size;
2263                 sei_data[sei_count].payloadType = HEVC_SEI_TYPE_TIME_CODE;
2264                 sei_data[sei_count].payload = (uint8_t*)tc_data;
2265                 sei_count ++;
2266             }
2267         }
2268
2269         nvenc_codec_specific_pic_params(avctx, &pic_params, sei_data, sei_count);
2270     } else {
2271         pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
2272     }
2273
2274     res = nvenc_push_context(avctx);
2275     if (res < 0)
2276         return res;
2277
2278     nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
2279
2280     for ( i = 0; i < sei_count; i++)
2281         av_freep(&sei_data[i].payload);
2282
2283     res = nvenc_pop_context(avctx);
2284     if (res < 0)
2285         return res;
2286
2287     if (nv_status != NV_ENC_SUCCESS &&
2288         nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
2289         return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
2290
2291     if (frame && frame->buf[0]) {
2292         av_fifo_generic_write(ctx->output_surface_queue, &in_surf, sizeof(in_surf), NULL);
2293         timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
2294     }
2295
2296     /* all the pending buffers are now ready for output */
2297     if (nv_status == NV_ENC_SUCCESS) {
2298         while (av_fifo_size(ctx->output_surface_queue) > 0) {
2299             av_fifo_generic_read(ctx->output_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2300             av_fifo_generic_write(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2301         }
2302     }
2303
2304     return 0;
2305 }
2306
2307 int ff_nvenc_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
2308 {
2309     NvencSurface *tmp_out_surf;
2310     int res, res2;
2311
2312     NvencContext *ctx = avctx->priv_data;
2313
2314     AVFrame *frame = ctx->frame;
2315
2316     if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
2317         return AVERROR(EINVAL);
2318
2319     if (!frame->buf[0]) {
2320         res = ff_encode_get_frame(avctx, frame);
2321         if (res < 0 && res != AVERROR_EOF)
2322             return res;
2323     }
2324
2325     res = nvenc_send_frame(avctx, frame);
2326     if (res < 0) {
2327         if (res != AVERROR(EAGAIN))
2328             return res;
2329     } else
2330         av_frame_unref(frame);
2331
2332     if (output_ready(avctx, avctx->internal->draining)) {
2333         av_fifo_generic_read(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2334
2335         res = nvenc_push_context(avctx);
2336         if (res < 0)
2337             return res;
2338
2339         res = process_output_surface(avctx, pkt, tmp_out_surf);
2340
2341         res2 = nvenc_pop_context(avctx);
2342         if (res2 < 0)
2343             return res2;
2344
2345         if (res)
2346             return res;
2347
2348         av_fifo_generic_write(ctx->unused_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2349     } else if (avctx->internal->draining) {
2350         return AVERROR_EOF;
2351     } else {
2352         return AVERROR(EAGAIN);
2353     }
2354
2355     return 0;
2356 }
2357
2358 av_cold void ff_nvenc_encode_flush(AVCodecContext *avctx)
2359 {
2360     NvencContext *ctx = avctx->priv_data;
2361
2362     nvenc_send_frame(avctx, NULL);
2363     av_fifo_reset(ctx->timestamp_list);
2364 }