]> git.sesse.net Git - ffmpeg/blob - libavcodec/nvenc.c
Merge commit '402fb5550e36dd994b13941ef5499f9087afd345'
[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 #if defined(_WIN32)
23 #include <windows.h>
24 #else
25 #include <dlfcn.h>
26 #endif
27
28 #include <nvEncodeAPI.h>
29
30 #include "libavutil/internal.h"
31 #include "libavutil/imgutils.h"
32 #include "libavutil/avassert.h"
33 #include "libavutil/opt.h"
34 #include "libavutil/mem.h"
35 #include "avcodec.h"
36 #include "internal.h"
37 #include "thread.h"
38
39 #if defined(_WIN32)
40 #define CUDAAPI __stdcall
41 #else
42 #define CUDAAPI
43 #endif
44
45 #if defined(_WIN32)
46 #define LOAD_FUNC(l, s) GetProcAddress(l, s)
47 #define DL_CLOSE_FUNC(l) FreeLibrary(l)
48 #else
49 #define LOAD_FUNC(l, s) dlsym(l, s)
50 #define DL_CLOSE_FUNC(l) dlclose(l)
51 #endif
52
53 typedef enum cudaError_enum {
54     CUDA_SUCCESS = 0
55 } CUresult;
56 typedef int CUdevice;
57 typedef void* CUcontext;
58
59 typedef CUresult(CUDAAPI *PCUINIT)(unsigned int Flags);
60 typedef CUresult(CUDAAPI *PCUDEVICEGETCOUNT)(int *count);
61 typedef CUresult(CUDAAPI *PCUDEVICEGET)(CUdevice *device, int ordinal);
62 typedef CUresult(CUDAAPI *PCUDEVICEGETNAME)(char *name, int len, CUdevice dev);
63 typedef CUresult(CUDAAPI *PCUDEVICECOMPUTECAPABILITY)(int *major, int *minor, CUdevice dev);
64 typedef CUresult(CUDAAPI *PCUCTXCREATE)(CUcontext *pctx, unsigned int flags, CUdevice dev);
65 typedef CUresult(CUDAAPI *PCUCTXPOPCURRENT)(CUcontext *pctx);
66 typedef CUresult(CUDAAPI *PCUCTXDESTROY)(CUcontext ctx);
67
68 typedef NVENCSTATUS (NVENCAPI* PNVENCODEAPICREATEINSTANCE)(NV_ENCODE_API_FUNCTION_LIST *functionList);
69
70 static const GUID dummy_license = { 0x0, 0x0, 0x0, { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 } };
71
72 typedef struct NvencInputSurface
73 {
74     NV_ENC_INPUT_PTR input_surface;
75     int width;
76     int height;
77
78     int lockCount;
79
80     NV_ENC_BUFFER_FORMAT format;
81 } NvencInputSurface;
82
83 typedef struct NvencOutputSurface
84 {
85     NV_ENC_OUTPUT_PTR output_surface;
86     int size;
87
88     NvencInputSurface* input_surface;
89
90     int busy;
91 } NvencOutputSurface;
92
93 typedef struct NvencData
94 {
95     union {
96         int64_t timestamp;
97         NvencOutputSurface *surface;
98     };
99 } NvencData;
100
101 typedef struct NvencDataList
102 {
103     NvencData* data;
104
105     uint32_t pos;
106     uint32_t count;
107     uint32_t size;
108 } NvencDataList;
109
110 typedef struct NvencDynLoadFunctions
111 {
112     PCUINIT cu_init;
113     PCUDEVICEGETCOUNT cu_device_get_count;
114     PCUDEVICEGET cu_device_get;
115     PCUDEVICEGETNAME cu_device_get_name;
116     PCUDEVICECOMPUTECAPABILITY cu_device_compute_capability;
117     PCUCTXCREATE cu_ctx_create;
118     PCUCTXPOPCURRENT cu_ctx_pop_current;
119     PCUCTXDESTROY cu_ctx_destroy;
120
121     NV_ENCODE_API_FUNCTION_LIST nvenc_funcs;
122     int nvenc_device_count;
123     CUdevice nvenc_devices[16];
124
125 #if defined(_WIN32)
126     HMODULE cuda_lib;
127     HMODULE nvenc_lib;
128 #else
129     void* cuda_lib;
130     void* nvenc_lib;
131 #endif
132 } NvencDynLoadFunctions;
133
134 typedef struct NvencContext
135 {
136     AVClass *avclass;
137
138     NvencDynLoadFunctions nvenc_dload_funcs;
139
140     NV_ENC_INITIALIZE_PARAMS init_encode_params;
141     NV_ENC_CONFIG encode_config;
142     CUcontext cu_context;
143
144     int max_surface_count;
145     NvencInputSurface *input_surfaces;
146     NvencOutputSurface *output_surfaces;
147
148     NvencDataList output_surface_queue;
149     NvencDataList output_surface_ready_queue;
150     NvencDataList timestamp_list;
151     int64_t last_dts;
152
153     void *nvencoder;
154
155     char *preset;
156     int cbr;
157     int twopass;
158     int gobpattern;
159     int gpu;
160 } NvencContext;
161
162 static NvencData* data_queue_dequeue(NvencDataList* queue)
163 {
164     uint32_t mask;
165     uint32_t read_pos;
166
167     av_assert0(queue);
168     av_assert0(queue->size);
169     av_assert0(queue->data);
170
171     if (!queue->count)
172         return NULL;
173
174     /* Size always is a multiple of two */
175     mask = queue->size - 1;
176     read_pos = (queue->pos - queue->count) & mask;
177     queue->count--;
178
179     return &queue->data[read_pos];
180 }
181
182 static int data_queue_enqueue(NvencDataList* queue, NvencData *data)
183 {
184     NvencDataList new_queue;
185     NvencData* tmp_data;
186     uint32_t mask;
187
188     if (!queue->size) {
189         /* size always has to be a multiple of two */
190         queue->size = 4;
191         queue->pos = 0;
192         queue->count = 0;
193
194         queue->data = av_malloc(queue->size * sizeof(*(queue->data)));
195
196         if (!queue->data) {
197             queue->size = 0;
198             return AVERROR(ENOMEM);
199         }
200     }
201
202     if (queue->count == queue->size) {
203         new_queue.size = queue->size << 1;
204         new_queue.pos = 0;
205         new_queue.count = 0;
206         new_queue.data = av_malloc(new_queue.size * sizeof(*(queue->data)));
207
208         if (!new_queue.data)
209             return AVERROR(ENOMEM);
210
211         while (tmp_data = data_queue_dequeue(queue))
212             data_queue_enqueue(&new_queue, tmp_data);
213
214         av_free(queue->data);
215         *queue = new_queue;
216     }
217
218     mask = queue->size - 1;
219
220     queue->data[queue->pos] = *data;
221     queue->pos = (queue->pos + 1) & mask;
222     queue->count++;
223
224     return 0;
225 }
226
227 static int out_surf_queue_enqueue(NvencDataList* queue, NvencOutputSurface* surface)
228 {
229     NvencData data;
230     data.surface = surface;
231
232     return data_queue_enqueue(queue, &data);
233 }
234
235 static NvencOutputSurface* out_surf_queue_dequeue(NvencDataList* queue)
236 {
237     NvencData* res = data_queue_dequeue(queue);
238
239     if (!res)
240         return NULL;
241
242     return res->surface;
243 }
244
245 static int timestamp_queue_enqueue(NvencDataList* queue, int64_t timestamp)
246 {
247     NvencData data;
248     data.timestamp = timestamp;
249
250     return data_queue_enqueue(queue, &data);
251 }
252
253 static int64_t timestamp_queue_dequeue(NvencDataList* queue)
254 {
255     NvencData* res = data_queue_dequeue(queue);
256
257     if (!res)
258         return AV_NOPTS_VALUE;
259
260     return res->timestamp;
261 }
262
263 #define CHECK_LOAD_FUNC(t, f, s) \
264 do { \
265     (f) = (t)LOAD_FUNC(dl_fn->cuda_lib, s); \
266     if (!(f)) { \
267         av_log(avctx, AV_LOG_FATAL, "Failed loading %s from CUDA library\n", s); \
268         goto error; \
269     } \
270 } while (0)
271
272 static av_cold int nvenc_dyload_cuda(AVCodecContext *avctx)
273 {
274     NvencContext *ctx = avctx->priv_data;
275     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
276
277     if (dl_fn->cuda_lib)
278         return 1;
279
280 #if defined(_WIN32)
281     dl_fn->cuda_lib = LoadLibrary(TEXT("nvcuda.dll"));
282 #else
283     dl_fn->cuda_lib = dlopen("libcuda.so", RTLD_LAZY);
284 #endif
285
286     if (!dl_fn->cuda_lib) {
287         av_log(avctx, AV_LOG_FATAL, "Failed loading CUDA library\n");
288         goto error;
289     }
290
291     CHECK_LOAD_FUNC(PCUINIT, dl_fn->cu_init, "cuInit");
292     CHECK_LOAD_FUNC(PCUDEVICEGETCOUNT, dl_fn->cu_device_get_count, "cuDeviceGetCount");
293     CHECK_LOAD_FUNC(PCUDEVICEGET, dl_fn->cu_device_get, "cuDeviceGet");
294     CHECK_LOAD_FUNC(PCUDEVICEGETNAME, dl_fn->cu_device_get_name, "cuDeviceGetName");
295     CHECK_LOAD_FUNC(PCUDEVICECOMPUTECAPABILITY, dl_fn->cu_device_compute_capability, "cuDeviceComputeCapability");
296     CHECK_LOAD_FUNC(PCUCTXCREATE, dl_fn->cu_ctx_create, "cuCtxCreate_v2");
297     CHECK_LOAD_FUNC(PCUCTXPOPCURRENT, dl_fn->cu_ctx_pop_current, "cuCtxPopCurrent_v2");
298     CHECK_LOAD_FUNC(PCUCTXDESTROY, dl_fn->cu_ctx_destroy, "cuCtxDestroy_v2");
299
300     return 1;
301
302 error:
303
304     if (dl_fn->cuda_lib)
305         DL_CLOSE_FUNC(dl_fn->cuda_lib);
306
307     dl_fn->cuda_lib = NULL;
308
309     return 0;
310 }
311
312 static av_cold int check_cuda_errors(AVCodecContext *avctx, CUresult err, const char *func)
313 {
314     if (err != CUDA_SUCCESS) {
315         av_log(avctx, AV_LOG_FATAL, ">> %s - failed with error code 0x%x\n", func, err);
316         return 0;
317     }
318     return 1;
319 }
320 #define check_cuda_errors(f) if (!check_cuda_errors(avctx, f, #f)) goto error
321
322 static av_cold int nvenc_check_cuda(AVCodecContext *avctx)
323 {
324     int device_count = 0;
325     CUdevice cu_device = 0;
326     char gpu_name[128];
327     int smminor = 0, smmajor = 0;
328     int i, smver;
329
330     NvencContext *ctx = avctx->priv_data;
331     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
332
333     if (!nvenc_dyload_cuda(avctx))
334         return 0;
335
336     if (dl_fn->nvenc_device_count > 0)
337         return 1;
338
339     check_cuda_errors(dl_fn->cu_init(0));
340
341     check_cuda_errors(dl_fn->cu_device_get_count(&device_count));
342
343     if (!device_count) {
344         av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
345         goto error;
346     }
347
348     av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", device_count);
349
350     dl_fn->nvenc_device_count = 0;
351
352     for (i = 0; i < device_count; ++i) {
353         check_cuda_errors(dl_fn->cu_device_get(&cu_device, i));
354         check_cuda_errors(dl_fn->cu_device_get_name(gpu_name, sizeof(gpu_name), cu_device));
355         check_cuda_errors(dl_fn->cu_device_compute_capability(&smmajor, &smminor, cu_device));
356
357         smver = (smmajor << 4) | smminor;
358
359         av_log(avctx, AV_LOG_VERBOSE, "[ GPU #%d - < %s > has Compute SM %d.%d, NVENC %s ]\n", i, gpu_name, smmajor, smminor, (smver >= 0x30) ? "Available" : "Not Available");
360
361         if (smver >= 0x30)
362             dl_fn->nvenc_devices[dl_fn->nvenc_device_count++] = cu_device;
363     }
364
365     if (!dl_fn->nvenc_device_count) {
366         av_log(avctx, AV_LOG_FATAL, "No NVENC capable devices found\n");
367         goto error;
368     }
369
370     return 1;
371
372 error:
373
374     dl_fn->nvenc_device_count = 0;
375
376     return 0;
377 }
378
379 static av_cold int nvenc_dyload_nvenc(AVCodecContext *avctx)
380 {
381     PNVENCODEAPICREATEINSTANCE nvEncodeAPICreateInstance = 0;
382     NVENCSTATUS nvstatus;
383
384     NvencContext *ctx = avctx->priv_data;
385     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
386
387     if (!nvenc_check_cuda(avctx))
388         return 0;
389
390     if (dl_fn->nvenc_lib)
391         return 1;
392
393 #if defined(_WIN32)
394     if (sizeof(void*) == 8) {
395         dl_fn->nvenc_lib = LoadLibrary(TEXT("nvEncodeAPI64.dll"));
396     } else {
397         dl_fn->nvenc_lib = LoadLibrary(TEXT("nvEncodeAPI.dll"));
398     }
399 #else
400     dl_fn->nvenc_lib = dlopen("libnvidia-encode.so.1", RTLD_LAZY);
401 #endif
402
403     if (!dl_fn->nvenc_lib) {
404         av_log(avctx, AV_LOG_FATAL, "Failed loading the nvenc library\n");
405         goto error;
406     }
407
408     nvEncodeAPICreateInstance = (PNVENCODEAPICREATEINSTANCE)LOAD_FUNC(dl_fn->nvenc_lib, "NvEncodeAPICreateInstance");
409
410     if (!nvEncodeAPICreateInstance) {
411         av_log(avctx, AV_LOG_FATAL, "Failed to load nvenc entrypoint\n");
412         goto error;
413     }
414
415     dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
416
417     nvstatus = nvEncodeAPICreateInstance(&dl_fn->nvenc_funcs);
418
419     if (nvstatus != NV_ENC_SUCCESS) {
420         av_log(avctx, AV_LOG_FATAL, "Failed to create nvenc instance\n");
421         goto error;
422     }
423
424     av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
425
426     return 1;
427
428 error:
429     if (dl_fn->nvenc_lib)
430         DL_CLOSE_FUNC(dl_fn->nvenc_lib);
431
432     dl_fn->nvenc_lib = NULL;
433
434     return 0;
435 }
436
437 static av_cold void nvenc_unload_nvenc(AVCodecContext *avctx)
438 {
439     NvencContext *ctx = avctx->priv_data;
440     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
441
442     DL_CLOSE_FUNC(dl_fn->nvenc_lib);
443     dl_fn->nvenc_lib = NULL;
444
445     dl_fn->nvenc_device_count = 0;
446
447     DL_CLOSE_FUNC(dl_fn->cuda_lib);
448     dl_fn->cuda_lib = NULL;
449
450     dl_fn->cu_init = NULL;
451     dl_fn->cu_device_get_count = NULL;
452     dl_fn->cu_device_get = NULL;
453     dl_fn->cu_device_get_name = NULL;
454     dl_fn->cu_device_compute_capability = NULL;
455     dl_fn->cu_ctx_create = NULL;
456     dl_fn->cu_ctx_pop_current = NULL;
457     dl_fn->cu_ctx_destroy = NULL;
458
459     av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
460 }
461
462 static av_cold int nvenc_encode_init(AVCodecContext *avctx)
463 {
464     NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS encode_session_params = { 0 };
465     NV_ENC_PRESET_CONFIG preset_config = { 0 };
466     CUcontext cu_context_curr;
467     CUresult cu_res;
468     GUID encoder_preset = NV_ENC_PRESET_HQ_GUID;
469     GUID license = dummy_license;
470     NVENCSTATUS nv_status = NV_ENC_SUCCESS;
471     int surfaceCount = 0;
472     int i, num_mbs;
473     int isLL = 0;
474     int res = 0;
475
476     NvencContext *ctx = avctx->priv_data;
477     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
478     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
479
480     if (!nvenc_dyload_nvenc(avctx))
481         return AVERROR_EXTERNAL;
482
483     avctx->coded_frame = av_frame_alloc();
484     if (!avctx->coded_frame) {
485         res = AVERROR(ENOMEM);
486         goto error;
487     }
488
489     ctx->last_dts = AV_NOPTS_VALUE;
490
491     ctx->encode_config.version = NV_ENC_CONFIG_VER;
492     ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
493     preset_config.version = NV_ENC_PRESET_CONFIG_VER;
494     preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
495     encode_session_params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
496     encode_session_params.apiVersion = NVENCAPI_VERSION;
497     encode_session_params.clientKeyPtr = &license;
498
499     if (ctx->gpu >= dl_fn->nvenc_device_count) {
500         av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->gpu, dl_fn->nvenc_device_count);
501         res = AVERROR(EINVAL);
502         goto error;
503     }
504
505     ctx->cu_context = NULL;
506     cu_res = dl_fn->cu_ctx_create(&ctx->cu_context, 0, dl_fn->nvenc_devices[ctx->gpu]);
507
508     if (cu_res != CUDA_SUCCESS) {
509         av_log(avctx, AV_LOG_FATAL, "Failed creating CUDA context for NVENC: 0x%x\n", (int)cu_res);
510         res = AVERROR_EXTERNAL;
511         goto error;
512     }
513
514     cu_res = dl_fn->cu_ctx_pop_current(&cu_context_curr);
515
516     if (cu_res != CUDA_SUCCESS) {
517         av_log(avctx, AV_LOG_FATAL, "Failed popping CUDA context: 0x%x\n", (int)cu_res);
518         res = AVERROR_EXTERNAL;
519         goto error;
520     }
521
522     encode_session_params.device = ctx->cu_context;
523     encode_session_params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
524
525     nv_status = p_nvenc->nvEncOpenEncodeSessionEx(&encode_session_params, &ctx->nvencoder);
526     if (nv_status != NV_ENC_SUCCESS) {
527         ctx->nvencoder = NULL;
528         av_log(avctx, AV_LOG_FATAL, "OpenEncodeSessionEx failed: 0x%x - invalid license key?\n", (int)nv_status);
529         res = AVERROR_EXTERNAL;
530         goto error;
531     }
532
533     if (ctx->preset) {
534         if (!strcmp(ctx->preset, "hp")) {
535             encoder_preset = NV_ENC_PRESET_HP_GUID;
536         } else if (!strcmp(ctx->preset, "hq")) {
537             encoder_preset = NV_ENC_PRESET_HQ_GUID;
538         } else if (!strcmp(ctx->preset, "bd")) {
539             encoder_preset = NV_ENC_PRESET_BD_GUID;
540         } else if (!strcmp(ctx->preset, "ll")) {
541             encoder_preset = NV_ENC_PRESET_LOW_LATENCY_DEFAULT_GUID;
542             isLL = 1;
543         } else if (!strcmp(ctx->preset, "llhp")) {
544             encoder_preset = NV_ENC_PRESET_LOW_LATENCY_HP_GUID;
545             isLL = 1;
546         } else if (!strcmp(ctx->preset, "llhq")) {
547             encoder_preset = NV_ENC_PRESET_LOW_LATENCY_HQ_GUID;
548             isLL = 1;
549         } else if (!strcmp(ctx->preset, "default")) {
550             encoder_preset = NV_ENC_PRESET_DEFAULT_GUID;
551         } else {
552             av_log(avctx, AV_LOG_FATAL, "Preset \"%s\" is unknown! Supported presets: hp, hq, bd, ll, llhp, llhq, default\n", ctx->preset);
553             res = AVERROR(EINVAL);
554             goto error;
555         }
556     }
557
558     nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder, NV_ENC_CODEC_H264_GUID, encoder_preset, &preset_config);
559     if (nv_status != NV_ENC_SUCCESS) {
560         av_log(avctx, AV_LOG_FATAL, "GetEncodePresetConfig failed: 0x%x\n", (int)nv_status);
561         res = AVERROR_EXTERNAL;
562         goto error;
563     }
564
565     ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
566     ctx->init_encode_params.encodeHeight = avctx->height;
567     ctx->init_encode_params.encodeWidth = avctx->width;
568     ctx->init_encode_params.darHeight = avctx->height;
569     ctx->init_encode_params.darWidth = avctx->width;
570     ctx->init_encode_params.frameRateNum = avctx->time_base.den;
571     ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
572
573     num_mbs = ((avctx->width + 15) >> 4) * ((avctx->height + 15) >> 4);
574     ctx->max_surface_count = (num_mbs >= 8160) ? 32 : 48;
575
576     ctx->init_encode_params.enableEncodeAsync = 0;
577     ctx->init_encode_params.enablePTD = 1;
578
579     ctx->init_encode_params.presetGUID = encoder_preset;
580
581     ctx->init_encode_params.encodeConfig = &ctx->encode_config;
582     memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
583     ctx->encode_config.version = NV_ENC_CONFIG_VER;
584
585     if (avctx->gop_size >= 0) {
586         ctx->encode_config.gopLength = avctx->gop_size;
587         ctx->encode_config.encodeCodecConfig.h264Config.idrPeriod = avctx->gop_size;
588     }
589
590     if (avctx->bit_rate > 0)
591         ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
592
593     if (avctx->rc_max_rate > 0)
594         ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
595
596     if (ctx->cbr) {
597         if (!ctx->twopass) {
598             ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CBR;
599         } else if (ctx->twopass == 1 || isLL) {
600             ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_2_PASS_QUALITY;
601
602             ctx->encode_config.encodeCodecConfig.h264Config.adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
603             ctx->encode_config.encodeCodecConfig.h264Config.fmoMode = NV_ENC_H264_FMO_DISABLE;
604
605             if (!isLL)
606                 av_log(avctx, AV_LOG_WARNING, "Twopass mode is only known to work with low latency (ll, llhq, llhp) presets.\n");
607         } else {
608             ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CBR;
609         }
610     } else if (avctx->global_quality > 0) {
611         ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
612         ctx->encode_config.rcParams.constQP.qpInterB = avctx->global_quality;
613         ctx->encode_config.rcParams.constQP.qpInterP = avctx->global_quality;
614         ctx->encode_config.rcParams.constQP.qpIntra = avctx->global_quality;
615
616         avctx->qmin = -1;
617         avctx->qmax = -1;
618     } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
619         ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
620
621         ctx->encode_config.rcParams.enableMinQP = 1;
622         ctx->encode_config.rcParams.enableMaxQP = 1;
623
624         ctx->encode_config.rcParams.minQP.qpInterB = avctx->qmin;
625         ctx->encode_config.rcParams.minQP.qpInterP = avctx->qmin;
626         ctx->encode_config.rcParams.minQP.qpIntra = avctx->qmin;
627
628         ctx->encode_config.rcParams.maxQP.qpInterB = avctx->qmax;
629         ctx->encode_config.rcParams.maxQP.qpInterP = avctx->qmax;
630         ctx->encode_config.rcParams.maxQP.qpIntra = avctx->qmax;
631     }
632
633     if (avctx->rc_buffer_size > 0)
634         ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
635
636     if (avctx->flags & CODEC_FLAG_INTERLACED_DCT) {
637         ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
638     } else {
639         ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
640     }
641
642     switch (avctx->profile) {
643     case FF_PROFILE_H264_BASELINE:
644         ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
645         break;
646     case FF_PROFILE_H264_MAIN:
647         ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
648         break;
649     case FF_PROFILE_H264_HIGH:
650     case FF_PROFILE_UNKNOWN:
651         ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
652         break;
653     default:
654         av_log(avctx, AV_LOG_WARNING, "Unsupported h264 profile requested, falling back to high\n");
655         ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
656         break;
657     }
658
659     if (ctx->gobpattern >= 0) {
660         ctx->encode_config.frameIntervalP = 1;
661     }
662
663     ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.colourDescriptionPresentFlag = 1;
664     ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.videoSignalTypePresentFlag = 1;
665
666     ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.colourMatrix = avctx->colorspace;
667     ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.colourPrimaries = avctx->color_primaries;
668     ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.transferCharacteristics = avctx->color_trc;
669
670     ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.videoFullRangeFlag = avctx->color_range == AVCOL_RANGE_JPEG;
671
672     ctx->encode_config.encodeCodecConfig.h264Config.disableSPSPPS = (avctx->flags & CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
673
674     nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
675     if (nv_status != NV_ENC_SUCCESS) {
676         av_log(avctx, AV_LOG_FATAL, "InitializeEncoder failed: 0x%x\n", (int)nv_status);
677         res = AVERROR_EXTERNAL;
678         goto error;
679     }
680
681     ctx->input_surfaces = av_malloc(ctx->max_surface_count * sizeof(*ctx->input_surfaces));
682
683     if (!ctx->input_surfaces) {
684         res = AVERROR(ENOMEM);
685         goto error;
686     }
687
688     ctx->output_surfaces = av_malloc(ctx->max_surface_count * sizeof(*ctx->output_surfaces));
689
690     if (!ctx->output_surfaces) {
691         res = AVERROR(ENOMEM);
692         goto error;
693     }
694
695     for (surfaceCount = 0; surfaceCount < ctx->max_surface_count; ++surfaceCount) {
696         NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
697         NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
698         allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
699         allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
700
701         allocSurf.width = (avctx->width + 31) & ~31;
702         allocSurf.height = (avctx->height + 31) & ~31;
703
704         allocSurf.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
705
706         switch (avctx->pix_fmt) {
707         case AV_PIX_FMT_YUV420P:
708             allocSurf.bufferFmt = NV_ENC_BUFFER_FORMAT_YV12_PL;
709             break;
710
711         case AV_PIX_FMT_NV12:
712             allocSurf.bufferFmt = NV_ENC_BUFFER_FORMAT_NV12_PL;
713             break;
714
715         case AV_PIX_FMT_YUV444P:
716             allocSurf.bufferFmt = NV_ENC_BUFFER_FORMAT_YUV444_PL;
717             break;
718
719         default:
720             av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format\n");
721             res = AVERROR(EINVAL);
722             goto error;
723         }
724
725         nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
726         if (nv_status = NV_ENC_SUCCESS){
727             av_log(avctx, AV_LOG_FATAL, "CreateInputBuffer failed\n");
728             res = AVERROR_EXTERNAL;
729             goto error;
730         }
731
732         ctx->input_surfaces[surfaceCount].lockCount = 0;
733         ctx->input_surfaces[surfaceCount].input_surface = allocSurf.inputBuffer;
734         ctx->input_surfaces[surfaceCount].format = allocSurf.bufferFmt;
735         ctx->input_surfaces[surfaceCount].width = allocSurf.width;
736         ctx->input_surfaces[surfaceCount].height = allocSurf.height;
737
738         /* 1MB is large enough to hold most output frames. NVENC increases this automaticaly if it's not enough. */
739         allocOut.size = 1024 * 1024;
740
741         allocOut.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
742
743         nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
744         if (nv_status = NV_ENC_SUCCESS) {
745             av_log(avctx, AV_LOG_FATAL, "CreateBitstreamBuffer failed\n");
746             ctx->output_surfaces[surfaceCount++].output_surface = NULL;
747             res = AVERROR_EXTERNAL;
748             goto error;
749         }
750
751         ctx->output_surfaces[surfaceCount].output_surface = allocOut.bitstreamBuffer;
752         ctx->output_surfaces[surfaceCount].size = allocOut.size;
753         ctx->output_surfaces[surfaceCount].busy = 0;
754     }
755
756     if (avctx->flags & CODEC_FLAG_GLOBAL_HEADER) {
757         uint32_t outSize = 0;
758         char tmpHeader[256];
759         NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
760         payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
761
762         payload.spsppsBuffer = tmpHeader;
763         payload.inBufferSize = sizeof(tmpHeader);
764         payload.outSPSPPSPayloadSize = &outSize;
765
766         nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
767         if (nv_status != NV_ENC_SUCCESS) {
768             av_log(avctx, AV_LOG_FATAL, "GetSequenceParams failed\n");
769             goto error;
770         }
771
772         avctx->extradata_size = outSize;
773         avctx->extradata = av_mallocz(outSize + FF_INPUT_BUFFER_PADDING_SIZE);
774
775         if (!avctx->extradata) {
776             res = AVERROR(ENOMEM);
777             goto error;
778         }
779
780         memcpy(avctx->extradata, tmpHeader, outSize);
781     }
782
783     if (ctx->encode_config.frameIntervalP > 1)
784         avctx->has_b_frames = 2;
785
786     if (ctx->encode_config.rcParams.averageBitRate > 0)
787         avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
788
789     return 0;
790
791 error:
792
793     for (i = 0; i < surfaceCount; ++i) {
794         p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->input_surfaces[i].input_surface);
795         if (ctx->output_surfaces[i].output_surface)
796             p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->output_surfaces[i].output_surface);
797     }
798
799     if (ctx->nvencoder)
800         p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
801
802     if (ctx->cu_context)
803         dl_fn->cu_ctx_destroy(ctx->cu_context);
804
805     av_frame_free(&avctx->coded_frame);
806
807     nvenc_unload_nvenc(avctx);
808
809     ctx->nvencoder = NULL;
810     ctx->cu_context = NULL;
811
812     return res;
813 }
814
815 static av_cold int nvenc_encode_close(AVCodecContext *avctx)
816 {
817     NvencContext *ctx = avctx->priv_data;
818     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
819     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
820     int i;
821
822     av_freep(&ctx->timestamp_list.data);
823     av_freep(&ctx->output_surface_ready_queue.data);
824     av_freep(&ctx->output_surface_queue.data);
825
826     for (i = 0; i < ctx->max_surface_count; ++i) {
827         p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->input_surfaces[i].input_surface);
828         p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->output_surfaces[i].output_surface);
829     }
830     ctx->max_surface_count = 0;
831
832     p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
833     ctx->nvencoder = NULL;
834
835     dl_fn->cu_ctx_destroy(ctx->cu_context);
836     ctx->cu_context = NULL;
837
838     nvenc_unload_nvenc(avctx);
839
840     av_frame_free(&avctx->coded_frame);
841
842     return 0;
843 }
844
845 static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, AVFrame *coded_frame, NvencOutputSurface *tmpoutsurf)
846 {
847     NvencContext *ctx = avctx->priv_data;
848     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
849     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
850
851     uint32_t *slice_offsets = av_mallocz(ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData * sizeof(*slice_offsets));
852     NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
853     NVENCSTATUS nv_status;
854     int res = 0;
855
856     if (!slice_offsets)
857         return AVERROR(ENOMEM);
858
859     lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
860
861     lock_params.doNotWait = 0;
862     lock_params.outputBitstream = tmpoutsurf->output_surface;
863     lock_params.sliceOffsets = slice_offsets;
864
865     nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
866     if (nv_status != NV_ENC_SUCCESS) {
867         av_log(avctx, AV_LOG_ERROR, "Failed locking bitstream buffer\n");
868         res = AVERROR_EXTERNAL;
869         goto error;
870     }
871
872     if (res = ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes)) {
873         p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
874         goto error;
875     }
876
877     memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
878
879     nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
880     if (nv_status != NV_ENC_SUCCESS)
881         av_log(avctx, AV_LOG_ERROR, "Failed unlocking bitstream buffer, expect the gates of mordor to open\n");
882
883     switch (lock_params.pictureType) {
884     case NV_ENC_PIC_TYPE_IDR:
885         pkt->flags |= AV_PKT_FLAG_KEY;
886     case NV_ENC_PIC_TYPE_I:
887         avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
888         break;
889     case NV_ENC_PIC_TYPE_P:
890         avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
891         break;
892     case NV_ENC_PIC_TYPE_B:
893         avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;
894         break;
895     case NV_ENC_PIC_TYPE_BI:
896         avctx->coded_frame->pict_type = AV_PICTURE_TYPE_BI;
897         break;
898     default:
899         av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
900         av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
901         res = AVERROR_EXTERNAL;
902         goto error;
903     }
904
905     pkt->pts = lock_params.outputTimeStamp;
906     pkt->dts = timestamp_queue_dequeue(&ctx->timestamp_list);
907
908     if (pkt->dts > pkt->pts)
909         pkt->dts = pkt->pts;
910
911     if (ctx->last_dts != AV_NOPTS_VALUE && pkt->dts <= ctx->last_dts)
912         pkt->dts = ctx->last_dts + 1;
913
914     ctx->last_dts = pkt->dts;
915
916     av_free(slice_offsets);
917
918     return 0;
919
920 error:
921
922     av_free(slice_offsets);
923     timestamp_queue_dequeue(&ctx->timestamp_list);
924
925     return res;
926 }
927
928 static int nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
929     const AVFrame *frame, int *got_packet)
930 {
931     NVENCSTATUS nv_status;
932     NvencOutputSurface *tmpoutsurf;
933     int res, i = 0;
934
935     NvencContext *ctx = avctx->priv_data;
936     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
937     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
938
939     NV_ENC_PIC_PARAMS pic_params = { 0 };
940     pic_params.version = NV_ENC_PIC_PARAMS_VER;
941
942     if (frame) {
943         NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
944         NvencInputSurface *inSurf = NULL;
945
946         for (i = 0; i < ctx->max_surface_count; ++i) {
947             if (!ctx->input_surfaces[i].lockCount) {
948                 inSurf = &ctx->input_surfaces[i];
949                 break;
950             }
951         }
952
953         av_assert0(inSurf);
954
955         inSurf->lockCount = 1;
956
957         lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
958         lockBufferParams.inputBuffer = inSurf->input_surface;
959
960         nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
961         if (nv_status != NV_ENC_SUCCESS) {
962             av_log(avctx, AV_LOG_ERROR, "Failed locking nvenc input buffer\n");
963             return 0;
964         }
965
966         if (avctx->pix_fmt == AV_PIX_FMT_YUV420P) {
967             uint8_t *buf = lockBufferParams.bufferDataPtr;
968
969             av_image_copy_plane(buf, lockBufferParams.pitch,
970                 frame->data[0], frame->linesize[0],
971                 avctx->width, avctx->height);
972
973             buf += inSurf->height * lockBufferParams.pitch;
974
975             av_image_copy_plane(buf, lockBufferParams.pitch >> 1,
976                 frame->data[2], frame->linesize[2],
977                 avctx->width >> 1, avctx->height >> 1);
978
979             buf += (inSurf->height * lockBufferParams.pitch) >> 2;
980
981             av_image_copy_plane(buf, lockBufferParams.pitch >> 1,
982                 frame->data[1], frame->linesize[1],
983                 avctx->width >> 1, avctx->height >> 1);
984         } else if (avctx->pix_fmt == AV_PIX_FMT_NV12) {
985             uint8_t *buf = lockBufferParams.bufferDataPtr;
986
987             av_image_copy_plane(buf, lockBufferParams.pitch,
988                 frame->data[0], frame->linesize[0],
989                 avctx->width, avctx->height);
990
991             buf += inSurf->height * lockBufferParams.pitch;
992
993             av_image_copy_plane(buf, lockBufferParams.pitch,
994                 frame->data[1], frame->linesize[1],
995                 avctx->width, avctx->height >> 1);
996         } else if (avctx->pix_fmt == AV_PIX_FMT_YUV444P) {
997             uint8_t *buf = lockBufferParams.bufferDataPtr;
998
999             av_image_copy_plane(buf, lockBufferParams.pitch,
1000                 frame->data[0], frame->linesize[0],
1001                 avctx->width, avctx->height);
1002
1003             buf += inSurf->height * lockBufferParams.pitch;
1004
1005             av_image_copy_plane(buf, lockBufferParams.pitch,
1006                 frame->data[1], frame->linesize[1],
1007                 avctx->width, avctx->height);
1008
1009             buf += inSurf->height * lockBufferParams.pitch;
1010
1011             av_image_copy_plane(buf, lockBufferParams.pitch,
1012                 frame->data[2], frame->linesize[2],
1013                 avctx->width, avctx->height);
1014         } else {
1015             av_log(avctx, AV_LOG_FATAL, "Invalid pixel format!\n");
1016             return AVERROR(EINVAL);
1017         }
1018
1019         nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, inSurf->input_surface);
1020         if (nv_status != NV_ENC_SUCCESS) {
1021             av_log(avctx, AV_LOG_FATAL, "Failed unlocking input buffer!\n");
1022             return AVERROR_EXTERNAL;
1023         }
1024
1025         for (i = 0; i < ctx->max_surface_count; ++i)
1026             if (!ctx->output_surfaces[i].busy)
1027                 break;
1028
1029         if (i == ctx->max_surface_count) {
1030             inSurf->lockCount = 0;
1031             av_log(avctx, AV_LOG_FATAL, "No free output surface found!\n");
1032             return AVERROR_EXTERNAL;
1033         }
1034
1035         ctx->output_surfaces[i].input_surface = inSurf;
1036
1037         pic_params.inputBuffer = inSurf->input_surface;
1038         pic_params.bufferFmt = inSurf->format;
1039         pic_params.inputWidth = avctx->width;
1040         pic_params.inputHeight = avctx->height;
1041         pic_params.outputBitstream = ctx->output_surfaces[i].output_surface;
1042         pic_params.completionEvent = 0;
1043
1044         if (avctx->flags & CODEC_FLAG_INTERLACED_DCT) {
1045             if (frame->top_field_first) {
1046                 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
1047             } else {
1048                 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
1049             }
1050         } else {
1051             pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1052         }
1053
1054         pic_params.encodePicFlags = 0;
1055         pic_params.inputTimeStamp = frame->pts;
1056         pic_params.inputDuration = 0;
1057         pic_params.codecPicParams.h264PicParams.sliceMode = ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1058         pic_params.codecPicParams.h264PicParams.sliceModeData = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1059         memcpy(&pic_params.rcParams, &ctx->encode_config.rcParams, sizeof(NV_ENC_RC_PARAMS));
1060
1061         res = timestamp_queue_enqueue(&ctx->timestamp_list, frame->pts);
1062
1063         if (res)
1064             return res;
1065     } else {
1066         pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1067     }
1068
1069     nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
1070
1071     if (frame && nv_status == NV_ENC_ERR_NEED_MORE_INPUT) {
1072         res = out_surf_queue_enqueue(&ctx->output_surface_queue, &ctx->output_surfaces[i]);
1073
1074         if (res)
1075             return res;
1076
1077         ctx->output_surfaces[i].busy = 1;
1078     }
1079
1080     if (nv_status != NV_ENC_SUCCESS && nv_status != NV_ENC_ERR_NEED_MORE_INPUT) {
1081         av_log(avctx, AV_LOG_ERROR, "EncodePicture failed!\n");
1082         return AVERROR_EXTERNAL;
1083     }
1084
1085     if (nv_status != NV_ENC_ERR_NEED_MORE_INPUT) {
1086         while (ctx->output_surface_queue.count) {
1087             tmpoutsurf = out_surf_queue_dequeue(&ctx->output_surface_queue);
1088             res = out_surf_queue_enqueue(&ctx->output_surface_ready_queue, tmpoutsurf);
1089
1090             if (res)
1091                 return res;
1092         }
1093
1094         if (frame) {
1095             res = out_surf_queue_enqueue(&ctx->output_surface_ready_queue, &ctx->output_surfaces[i]);
1096
1097             if (res)
1098                 return res;
1099
1100             ctx->output_surfaces[i].busy = 1;
1101         }
1102     }
1103
1104     if (ctx->output_surface_ready_queue.count) {
1105         tmpoutsurf = out_surf_queue_dequeue(&ctx->output_surface_ready_queue);
1106
1107         res = process_output_surface(avctx, pkt, avctx->coded_frame, tmpoutsurf);
1108
1109         if (res)
1110             return res;
1111
1112         tmpoutsurf->busy = 0;
1113         av_assert0(tmpoutsurf->input_surface->lockCount);
1114         tmpoutsurf->input_surface->lockCount--;
1115
1116         *got_packet = 1;
1117     } else {
1118         *got_packet = 0;
1119     }
1120
1121     return 0;
1122 }
1123
1124 static enum AVPixelFormat pix_fmts_nvenc[] = {
1125     AV_PIX_FMT_NV12,
1126     AV_PIX_FMT_NONE
1127 };
1128
1129 #define OFFSET(x) offsetof(NvencContext, x)
1130 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
1131 static const AVOption options[] = {
1132     { "preset", "Set the encoding preset (one of hq, hp, bd, ll, llhq, llhp, default)", OFFSET(preset), AV_OPT_TYPE_STRING, { .str = "hq" }, 0, 0, VE },
1133     { "cbr", "Use cbr encoding mode", OFFSET(cbr), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
1134     { "2pass", "Use 2pass cbr encoding mode (low latency mode only)", OFFSET(twopass), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, VE },
1135     { "goppattern", "Specifies the GOP pattern as follows: 0: I, 1: IPP, 2: IBP, 3: IBBP", OFFSET(gobpattern), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 3, VE },
1136     { "gpu", "Selects which NVENC capable GPU to use. First GPU is 0, second is 1, and so on.", OFFSET(gpu), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, VE },
1137     { NULL }
1138 };
1139
1140 static const AVClass nvenc_class = {
1141     .class_name = "nvenc",
1142     .item_name = av_default_item_name,
1143     .option = options,
1144     .version = LIBAVUTIL_VERSION_INT,
1145 };
1146
1147 static const AVCodecDefault nvenc_defaults[] = {
1148     { "b", "0" },
1149     { "qmin", "-1" },
1150     { "qmax", "-1" },
1151     { "qdiff", "-1" },
1152     { "qblur", "-1" },
1153     { "qcomp", "-1" },
1154     { NULL },
1155 };
1156
1157 AVCodec ff_nvenc_encoder = {
1158     .name = "nvenc",
1159     .long_name = NULL_IF_CONFIG_SMALL("Nvidia NVENC h264 encoder"),
1160     .type = AVMEDIA_TYPE_VIDEO,
1161     .id = AV_CODEC_ID_H264,
1162     .priv_data_size = sizeof(NvencContext),
1163     .init = nvenc_encode_init,
1164     .encode2 = nvenc_encode_frame,
1165     .close = nvenc_encode_close,
1166     .capabilities = CODEC_CAP_DELAY,
1167     .priv_class = &nvenc_class,
1168     .defaults = nvenc_defaults,
1169     .pix_fmts = pix_fmts_nvenc,
1170 };