]> git.sesse.net Git - ffmpeg/blob - libavcodec/nvenc.c
avcodec/nvenc: split H264/HEVC encoder definitions into separate files
[ffmpeg] / libavcodec / nvenc.c
1 /*
2  * H.264 hardware encoding using nvidia nvenc
3  * Copyright (c) 2014 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 #if defined(_WIN32)
25 #include <windows.h>
26 #else
27 #include <dlfcn.h>
28 #endif
29
30 #include "libavutil/imgutils.h"
31 #include "libavutil/avassert.h"
32 #include "libavutil/mem.h"
33 #include "libavutil/hwcontext.h"
34 #include "internal.h"
35 #include "thread.h"
36
37 #include "nvenc.h"
38
39 #if CONFIG_CUDA
40 #include "libavutil/hwcontext_cuda.h"
41 #endif
42
43 #if defined(_WIN32)
44 #define LOAD_FUNC(l, s) GetProcAddress(l, s)
45 #define DL_CLOSE_FUNC(l) FreeLibrary(l)
46 #else
47 #define LOAD_FUNC(l, s) dlsym(l, s)
48 #define DL_CLOSE_FUNC(l) dlclose(l)
49 #endif
50
51 const enum AVPixelFormat ff_nvenc_pix_fmts[] = {
52     AV_PIX_FMT_YUV420P,
53     AV_PIX_FMT_NV12,
54     AV_PIX_FMT_YUV444P,
55 #if CONFIG_CUDA
56     AV_PIX_FMT_CUDA,
57 #endif
58     AV_PIX_FMT_NONE
59 };
60
61 typedef struct NvencData
62 {
63     union {
64         int64_t timestamp;
65         NvencSurface *surface;
66     } u;
67 } NvencData;
68
69 typedef struct NvencValuePair
70 {
71     const char *str;
72     uint32_t num;
73 } NvencValuePair;
74
75 static const NvencValuePair nvenc_h264_level_pairs[] = {
76     { "auto", NV_ENC_LEVEL_AUTOSELECT },
77     { "1"   , NV_ENC_LEVEL_H264_1     },
78     { "1.0" , NV_ENC_LEVEL_H264_1     },
79     { "1b"  , NV_ENC_LEVEL_H264_1b    },
80     { "1.0b", NV_ENC_LEVEL_H264_1b    },
81     { "1.1" , NV_ENC_LEVEL_H264_11    },
82     { "1.2" , NV_ENC_LEVEL_H264_12    },
83     { "1.3" , NV_ENC_LEVEL_H264_13    },
84     { "2"   , NV_ENC_LEVEL_H264_2     },
85     { "2.0" , NV_ENC_LEVEL_H264_2     },
86     { "2.1" , NV_ENC_LEVEL_H264_21    },
87     { "2.2" , NV_ENC_LEVEL_H264_22    },
88     { "3"   , NV_ENC_LEVEL_H264_3     },
89     { "3.0" , NV_ENC_LEVEL_H264_3     },
90     { "3.1" , NV_ENC_LEVEL_H264_31    },
91     { "3.2" , NV_ENC_LEVEL_H264_32    },
92     { "4"   , NV_ENC_LEVEL_H264_4     },
93     { "4.0" , NV_ENC_LEVEL_H264_4     },
94     { "4.1" , NV_ENC_LEVEL_H264_41    },
95     { "4.2" , NV_ENC_LEVEL_H264_42    },
96     { "5"   , NV_ENC_LEVEL_H264_5     },
97     { "5.0" , NV_ENC_LEVEL_H264_5     },
98     { "5.1" , NV_ENC_LEVEL_H264_51    },
99     { NULL }
100 };
101
102 static const NvencValuePair nvenc_hevc_level_pairs[] = {
103     { "auto", NV_ENC_LEVEL_AUTOSELECT },
104     { "1"   , NV_ENC_LEVEL_HEVC_1     },
105     { "1.0" , NV_ENC_LEVEL_HEVC_1     },
106     { "2"   , NV_ENC_LEVEL_HEVC_2     },
107     { "2.0" , NV_ENC_LEVEL_HEVC_2     },
108     { "2.1" , NV_ENC_LEVEL_HEVC_21    },
109     { "3"   , NV_ENC_LEVEL_HEVC_3     },
110     { "3.0" , NV_ENC_LEVEL_HEVC_3     },
111     { "3.1" , NV_ENC_LEVEL_HEVC_31    },
112     { "4"   , NV_ENC_LEVEL_HEVC_4     },
113     { "4.0" , NV_ENC_LEVEL_HEVC_4     },
114     { "4.1" , NV_ENC_LEVEL_HEVC_41    },
115     { "5"   , NV_ENC_LEVEL_HEVC_5     },
116     { "5.0" , NV_ENC_LEVEL_HEVC_5     },
117     { "5.1" , NV_ENC_LEVEL_HEVC_51    },
118     { "5.2" , NV_ENC_LEVEL_HEVC_52    },
119     { "6"   , NV_ENC_LEVEL_HEVC_6     },
120     { "6.0" , NV_ENC_LEVEL_HEVC_6     },
121     { "6.1" , NV_ENC_LEVEL_HEVC_61    },
122     { "6.2" , NV_ENC_LEVEL_HEVC_62    },
123     { NULL }
124 };
125
126 static const struct {
127     NVENCSTATUS nverr;
128     int         averr;
129     const char *desc;
130 } nvenc_errors[] = {
131     { NV_ENC_SUCCESS,                      0,                "success"                  },
132     { NV_ENC_ERR_NO_ENCODE_DEVICE,         AVERROR(ENOENT),  "no encode device"         },
133     { NV_ENC_ERR_UNSUPPORTED_DEVICE,       AVERROR(ENOSYS),  "unsupported device"       },
134     { NV_ENC_ERR_INVALID_ENCODERDEVICE,    AVERROR(EINVAL),  "invalid encoder device"   },
135     { NV_ENC_ERR_INVALID_DEVICE,           AVERROR(EINVAL),  "invalid device"           },
136     { NV_ENC_ERR_DEVICE_NOT_EXIST,         AVERROR(EIO),     "device does not exist"    },
137     { NV_ENC_ERR_INVALID_PTR,              AVERROR(EFAULT),  "invalid ptr"              },
138     { NV_ENC_ERR_INVALID_EVENT,            AVERROR(EINVAL),  "invalid event"            },
139     { NV_ENC_ERR_INVALID_PARAM,            AVERROR(EINVAL),  "invalid param"            },
140     { NV_ENC_ERR_INVALID_CALL,             AVERROR(EINVAL),  "invalid call"             },
141     { NV_ENC_ERR_OUT_OF_MEMORY,            AVERROR(ENOMEM),  "out of memory"            },
142     { NV_ENC_ERR_ENCODER_NOT_INITIALIZED,  AVERROR(EINVAL),  "encoder not initialized"  },
143     { NV_ENC_ERR_UNSUPPORTED_PARAM,        AVERROR(ENOSYS),  "unsupported param"        },
144     { NV_ENC_ERR_LOCK_BUSY,                AVERROR(EAGAIN),  "lock busy"                },
145     { NV_ENC_ERR_NOT_ENOUGH_BUFFER,        AVERROR(ENOBUFS), "not enough buffer"        },
146     { NV_ENC_ERR_INVALID_VERSION,          AVERROR(EINVAL),  "invalid version"          },
147     { NV_ENC_ERR_MAP_FAILED,               AVERROR(EIO),     "map failed"               },
148     { NV_ENC_ERR_NEED_MORE_INPUT,          AVERROR(EAGAIN),  "need more input"          },
149     { NV_ENC_ERR_ENCODER_BUSY,             AVERROR(EAGAIN),  "encoder busy"             },
150     { NV_ENC_ERR_EVENT_NOT_REGISTERD,      AVERROR(EBADF),   "event not registered"     },
151     { NV_ENC_ERR_GENERIC,                  AVERROR_UNKNOWN,  "generic error"            },
152     { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY,  AVERROR(EINVAL),  "incompatible client key"  },
153     { NV_ENC_ERR_UNIMPLEMENTED,            AVERROR(ENOSYS),  "unimplemented"            },
154     { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO),     "resource register failed" },
155     { NV_ENC_ERR_RESOURCE_NOT_REGISTERED,  AVERROR(EBADF),   "resource not registered"  },
156     { NV_ENC_ERR_RESOURCE_NOT_MAPPED,      AVERROR(EBADF),   "resource not mapped"      },
157 };
158
159 static int nvenc_map_error(NVENCSTATUS err, const char **desc)
160 {
161     int i;
162     for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
163         if (nvenc_errors[i].nverr == err) {
164             if (desc)
165                 *desc = nvenc_errors[i].desc;
166             return nvenc_errors[i].averr;
167         }
168     }
169     if (desc)
170         *desc = "unknown error";
171     return AVERROR_UNKNOWN;
172 }
173
174 static int nvenc_print_error(void *log_ctx, NVENCSTATUS err,
175                                      const char *error_string)
176 {
177     const char *desc;
178     int ret;
179     ret = nvenc_map_error(err, &desc);
180     av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
181     return ret;
182 }
183
184 static int input_string_to_uint32(AVCodecContext *avctx, const NvencValuePair *pair, const char *input, uint32_t *output)
185 {
186     for (; pair->str; ++pair) {
187         if (!strcmp(input, pair->str)) {
188             *output = pair->num;
189             return 0;
190         }
191     }
192
193     return AVERROR(EINVAL);
194 }
195
196 static void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
197 {
198     av_fifo_generic_write(queue, &timestamp, sizeof(timestamp), NULL);
199 }
200
201 static int64_t timestamp_queue_dequeue(AVFifoBuffer* queue)
202 {
203     int64_t timestamp = AV_NOPTS_VALUE;
204     if (av_fifo_size(queue) > 0)
205         av_fifo_generic_read(queue, &timestamp, sizeof(timestamp), NULL);
206
207     return timestamp;
208 }
209
210 #define CHECK_LOAD_FUNC(t, f, s) \
211 do { \
212     (f) = (t)LOAD_FUNC(dl_fn->cuda_lib, s); \
213     if (!(f)) { \
214         av_log(avctx, AV_LOG_FATAL, "Failed loading %s from CUDA library\n", s); \
215         goto error; \
216     } \
217 } while (0)
218
219 static av_cold int nvenc_dyload_cuda(AVCodecContext *avctx)
220 {
221     NvencContext *ctx = avctx->priv_data;
222     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
223
224 #if CONFIG_CUDA
225     dl_fn->cu_init                      = cuInit;
226     dl_fn->cu_device_get_count          = cuDeviceGetCount;
227     dl_fn->cu_device_get                = cuDeviceGet;
228     dl_fn->cu_device_get_name           = cuDeviceGetName;
229     dl_fn->cu_device_compute_capability = cuDeviceComputeCapability;
230     dl_fn->cu_ctx_create                = cuCtxCreate_v2;
231     dl_fn->cu_ctx_pop_current           = cuCtxPopCurrent_v2;
232     dl_fn->cu_ctx_destroy               = cuCtxDestroy_v2;
233
234     return 1;
235 #else
236     if (dl_fn->cuda_lib)
237         return 1;
238
239 #if defined(_WIN32)
240     dl_fn->cuda_lib = LoadLibrary(TEXT("nvcuda.dll"));
241 #else
242     dl_fn->cuda_lib = dlopen("libcuda.so", RTLD_LAZY);
243 #endif
244
245     if (!dl_fn->cuda_lib) {
246         av_log(avctx, AV_LOG_FATAL, "Failed loading CUDA library\n");
247         goto error;
248     }
249
250     CHECK_LOAD_FUNC(PCUINIT, dl_fn->cu_init, "cuInit");
251     CHECK_LOAD_FUNC(PCUDEVICEGETCOUNT, dl_fn->cu_device_get_count, "cuDeviceGetCount");
252     CHECK_LOAD_FUNC(PCUDEVICEGET, dl_fn->cu_device_get, "cuDeviceGet");
253     CHECK_LOAD_FUNC(PCUDEVICEGETNAME, dl_fn->cu_device_get_name, "cuDeviceGetName");
254     CHECK_LOAD_FUNC(PCUDEVICECOMPUTECAPABILITY, dl_fn->cu_device_compute_capability, "cuDeviceComputeCapability");
255     CHECK_LOAD_FUNC(PCUCTXCREATE, dl_fn->cu_ctx_create, "cuCtxCreate_v2");
256     CHECK_LOAD_FUNC(PCUCTXPOPCURRENT, dl_fn->cu_ctx_pop_current, "cuCtxPopCurrent_v2");
257     CHECK_LOAD_FUNC(PCUCTXDESTROY, dl_fn->cu_ctx_destroy, "cuCtxDestroy_v2");
258
259     return 1;
260
261 error:
262
263     if (dl_fn->cuda_lib)
264         DL_CLOSE_FUNC(dl_fn->cuda_lib);
265
266     dl_fn->cuda_lib = NULL;
267
268     return 0;
269 #endif
270 }
271
272 static av_cold int check_cuda_errors(AVCodecContext *avctx, CUresult err, const char *func)
273 {
274     if (err != CUDA_SUCCESS) {
275         av_log(avctx, AV_LOG_FATAL, ">> %s - failed with error code 0x%x\n", func, err);
276         return 0;
277     }
278     return 1;
279 }
280 #define check_cuda_errors(f) if (!check_cuda_errors(avctx, f, #f)) goto error
281
282 static av_cold int nvenc_check_cuda(AVCodecContext *avctx)
283 {
284     int device_count = 0;
285     CUdevice cu_device = 0;
286     char gpu_name[128];
287     int smminor = 0, smmajor = 0;
288     int i, smver, target_smver;
289
290     NvencContext *ctx = avctx->priv_data;
291     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
292
293     switch (avctx->codec->id) {
294     case AV_CODEC_ID_H264:
295         target_smver = ctx->data_pix_fmt == AV_PIX_FMT_YUV444P ? 0x52 : 0x30;
296         break;
297     case AV_CODEC_ID_H265:
298         target_smver = 0x52;
299         break;
300     default:
301         av_log(avctx, AV_LOG_FATAL, "Unknown codec name\n");
302         goto error;
303     }
304
305     if (!strncmp(ctx->preset, "lossless", 8))
306         target_smver = 0x52;
307
308     if (!nvenc_dyload_cuda(avctx))
309         return 0;
310
311     if (dl_fn->nvenc_device_count > 0)
312         return 1;
313
314     check_cuda_errors(dl_fn->cu_init(0));
315
316     check_cuda_errors(dl_fn->cu_device_get_count(&device_count));
317
318     if (!device_count) {
319         av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
320         goto error;
321     }
322
323     av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", device_count);
324
325     dl_fn->nvenc_device_count = 0;
326
327     for (i = 0; i < device_count; ++i) {
328         check_cuda_errors(dl_fn->cu_device_get(&cu_device, i));
329         check_cuda_errors(dl_fn->cu_device_get_name(gpu_name, sizeof(gpu_name), cu_device));
330         check_cuda_errors(dl_fn->cu_device_compute_capability(&smmajor, &smminor, cu_device));
331
332         smver = (smmajor << 4) | smminor;
333
334         av_log(avctx, AV_LOG_VERBOSE, "[ GPU #%d - < %s > has Compute SM %d.%d, NVENC %s ]\n", i, gpu_name, smmajor, smminor, (smver >= target_smver) ? "Available" : "Not Available");
335
336         if (smver >= target_smver)
337             dl_fn->nvenc_devices[dl_fn->nvenc_device_count++] = cu_device;
338     }
339
340     if (!dl_fn->nvenc_device_count) {
341         av_log(avctx, AV_LOG_FATAL, "No NVENC capable devices found\n");
342         goto error;
343     }
344
345     return 1;
346
347 error:
348
349     dl_fn->nvenc_device_count = 0;
350
351     return 0;
352 }
353
354 static av_cold int nvenc_dyload_nvenc(AVCodecContext *avctx)
355 {
356     PNVENCODEAPICREATEINSTANCE nvEncodeAPICreateInstance = 0;
357     NVENCSTATUS nvstatus;
358
359     NvencContext *ctx = avctx->priv_data;
360     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
361
362     if (!nvenc_check_cuda(avctx))
363         return 0;
364
365     if (dl_fn->nvenc_lib)
366         return 1;
367
368 #if defined(_WIN32)
369     if (sizeof(void*) == 8) {
370         dl_fn->nvenc_lib = LoadLibrary(TEXT("nvEncodeAPI64.dll"));
371     } else {
372         dl_fn->nvenc_lib = LoadLibrary(TEXT("nvEncodeAPI.dll"));
373     }
374 #else
375     dl_fn->nvenc_lib = dlopen("libnvidia-encode.so.1", RTLD_LAZY);
376 #endif
377
378     if (!dl_fn->nvenc_lib) {
379         av_log(avctx, AV_LOG_FATAL, "Failed loading the nvenc library\n");
380         goto error;
381     }
382
383     nvEncodeAPICreateInstance = (PNVENCODEAPICREATEINSTANCE)LOAD_FUNC(dl_fn->nvenc_lib, "NvEncodeAPICreateInstance");
384
385     if (!nvEncodeAPICreateInstance) {
386         av_log(avctx, AV_LOG_FATAL, "Failed to load nvenc entrypoint\n");
387         goto error;
388     }
389
390     dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
391
392     nvstatus = nvEncodeAPICreateInstance(&dl_fn->nvenc_funcs);
393
394     if (nvstatus != NV_ENC_SUCCESS) {
395         nvenc_print_error(avctx, nvstatus, "Failed to create nvenc instance");
396         goto error;
397     }
398
399     av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
400
401     return 1;
402
403 error:
404     if (dl_fn->nvenc_lib)
405         DL_CLOSE_FUNC(dl_fn->nvenc_lib);
406
407     dl_fn->nvenc_lib = NULL;
408
409     return 0;
410 }
411
412 static av_cold void nvenc_unload_nvenc(AVCodecContext *avctx)
413 {
414     NvencContext *ctx = avctx->priv_data;
415     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
416
417     DL_CLOSE_FUNC(dl_fn->nvenc_lib);
418     dl_fn->nvenc_lib = NULL;
419
420     dl_fn->nvenc_device_count = 0;
421
422 #if !CONFIG_CUDA
423     DL_CLOSE_FUNC(dl_fn->cuda_lib);
424     dl_fn->cuda_lib = NULL;
425 #endif
426
427     dl_fn->cu_init = NULL;
428     dl_fn->cu_device_get_count = NULL;
429     dl_fn->cu_device_get = NULL;
430     dl_fn->cu_device_get_name = NULL;
431     dl_fn->cu_device_compute_capability = NULL;
432     dl_fn->cu_ctx_create = NULL;
433     dl_fn->cu_ctx_pop_current = NULL;
434     dl_fn->cu_ctx_destroy = NULL;
435
436     av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
437 }
438
439 static av_cold int nvenc_setup_device(AVCodecContext *avctx)
440 {
441     NvencContext *ctx = avctx->priv_data;
442     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
443
444     CUresult cu_res;
445     CUcontext cu_context_curr;
446
447     ctx->data_pix_fmt = avctx->pix_fmt;
448
449 #if CONFIG_CUDA
450     if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
451         AVHWFramesContext *frames_ctx;
452         AVCUDADeviceContext *device_hwctx;
453
454         if (!avctx->hw_frames_ctx) {
455             av_log(avctx, AV_LOG_ERROR, "hw_frames_ctx must be set when using GPU frames as input\n");
456             return AVERROR(EINVAL);
457         }
458
459         frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
460         device_hwctx = frames_ctx->device_ctx->hwctx;
461         ctx->cu_context = device_hwctx->cuda_ctx;
462         ctx->data_pix_fmt = frames_ctx->sw_format;
463         return 0;
464     }
465 #endif
466
467     if (ctx->gpu >= dl_fn->nvenc_device_count) {
468         av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->gpu, dl_fn->nvenc_device_count);
469         return AVERROR(EINVAL);
470     }
471
472     ctx->cu_context = NULL;
473     cu_res = dl_fn->cu_ctx_create(&ctx->cu_context_internal, 4, dl_fn->nvenc_devices[ctx->gpu]); // CU_CTX_SCHED_BLOCKING_SYNC=4, avoid CPU spins
474
475     if (cu_res != CUDA_SUCCESS) {
476         av_log(avctx, AV_LOG_FATAL, "Failed creating CUDA context for NVENC: 0x%x\n", (int)cu_res);
477         return AVERROR_EXTERNAL;
478     }
479
480     cu_res = dl_fn->cu_ctx_pop_current(&cu_context_curr);
481
482     if (cu_res != CUDA_SUCCESS) {
483         av_log(avctx, AV_LOG_FATAL, "Failed popping CUDA context: 0x%x\n", (int)cu_res);
484         return AVERROR_EXTERNAL;
485     }
486
487     ctx->cu_context = ctx->cu_context_internal;
488
489     return 0;
490 }
491
492 static av_cold int nvenc_open_session(AVCodecContext *avctx)
493 {
494     NvencContext *ctx = avctx->priv_data;
495     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
496     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
497
498     NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS encode_session_params = { 0 };
499     NVENCSTATUS nv_status;
500
501     encode_session_params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
502     encode_session_params.apiVersion = NVENCAPI_VERSION;
503     encode_session_params.device = ctx->cu_context;
504     encode_session_params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
505
506     nv_status = p_nvenc->nvEncOpenEncodeSessionEx(&encode_session_params, &ctx->nvencoder);
507     if (nv_status != NV_ENC_SUCCESS) {
508         ctx->nvencoder = NULL;
509         return nvenc_print_error(avctx, nv_status, "OpenEncodeSessionEx failed");
510     }
511
512     return 0;
513 }
514
515 static av_cold void set_constqp(AVCodecContext *avctx)
516 {
517     NvencContext *ctx = avctx->priv_data;
518
519     ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
520     ctx->encode_config.rcParams.constQP.qpInterB = avctx->global_quality;
521     ctx->encode_config.rcParams.constQP.qpInterP = avctx->global_quality;
522     ctx->encode_config.rcParams.constQP.qpIntra = avctx->global_quality;
523 }
524
525 static av_cold void set_vbr(AVCodecContext *avctx)
526 {
527     NvencContext *ctx = avctx->priv_data;
528
529     ctx->encode_config.rcParams.enableMinQP = 1;
530     ctx->encode_config.rcParams.enableMaxQP = 1;
531
532     ctx->encode_config.rcParams.minQP.qpInterB = avctx->qmin;
533     ctx->encode_config.rcParams.minQP.qpInterP = avctx->qmin;
534     ctx->encode_config.rcParams.minQP.qpIntra = avctx->qmin;
535
536     ctx->encode_config.rcParams.maxQP.qpInterB = avctx->qmax;
537     ctx->encode_config.rcParams.maxQP.qpInterP = avctx->qmax;
538     ctx->encode_config.rcParams.maxQP.qpIntra = avctx->qmax;
539 }
540
541 static av_cold void set_lossless(AVCodecContext *avctx)
542 {
543     NvencContext *ctx = avctx->priv_data;
544
545     ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
546     ctx->encode_config.rcParams.constQP.qpInterB = 0;
547     ctx->encode_config.rcParams.constQP.qpInterP = 0;
548     ctx->encode_config.rcParams.constQP.qpIntra = 0;
549 }
550
551 static av_cold void nvenc_setup_rate_control(AVCodecContext *avctx, int lossless)
552 {
553     NvencContext *ctx = avctx->priv_data;
554
555     int qp_inter_p;
556
557     if (avctx->bit_rate > 0) {
558         ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
559     } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
560         ctx->encode_config.rcParams.maxBitRate = ctx->encode_config.rcParams.averageBitRate;
561     }
562
563     if (avctx->rc_max_rate > 0)
564         ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
565
566     if (lossless) {
567         if (avctx->codec->id == AV_CODEC_ID_H264)
568             ctx->encode_config.encodeCodecConfig.h264Config.qpPrimeYZeroTransformBypassFlag = 1;
569
570         set_lossless(avctx);
571
572         avctx->qmin = -1;
573         avctx->qmax = -1;
574     } else if (ctx->cbr) {
575         if (!ctx->twopass) {
576             ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CBR;
577         } else {
578             ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_2_PASS_QUALITY;
579
580             if (avctx->codec->id == AV_CODEC_ID_H264) {
581                 ctx->encode_config.encodeCodecConfig.h264Config.adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
582                 ctx->encode_config.encodeCodecConfig.h264Config.fmoMode = NV_ENC_H264_FMO_DISABLE;
583             }
584         }
585
586         if (avctx->codec->id == AV_CODEC_ID_H264) {
587             ctx->encode_config.encodeCodecConfig.h264Config.outputBufferingPeriodSEI = 1;
588             ctx->encode_config.encodeCodecConfig.h264Config.outputPictureTimingSEI = 1;
589         } else if (avctx->codec->id == AV_CODEC_ID_H265) {
590             ctx->encode_config.encodeCodecConfig.hevcConfig.outputBufferingPeriodSEI = 1;
591             ctx->encode_config.encodeCodecConfig.hevcConfig.outputPictureTimingSEI = 1;
592         }
593     } else if (avctx->global_quality > 0) {
594         set_constqp(avctx);
595
596         avctx->qmin = -1;
597         avctx->qmax = -1;
598     } else {
599         if (avctx->qmin >= 0 && avctx->qmax >= 0) {
600             set_vbr(avctx);
601
602             qp_inter_p = (avctx->qmax + 3 * avctx->qmin) / 4; // biased towards Qmin
603
604             if (ctx->twopass) {
605                 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_2_PASS_VBR;
606                 if (avctx->codec->id == AV_CODEC_ID_H264) {
607                     ctx->encode_config.encodeCodecConfig.h264Config.adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
608                     ctx->encode_config.encodeCodecConfig.h264Config.fmoMode = NV_ENC_H264_FMO_DISABLE;
609                 }
610             } else {
611                 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR_MINQP;
612             }
613         } else {
614             qp_inter_p = 26; // default to 26
615
616             if (ctx->twopass) {
617                 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_2_PASS_VBR;
618             } else {
619                 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
620             }
621         }
622
623         ctx->encode_config.rcParams.enableInitialRCQP = 1;
624         ctx->encode_config.rcParams.initialRCQP.qpInterP  = qp_inter_p;
625
626         if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
627             ctx->encode_config.rcParams.initialRCQP.qpIntra = av_clip(
628                 qp_inter_p * fabs(avctx->i_quant_factor) + avctx->i_quant_offset, 0, 51);
629             ctx->encode_config.rcParams.initialRCQP.qpInterB = av_clip(
630                 qp_inter_p * fabs(avctx->b_quant_factor) + avctx->b_quant_offset, 0, 51);
631         } else {
632             ctx->encode_config.rcParams.initialRCQP.qpIntra = qp_inter_p;
633             ctx->encode_config.rcParams.initialRCQP.qpInterB = qp_inter_p;
634         }
635     }
636
637     if (avctx->rc_buffer_size > 0) {
638         ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
639     } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
640         ctx->encode_config.rcParams.vbvBufferSize = 2 * ctx->encode_config.rcParams.averageBitRate;
641     }
642 }
643
644 static av_cold int nvenc_setup_h264_config(AVCodecContext *avctx, int lossless)
645 {
646     NvencContext *ctx = avctx->priv_data;
647     int res;
648
649     ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.colourMatrix = avctx->colorspace;
650     ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.colourPrimaries = avctx->color_primaries;
651     ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.transferCharacteristics = avctx->color_trc;
652     ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
653         || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
654
655     ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.colourDescriptionPresentFlag =
656         (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
657
658     ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.videoSignalTypePresentFlag =
659         (ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.colourDescriptionPresentFlag
660         || ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.videoFormat != 5
661         || ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.videoFullRangeFlag != 0);
662
663     ctx->encode_config.encodeCodecConfig.h264Config.sliceMode = 3;
664     ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData = 1;
665
666     ctx->encode_config.encodeCodecConfig.h264Config.disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
667     ctx->encode_config.encodeCodecConfig.h264Config.repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
668
669     ctx->encode_config.encodeCodecConfig.h264Config.outputAUD = 1;
670
671     if (!ctx->profile && !lossless) {
672         switch (avctx->profile) {
673         case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
674             ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
675             break;
676         case FF_PROFILE_H264_BASELINE:
677             ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
678             break;
679         case FF_PROFILE_H264_MAIN:
680             ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
681             break;
682         case FF_PROFILE_H264_HIGH:
683         case FF_PROFILE_UNKNOWN:
684             ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
685             break;
686         default:
687             av_log(avctx, AV_LOG_WARNING, "Unsupported profile requested, falling back to high\n");
688             ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
689             break;
690         }
691     } else if (!lossless) {
692         if (!strcmp(ctx->profile, "high")) {
693             ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
694             avctx->profile = FF_PROFILE_H264_HIGH;
695         } else if (!strcmp(ctx->profile, "main")) {
696             ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
697             avctx->profile = FF_PROFILE_H264_MAIN;
698         } else if (!strcmp(ctx->profile, "baseline")) {
699             ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
700             avctx->profile = FF_PROFILE_H264_BASELINE;
701         } else if (!strcmp(ctx->profile, "high444p")) {
702             ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
703             avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
704         } else {
705             av_log(avctx, AV_LOG_FATAL, "Profile \"%s\" is unknown! Supported profiles: high, main, baseline\n", ctx->profile);
706             return AVERROR(EINVAL);
707         }
708     }
709
710     // force setting profile as high444p if input is AV_PIX_FMT_YUV444P
711     if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P) {
712         ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
713         avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
714     }
715
716     ctx->encode_config.encodeCodecConfig.h264Config.chromaFormatIDC = avctx->profile == FF_PROFILE_H264_HIGH_444_PREDICTIVE ? 3 : 1;
717
718     if (ctx->level) {
719         res = input_string_to_uint32(avctx, nvenc_h264_level_pairs, ctx->level, &ctx->encode_config.encodeCodecConfig.h264Config.level);
720
721         if (res) {
722             av_log(avctx, AV_LOG_FATAL, "Level \"%s\" is unknown! Supported levels: auto, 1, 1b, 1.1, 1.2, 1.3, 2, 2.1, 2.2, 3, 3.1, 3.2, 4, 4.1, 4.2, 5, 5.1\n", ctx->level);
723             return res;
724         }
725     } else {
726         ctx->encode_config.encodeCodecConfig.h264Config.level = NV_ENC_LEVEL_AUTOSELECT;
727     }
728
729     return 0;
730 }
731
732 static av_cold int nvenc_setup_hevc_config(AVCodecContext *avctx)
733 {
734     NvencContext *ctx = avctx->priv_data;
735     int res;
736
737     ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.colourMatrix = avctx->colorspace;
738     ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.colourPrimaries = avctx->color_primaries;
739     ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.transferCharacteristics = avctx->color_trc;
740     ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
741         || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
742
743     ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.colourDescriptionPresentFlag =
744         (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
745
746     ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.videoSignalTypePresentFlag =
747         (ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.colourDescriptionPresentFlag
748         || ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.videoFormat != 5
749         || ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.videoFullRangeFlag != 0);
750
751     ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode = 3;
752     ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData = 1;
753
754     ctx->encode_config.encodeCodecConfig.hevcConfig.disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
755     ctx->encode_config.encodeCodecConfig.hevcConfig.repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
756
757     ctx->encode_config.encodeCodecConfig.hevcConfig.outputAUD = 1;
758
759     /* No other profile is supported in the current SDK version 5 */
760     ctx->encode_config.profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
761     avctx->profile = FF_PROFILE_HEVC_MAIN;
762
763     if (ctx->level) {
764         res = input_string_to_uint32(avctx, nvenc_hevc_level_pairs, ctx->level, &ctx->encode_config.encodeCodecConfig.hevcConfig.level);
765
766         if (res) {
767             av_log(avctx, AV_LOG_FATAL, "Level \"%s\" is unknown! Supported levels: auto, 1, 2, 2.1, 3, 3.1, 4, 4.1, 5, 5.1, 5.2, 6, 6.1, 6.2\n", ctx->level);
768             return res;
769         }
770     } else {
771         ctx->encode_config.encodeCodecConfig.hevcConfig.level = NV_ENC_LEVEL_AUTOSELECT;
772     }
773
774     if (ctx->tier) {
775         if (!strcmp(ctx->tier, "main")) {
776             ctx->encode_config.encodeCodecConfig.hevcConfig.tier = NV_ENC_TIER_HEVC_MAIN;
777         } else if (!strcmp(ctx->tier, "high")) {
778             ctx->encode_config.encodeCodecConfig.hevcConfig.tier = NV_ENC_TIER_HEVC_HIGH;
779         } else {
780             av_log(avctx, AV_LOG_FATAL, "Tier \"%s\" is unknown! Supported tiers: main, high\n", ctx->tier);
781             return AVERROR(EINVAL);
782         }
783     }
784
785     return 0;
786 }
787
788 static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx, int lossless)
789 {
790     switch (avctx->codec->id) {
791     case AV_CODEC_ID_H264:
792         return nvenc_setup_h264_config(avctx, lossless);
793     case AV_CODEC_ID_H265:
794         return nvenc_setup_hevc_config(avctx);
795     /* Earlier switch/case will return if unknown codec is passed. */
796     }
797
798     return 0;
799 }
800
801 static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
802 {
803     NvencContext *ctx = avctx->priv_data;
804     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
805     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
806
807     NV_ENC_PRESET_CONFIG preset_config = { 0 };
808     GUID encoder_preset = NV_ENC_PRESET_HQ_GUID;
809     GUID codec;
810     NVENCSTATUS nv_status = NV_ENC_SUCCESS;
811     AVCPBProperties *cpb_props;
812     int num_mbs;
813     int isLL = 0;
814     int lossless = 0;
815     int res = 0;
816     int dw, dh;
817
818     ctx->last_dts = AV_NOPTS_VALUE;
819
820     ctx->encode_config.version = NV_ENC_CONFIG_VER;
821     ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
822     preset_config.version = NV_ENC_PRESET_CONFIG_VER;
823     preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
824
825     if (ctx->preset) {
826         if (!strcmp(ctx->preset, "slow")) {
827             encoder_preset = NV_ENC_PRESET_HQ_GUID;
828             ctx->twopass = 1;
829         } else if (!strcmp(ctx->preset, "medium")) {
830             encoder_preset = NV_ENC_PRESET_HQ_GUID;
831             ctx->twopass = 0;
832         } else if (!strcmp(ctx->preset, "fast")) {
833             encoder_preset = NV_ENC_PRESET_HP_GUID;
834             ctx->twopass = 0;
835         } else if (!strcmp(ctx->preset, "hq")) {
836             encoder_preset = NV_ENC_PRESET_HQ_GUID;
837         } else if (!strcmp(ctx->preset, "hp")) {
838             encoder_preset = NV_ENC_PRESET_HP_GUID;
839         } else if (!strcmp(ctx->preset, "bd")) {
840             encoder_preset = NV_ENC_PRESET_BD_GUID;
841         } else if (!strcmp(ctx->preset, "ll")) {
842             encoder_preset = NV_ENC_PRESET_LOW_LATENCY_DEFAULT_GUID;
843             isLL = 1;
844         } else if (!strcmp(ctx->preset, "llhp")) {
845             encoder_preset = NV_ENC_PRESET_LOW_LATENCY_HP_GUID;
846             isLL = 1;
847         } else if (!strcmp(ctx->preset, "llhq")) {
848             encoder_preset = NV_ENC_PRESET_LOW_LATENCY_HQ_GUID;
849             isLL = 1;
850         } else if (!strcmp(ctx->preset, "lossless")) {
851             encoder_preset = NV_ENC_PRESET_LOSSLESS_DEFAULT_GUID;
852             lossless = 1;
853         } else if (!strcmp(ctx->preset, "losslesshp")) {
854             encoder_preset = NV_ENC_PRESET_LOSSLESS_HP_GUID;
855             lossless = 1;
856         } else if (!strcmp(ctx->preset, "default")) {
857             encoder_preset = NV_ENC_PRESET_DEFAULT_GUID;
858         } else {
859             av_log(avctx, AV_LOG_FATAL, "Preset \"%s\" is unknown! Supported presets: slow, medium, fast, hp, hq, bd, ll, llhp, llhq, lossless, losslesshp, default\n", ctx->preset);
860             return AVERROR(EINVAL);
861         }
862     }
863
864     if (ctx->twopass < 0) {
865         ctx->twopass = isLL;
866     }
867
868     switch (avctx->codec->id) {
869     case AV_CODEC_ID_H264:
870         codec = NV_ENC_CODEC_H264_GUID;
871         break;
872     case AV_CODEC_ID_H265:
873         codec = NV_ENC_CODEC_HEVC_GUID;
874         break;
875     default:
876         av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
877         return AVERROR(EINVAL);
878     }
879
880     nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder, codec, encoder_preset, &preset_config);
881     if (nv_status != NV_ENC_SUCCESS) {
882         return nvenc_print_error(avctx, nv_status, "GetEncodePresetConfig failed");
883     }
884
885     ctx->init_encode_params.encodeGUID = codec;
886     ctx->init_encode_params.encodeHeight = avctx->height;
887     ctx->init_encode_params.encodeWidth = avctx->width;
888
889     if (avctx->sample_aspect_ratio.num && avctx->sample_aspect_ratio.den &&
890         (avctx->sample_aspect_ratio.num != 1 || avctx->sample_aspect_ratio.num != 1)) {
891         av_reduce(&dw, &dh,
892                   avctx->width * avctx->sample_aspect_ratio.num,
893                   avctx->height * avctx->sample_aspect_ratio.den,
894                   1024 * 1024);
895         ctx->init_encode_params.darHeight = dh;
896         ctx->init_encode_params.darWidth = dw;
897     } else {
898         ctx->init_encode_params.darHeight = avctx->height;
899         ctx->init_encode_params.darWidth = avctx->width;
900     }
901
902     // De-compensate for hardware, dubiously, trying to compensate for
903     // playback at 704 pixel width.
904     if (avctx->width == 720 &&
905         (avctx->height == 480 || avctx->height == 576)) {
906         av_reduce(&dw, &dh,
907                   ctx->init_encode_params.darWidth * 44,
908                   ctx->init_encode_params.darHeight * 45,
909                   1024 * 1024);
910         ctx->init_encode_params.darHeight = dh;
911         ctx->init_encode_params.darWidth = dw;
912     }
913
914     ctx->init_encode_params.frameRateNum = avctx->time_base.den;
915     ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
916
917     num_mbs = ((avctx->width + 15) >> 4) * ((avctx->height + 15) >> 4);
918     ctx->max_surface_count = (num_mbs >= 8160) ? 32 : 48;
919
920     if (ctx->buffer_delay >= ctx->max_surface_count)
921         ctx->buffer_delay = ctx->max_surface_count - 1;
922
923     ctx->init_encode_params.enableEncodeAsync = 0;
924     ctx->init_encode_params.enablePTD = 1;
925
926     ctx->init_encode_params.presetGUID = encoder_preset;
927
928     ctx->init_encode_params.encodeConfig = &ctx->encode_config;
929     memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
930     ctx->encode_config.version = NV_ENC_CONFIG_VER;
931
932     if (avctx->refs >= 0) {
933         /* 0 means "let the hardware decide" */
934         switch (avctx->codec->id) {
935         case AV_CODEC_ID_H264:
936             ctx->encode_config.encodeCodecConfig.h264Config.maxNumRefFrames = avctx->refs;
937             break;
938         case AV_CODEC_ID_H265:
939             ctx->encode_config.encodeCodecConfig.hevcConfig.maxNumRefFramesInDPB = avctx->refs;
940             break;
941         /* Earlier switch/case will return if unknown codec is passed. */
942         }
943     }
944
945     if (avctx->gop_size > 0) {
946         if (avctx->max_b_frames >= 0) {
947             /* 0 is intra-only, 1 is I/P only, 2 is one B Frame, 3 two B frames, and so on. */
948             ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
949         }
950
951         ctx->encode_config.gopLength = avctx->gop_size;
952         switch (avctx->codec->id) {
953         case AV_CODEC_ID_H264:
954             ctx->encode_config.encodeCodecConfig.h264Config.idrPeriod = avctx->gop_size;
955             break;
956         case AV_CODEC_ID_H265:
957             ctx->encode_config.encodeCodecConfig.hevcConfig.idrPeriod = avctx->gop_size;
958             break;
959         /* Earlier switch/case will return if unknown codec is passed. */
960         }
961     } else if (avctx->gop_size == 0) {
962         ctx->encode_config.frameIntervalP = 0;
963         ctx->encode_config.gopLength = 1;
964         switch (avctx->codec->id) {
965         case AV_CODEC_ID_H264:
966             ctx->encode_config.encodeCodecConfig.h264Config.idrPeriod = 1;
967             break;
968         case AV_CODEC_ID_H265:
969             ctx->encode_config.encodeCodecConfig.hevcConfig.idrPeriod = 1;
970             break;
971         /* Earlier switch/case will return if unknown codec is passed. */
972         }
973     }
974
975     /* when there're b frames, set dts offset */
976     if (ctx->encode_config.frameIntervalP >= 2)
977         ctx->last_dts = -2;
978
979     nvenc_setup_rate_control(avctx, lossless);
980
981     if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
982         ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
983     } else {
984         ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
985     }
986
987     res = nvenc_setup_codec_config(avctx, lossless);
988     if (res)
989         return res;
990
991     nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
992     if (nv_status != NV_ENC_SUCCESS) {
993         return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
994     }
995
996     if (ctx->encode_config.frameIntervalP > 1)
997         avctx->has_b_frames = 2;
998
999     if (ctx->encode_config.rcParams.averageBitRate > 0)
1000         avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
1001
1002     cpb_props = ff_add_cpb_side_data(avctx);
1003     if (!cpb_props)
1004         return AVERROR(ENOMEM);
1005     cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
1006     cpb_props->avg_bitrate = avctx->bit_rate;
1007     cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
1008
1009     return 0;
1010 }
1011
1012 static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
1013 {
1014     NvencContext *ctx = avctx->priv_data;
1015     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1016     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1017
1018     NVENCSTATUS nv_status;
1019     NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
1020     allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1021
1022     switch (ctx->data_pix_fmt) {
1023     case AV_PIX_FMT_YUV420P:
1024         ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_YV12_PL;
1025         break;
1026
1027     case AV_PIX_FMT_NV12:
1028         ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_NV12_PL;
1029         break;
1030
1031     case AV_PIX_FMT_YUV444P:
1032         ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_YUV444_PL;
1033         break;
1034
1035     default:
1036         av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format\n");
1037         return AVERROR(EINVAL);
1038     }
1039
1040     if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1041         ctx->surfaces[idx].in_ref = av_frame_alloc();
1042         if (!ctx->surfaces[idx].in_ref)
1043             return AVERROR(ENOMEM);
1044     } else {
1045         NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1046         allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1047         allocSurf.width = (avctx->width + 31) & ~31;
1048         allocSurf.height = (avctx->height + 31) & ~31;
1049         allocSurf.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
1050         allocSurf.bufferFmt = ctx->surfaces[idx].format;
1051
1052         nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
1053         if (nv_status != NV_ENC_SUCCESS) {
1054             return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
1055         }
1056
1057         ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
1058         ctx->surfaces[idx].width = allocSurf.width;
1059         ctx->surfaces[idx].height = allocSurf.height;
1060     }
1061
1062     ctx->surfaces[idx].lockCount = 0;
1063
1064     /* 1MB is large enough to hold most output frames. NVENC increases this automaticaly if it's not enough. */
1065     allocOut.size = 1024 * 1024;
1066
1067     allocOut.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
1068
1069     nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
1070     if (nv_status != NV_ENC_SUCCESS) {
1071         int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
1072         if (avctx->pix_fmt != AV_PIX_FMT_CUDA)
1073             p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
1074         av_frame_free(&ctx->surfaces[idx].in_ref);
1075         return err;
1076     }
1077
1078     ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1079     ctx->surfaces[idx].size = allocOut.size;
1080
1081     return 0;
1082 }
1083
1084 static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx, int* surfaceCount)
1085 {
1086     int res;
1087     NvencContext *ctx = avctx->priv_data;
1088
1089     ctx->surfaces = av_malloc(ctx->max_surface_count * sizeof(*ctx->surfaces));
1090
1091     if (!ctx->surfaces) {
1092         return AVERROR(ENOMEM);
1093     }
1094
1095     ctx->timestamp_list = av_fifo_alloc(ctx->max_surface_count * sizeof(int64_t));
1096     if (!ctx->timestamp_list)
1097         return AVERROR(ENOMEM);
1098     ctx->output_surface_queue = av_fifo_alloc(ctx->max_surface_count * sizeof(NvencSurface*));
1099     if (!ctx->output_surface_queue)
1100         return AVERROR(ENOMEM);
1101     ctx->output_surface_ready_queue = av_fifo_alloc(ctx->max_surface_count * sizeof(NvencSurface*));
1102     if (!ctx->output_surface_ready_queue)
1103         return AVERROR(ENOMEM);
1104
1105     for (*surfaceCount = 0; *surfaceCount < ctx->max_surface_count; ++*surfaceCount) {
1106         res = nvenc_alloc_surface(avctx, *surfaceCount);
1107         if (res)
1108             return res;
1109     }
1110
1111     return 0;
1112 }
1113
1114 static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
1115 {
1116     NvencContext *ctx = avctx->priv_data;
1117     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1118     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1119
1120     NVENCSTATUS nv_status;
1121     uint32_t outSize = 0;
1122     char tmpHeader[256];
1123     NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1124     payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1125
1126     payload.spsppsBuffer = tmpHeader;
1127     payload.inBufferSize = sizeof(tmpHeader);
1128     payload.outSPSPPSPayloadSize = &outSize;
1129
1130     nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
1131     if (nv_status != NV_ENC_SUCCESS) {
1132         return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
1133     }
1134
1135     avctx->extradata_size = outSize;
1136     avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
1137
1138     if (!avctx->extradata) {
1139         return AVERROR(ENOMEM);
1140     }
1141
1142     memcpy(avctx->extradata, tmpHeader, outSize);
1143
1144     return 0;
1145 }
1146
1147 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
1148 {
1149     NvencContext *ctx = avctx->priv_data;
1150     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1151     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1152
1153     int res;
1154     int i;
1155     int surfaceCount = 0;
1156
1157     if (!nvenc_dyload_nvenc(avctx))
1158         return AVERROR_EXTERNAL;
1159
1160     res = nvenc_setup_device(avctx);
1161     if (res)
1162         goto error;
1163
1164     res = nvenc_open_session(avctx);
1165     if (res)
1166         goto error;
1167
1168     res = nvenc_setup_encoder(avctx);
1169     if (res)
1170         goto error;
1171
1172     res = nvenc_setup_surfaces(avctx, &surfaceCount);
1173     if (res)
1174         goto error;
1175
1176     if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1177         res = nvenc_setup_extradata(avctx);
1178         if (res)
1179             goto error;
1180     }
1181
1182     return 0;
1183
1184 error:
1185     av_fifo_freep(&ctx->timestamp_list);
1186     av_fifo_freep(&ctx->output_surface_ready_queue);
1187     av_fifo_freep(&ctx->output_surface_queue);
1188
1189     for (i = 0; i < surfaceCount; ++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     av_freep(&ctx->surfaces);
1196
1197     if (ctx->nvencoder)
1198         p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1199     ctx->nvencoder = NULL;
1200
1201     if (ctx->cu_context_internal)
1202         dl_fn->cu_ctx_destroy(ctx->cu_context_internal);
1203     ctx->cu_context = ctx->cu_context_internal = NULL;
1204
1205     nvenc_unload_nvenc(avctx);
1206
1207     return res;
1208 }
1209
1210 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
1211 {
1212     NvencContext *ctx = avctx->priv_data;
1213     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1214     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1215     int i;
1216
1217     av_fifo_freep(&ctx->timestamp_list);
1218     av_fifo_freep(&ctx->output_surface_ready_queue);
1219     av_fifo_freep(&ctx->output_surface_queue);
1220
1221     if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1222         for (i = 0; i < ctx->max_surface_count; ++i) {
1223             if (ctx->surfaces[i].input_surface) {
1224                  p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->surfaces[i].in_map.mappedResource);
1225             }
1226         }
1227         for (i = 0; i < ctx->nb_registered_frames; i++) {
1228             if (ctx->registered_frames[i].regptr)
1229                 p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1230         }
1231         ctx->nb_registered_frames = 0;
1232     }
1233
1234     for (i = 0; i < ctx->max_surface_count; ++i) {
1235         if (avctx->pix_fmt != AV_PIX_FMT_CUDA)
1236             p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
1237         av_frame_free(&ctx->surfaces[i].in_ref);
1238         p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
1239     }
1240     av_freep(&ctx->surfaces);
1241     ctx->max_surface_count = 0;
1242
1243     p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1244     ctx->nvencoder = NULL;
1245
1246     if (ctx->cu_context_internal)
1247         dl_fn->cu_ctx_destroy(ctx->cu_context_internal);
1248     ctx->cu_context = ctx->cu_context_internal = NULL;
1249
1250     nvenc_unload_nvenc(avctx);
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->max_surface_count; ++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 *inSurf,
1270             NV_ENC_LOCK_INPUT_BUFFER *lockBufferParams, const AVFrame *frame)
1271 {
1272     uint8_t *buf = lockBufferParams->bufferDataPtr;
1273     int off = inSurf->height * lockBufferParams->pitch;
1274
1275     if (frame->format == AV_PIX_FMT_YUV420P) {
1276         av_image_copy_plane(buf, lockBufferParams->pitch,
1277             frame->data[0], frame->linesize[0],
1278             avctx->width, avctx->height);
1279
1280         buf += off;
1281
1282         av_image_copy_plane(buf, lockBufferParams->pitch >> 1,
1283             frame->data[2], frame->linesize[2],
1284             avctx->width >> 1, avctx->height >> 1);
1285
1286         buf += off >> 2;
1287
1288         av_image_copy_plane(buf, lockBufferParams->pitch >> 1,
1289             frame->data[1], frame->linesize[1],
1290             avctx->width >> 1, avctx->height >> 1);
1291     } else if (frame->format == AV_PIX_FMT_NV12) {
1292         av_image_copy_plane(buf, lockBufferParams->pitch,
1293             frame->data[0], frame->linesize[0],
1294             avctx->width, avctx->height);
1295
1296         buf += off;
1297
1298         av_image_copy_plane(buf, lockBufferParams->pitch,
1299             frame->data[1], frame->linesize[1],
1300             avctx->width, avctx->height >> 1);
1301     } else if (frame->format == AV_PIX_FMT_YUV444P) {
1302         av_image_copy_plane(buf, lockBufferParams->pitch,
1303             frame->data[0], frame->linesize[0],
1304             avctx->width, avctx->height);
1305
1306         buf += off;
1307
1308         av_image_copy_plane(buf, lockBufferParams->pitch,
1309             frame->data[1], frame->linesize[1],
1310             avctx->width, avctx->height);
1311
1312         buf += off;
1313
1314         av_image_copy_plane(buf, lockBufferParams->pitch,
1315             frame->data[2], frame->linesize[2],
1316             avctx->width, avctx->height);
1317     } else {
1318         av_log(avctx, AV_LOG_FATAL, "Invalid pixel format!\n");
1319         return AVERROR(EINVAL);
1320     }
1321
1322     return 0;
1323 }
1324
1325 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1326 {
1327     NvencContext *ctx = avctx->priv_data;
1328     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1329     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1330
1331     int i;
1332
1333     if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1334         for (i = 0; i < ctx->nb_registered_frames; i++) {
1335             if (!ctx->registered_frames[i].mapped) {
1336                 if (ctx->registered_frames[i].regptr) {
1337                     p_nvenc->nvEncUnregisterResource(ctx->nvencoder,
1338                                                 ctx->registered_frames[i].regptr);
1339                     ctx->registered_frames[i].regptr = NULL;
1340                 }
1341                 return i;
1342             }
1343         }
1344     } else {
1345         return ctx->nb_registered_frames++;
1346     }
1347
1348     av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1349     return AVERROR(ENOMEM);
1350 }
1351
1352 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1353 {
1354     NvencContext *ctx = avctx->priv_data;
1355     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1356     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1357
1358     AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1359     NV_ENC_REGISTER_RESOURCE reg;
1360     int i, idx, ret;
1361
1362     for (i = 0; i < ctx->nb_registered_frames; i++) {
1363         if (ctx->registered_frames[i].ptr == (CUdeviceptr)frame->data[0])
1364             return i;
1365     }
1366
1367     idx = nvenc_find_free_reg_resource(avctx);
1368     if (idx < 0)
1369         return idx;
1370
1371     reg.version            = NV_ENC_REGISTER_RESOURCE_VER;
1372     reg.resourceType       = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1373     reg.width              = frames_ctx->width;
1374     reg.height             = frames_ctx->height;
1375     reg.bufferFormat       = ctx->surfaces[0].format;
1376     reg.pitch              = frame->linesize[0];
1377     reg.resourceToRegister = frame->data[0];
1378
1379     ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, &reg);
1380     if (ret != NV_ENC_SUCCESS) {
1381         nvenc_print_error(avctx, ret, "Error registering an input resource");
1382         return AVERROR_UNKNOWN;
1383     }
1384
1385     ctx->registered_frames[idx].ptr    = (CUdeviceptr)frame->data[0];
1386     ctx->registered_frames[idx].regptr = reg.registeredResource;
1387     return idx;
1388 }
1389
1390 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1391                                       NvencSurface *nvenc_frame)
1392 {
1393     NvencContext *ctx = avctx->priv_data;
1394     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1395     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1396
1397     int res;
1398     NVENCSTATUS nv_status;
1399
1400     if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1401         int reg_idx = nvenc_register_frame(avctx, frame);
1402         if (reg_idx < 0) {
1403             av_log(avctx, AV_LOG_ERROR, "Could not register an input CUDA frame\n");
1404             return reg_idx;
1405         }
1406
1407         res = av_frame_ref(nvenc_frame->in_ref, frame);
1408         if (res < 0)
1409             return res;
1410
1411         nvenc_frame->in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1412         nvenc_frame->in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1413         nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &nvenc_frame->in_map);
1414         if (nv_status != NV_ENC_SUCCESS) {
1415             av_frame_unref(nvenc_frame->in_ref);
1416             return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
1417         }
1418
1419         ctx->registered_frames[reg_idx].mapped = 1;
1420         nvenc_frame->reg_idx                   = reg_idx;
1421         nvenc_frame->input_surface             = nvenc_frame->in_map.mappedResource;
1422         return 0;
1423     } else {
1424         NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1425
1426         lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1427         lockBufferParams.inputBuffer = nvenc_frame->input_surface;
1428
1429         nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
1430         if (nv_status != NV_ENC_SUCCESS) {
1431             return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
1432         }
1433
1434         res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
1435
1436         nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
1437         if (nv_status != NV_ENC_SUCCESS) {
1438             return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
1439         }
1440
1441         return res;
1442     }
1443 }
1444
1445 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1446                                                     NV_ENC_PIC_PARAMS *params)
1447 {
1448     NvencContext *ctx = avctx->priv_data;
1449
1450     switch (avctx->codec->id) {
1451     case AV_CODEC_ID_H264:
1452       params->codecPicParams.h264PicParams.sliceMode = ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1453       params->codecPicParams.h264PicParams.sliceModeData = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1454       break;
1455     case AV_CODEC_ID_H265:
1456       params->codecPicParams.hevcPicParams.sliceMode = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1457       params->codecPicParams.hevcPicParams.sliceModeData = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1458       break;
1459     }
1460 }
1461
1462 static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
1463 {
1464     NvencContext *ctx = avctx->priv_data;
1465     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1466     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1467
1468     uint32_t slice_mode_data;
1469     uint32_t *slice_offsets;
1470     NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1471     NVENCSTATUS nv_status;
1472     int res = 0;
1473
1474     enum AVPictureType pict_type;
1475
1476     switch (avctx->codec->id) {
1477     case AV_CODEC_ID_H264:
1478       slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1479       break;
1480     case AV_CODEC_ID_H265:
1481       slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1482       break;
1483     default:
1484       av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
1485       res = AVERROR(EINVAL);
1486       goto error;
1487     }
1488     slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
1489
1490     if (!slice_offsets)
1491         return AVERROR(ENOMEM);
1492
1493     lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1494
1495     lock_params.doNotWait = 0;
1496     lock_params.outputBitstream = tmpoutsurf->output_surface;
1497     lock_params.sliceOffsets = slice_offsets;
1498
1499     nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
1500     if (nv_status != NV_ENC_SUCCESS) {
1501         res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
1502         goto error;
1503     }
1504
1505     if (res = ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes,0)) {
1506         p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1507         goto error;
1508     }
1509
1510     memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1511
1512     nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1513     if (nv_status != NV_ENC_SUCCESS)
1514         nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
1515
1516
1517     if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1518         p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, tmpoutsurf->in_map.mappedResource);
1519         av_frame_unref(tmpoutsurf->in_ref);
1520         ctx->registered_frames[tmpoutsurf->reg_idx].mapped = 0;
1521
1522         tmpoutsurf->input_surface = NULL;
1523     }
1524
1525     switch (lock_params.pictureType) {
1526     case NV_ENC_PIC_TYPE_IDR:
1527         pkt->flags |= AV_PKT_FLAG_KEY;
1528     case NV_ENC_PIC_TYPE_I:
1529         pict_type = AV_PICTURE_TYPE_I;
1530         break;
1531     case NV_ENC_PIC_TYPE_P:
1532         pict_type = AV_PICTURE_TYPE_P;
1533         break;
1534     case NV_ENC_PIC_TYPE_B:
1535         pict_type = AV_PICTURE_TYPE_B;
1536         break;
1537     case NV_ENC_PIC_TYPE_BI:
1538         pict_type = AV_PICTURE_TYPE_BI;
1539         break;
1540     default:
1541         av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
1542         av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
1543         res = AVERROR_EXTERNAL;
1544         goto error;
1545     }
1546
1547 #if FF_API_CODED_FRAME
1548 FF_DISABLE_DEPRECATION_WARNINGS
1549     avctx->coded_frame->pict_type = pict_type;
1550 FF_ENABLE_DEPRECATION_WARNINGS
1551 #endif
1552
1553     ff_side_data_set_encoder_stats(pkt,
1554         (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
1555
1556     pkt->pts = lock_params.outputTimeStamp;
1557     pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
1558
1559     /* when there're b frame(s), set dts offset */
1560     if (ctx->encode_config.frameIntervalP >= 2)
1561         pkt->dts -= 1;
1562
1563     if (pkt->dts > pkt->pts)
1564         pkt->dts = pkt->pts;
1565
1566     if (ctx->last_dts != AV_NOPTS_VALUE && pkt->dts <= ctx->last_dts)
1567         pkt->dts = ctx->last_dts + 1;
1568
1569     ctx->last_dts = pkt->dts;
1570
1571     av_free(slice_offsets);
1572
1573     return 0;
1574
1575 error:
1576
1577     av_free(slice_offsets);
1578     timestamp_queue_dequeue(ctx->timestamp_list);
1579
1580     return res;
1581 }
1582
1583 static int output_ready(NvencContext *ctx, int flush)
1584 {
1585     int nb_ready, nb_pending;
1586
1587     nb_ready   = av_fifo_size(ctx->output_surface_ready_queue)   / sizeof(NvencSurface*);
1588     nb_pending = av_fifo_size(ctx->output_surface_queue)         / sizeof(NvencSurface*);
1589     return nb_ready > 0 && (flush || nb_ready + nb_pending >= ctx->buffer_delay);
1590 }
1591
1592 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1593     const AVFrame *frame, int *got_packet)
1594 {
1595     NVENCSTATUS nv_status;
1596     NvencSurface *tmpoutsurf, *inSurf;
1597     int res;
1598
1599     NvencContext *ctx = avctx->priv_data;
1600     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1601     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1602
1603     NV_ENC_PIC_PARAMS pic_params = { 0 };
1604     pic_params.version = NV_ENC_PIC_PARAMS_VER;
1605
1606     if (frame) {
1607         inSurf = get_free_frame(ctx);
1608         av_assert0(inSurf);
1609
1610         res = nvenc_upload_frame(avctx, frame, inSurf);
1611         if (res) {
1612             inSurf->lockCount = 0;
1613             return res;
1614         }
1615
1616         pic_params.inputBuffer = inSurf->input_surface;
1617         pic_params.bufferFmt = inSurf->format;
1618         pic_params.inputWidth = avctx->width;
1619         pic_params.inputHeight = avctx->height;
1620         pic_params.outputBitstream = inSurf->output_surface;
1621         pic_params.completionEvent = 0;
1622
1623         if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1624             if (frame->top_field_first) {
1625                 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
1626             } else {
1627                 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
1628             }
1629         } else {
1630             pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1631         }
1632
1633         pic_params.encodePicFlags = 0;
1634         pic_params.inputTimeStamp = frame->pts;
1635         pic_params.inputDuration = 0;
1636
1637         nvenc_codec_specific_pic_params(avctx, &pic_params);
1638
1639         timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
1640     } else {
1641         pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1642     }
1643
1644     nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
1645
1646     if (frame && nv_status == NV_ENC_ERR_NEED_MORE_INPUT)
1647         av_fifo_generic_write(ctx->output_surface_queue, &inSurf, sizeof(inSurf), NULL);
1648
1649     if (nv_status != NV_ENC_SUCCESS && nv_status != NV_ENC_ERR_NEED_MORE_INPUT) {
1650         return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
1651     }
1652
1653     if (nv_status != NV_ENC_ERR_NEED_MORE_INPUT) {
1654         while (av_fifo_size(ctx->output_surface_queue) > 0) {
1655             av_fifo_generic_read(ctx->output_surface_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
1656             av_fifo_generic_write(ctx->output_surface_ready_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
1657         }
1658
1659         if (frame)
1660             av_fifo_generic_write(ctx->output_surface_ready_queue, &inSurf, sizeof(inSurf), NULL);
1661     }
1662
1663     if (output_ready(ctx, !frame)) {
1664         av_fifo_generic_read(ctx->output_surface_ready_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
1665
1666         res = process_output_surface(avctx, pkt, tmpoutsurf);
1667
1668         if (res)
1669             return res;
1670
1671         av_assert0(tmpoutsurf->lockCount);
1672         tmpoutsurf->lockCount--;
1673
1674         *got_packet = 1;
1675     } else {
1676         *got_packet = 0;
1677     }
1678
1679     return 0;
1680 }