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