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