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