]> git.sesse.net Git - ffmpeg/blob - libavcodec/nvenc.c
Merge commit 'a344e5d094ebcf9a23acf3a27c56cbbbc829db42'
[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 typedef struct NvencInputSurface
71 {
72     NV_ENC_INPUT_PTR input_surface;
73     int width;
74     int height;
75
76     int lockCount;
77
78     NV_ENC_BUFFER_FORMAT format;
79 } NvencInputSurface;
80
81 typedef struct NvencOutputSurface
82 {
83     NV_ENC_OUTPUT_PTR output_surface;
84     int size;
85
86     NvencInputSurface* input_surface;
87
88     int busy;
89 } NvencOutputSurface;
90
91 typedef struct NvencData
92 {
93     union {
94         int64_t timestamp;
95         NvencOutputSurface *surface;
96     } u;
97 } NvencData;
98
99 typedef struct NvencDataList
100 {
101     NvencData* data;
102
103     uint32_t pos;
104     uint32_t count;
105     uint32_t size;
106 } NvencDataList;
107
108 typedef struct NvencDynLoadFunctions
109 {
110     PCUINIT cu_init;
111     PCUDEVICEGETCOUNT cu_device_get_count;
112     PCUDEVICEGET cu_device_get;
113     PCUDEVICEGETNAME cu_device_get_name;
114     PCUDEVICECOMPUTECAPABILITY cu_device_compute_capability;
115     PCUCTXCREATE cu_ctx_create;
116     PCUCTXPOPCURRENT cu_ctx_pop_current;
117     PCUCTXDESTROY cu_ctx_destroy;
118
119     NV_ENCODE_API_FUNCTION_LIST nvenc_funcs;
120     int nvenc_device_count;
121     CUdevice nvenc_devices[16];
122
123 #if defined(_WIN32)
124     HMODULE cuda_lib;
125     HMODULE nvenc_lib;
126 #else
127     void* cuda_lib;
128     void* nvenc_lib;
129 #endif
130 } NvencDynLoadFunctions;
131
132 typedef struct NvencValuePair
133 {
134     const char *str;
135     uint32_t num;
136 } NvencValuePair;
137
138 typedef struct NvencContext
139 {
140     AVClass *avclass;
141
142     NvencDynLoadFunctions nvenc_dload_funcs;
143
144     NV_ENC_INITIALIZE_PARAMS init_encode_params;
145     NV_ENC_CONFIG encode_config;
146     CUcontext cu_context;
147
148     int max_surface_count;
149     NvencInputSurface *input_surfaces;
150     NvencOutputSurface *output_surfaces;
151
152     NvencDataList output_surface_queue;
153     NvencDataList output_surface_ready_queue;
154     NvencDataList timestamp_list;
155     int64_t last_dts;
156
157     void *nvencoder;
158
159     char *preset;
160     char *profile;
161     char *level;
162     char *tier;
163     int cbr;
164     int twopass;
165     int gpu;
166 } NvencContext;
167
168 static const NvencValuePair nvenc_h264_level_pairs[] = {
169     { "auto", NV_ENC_LEVEL_AUTOSELECT },
170     { "1"   , NV_ENC_LEVEL_H264_1     },
171     { "1.0" , NV_ENC_LEVEL_H264_1     },
172     { "1b"  , NV_ENC_LEVEL_H264_1b    },
173     { "1.0b", NV_ENC_LEVEL_H264_1b    },
174     { "1.1" , NV_ENC_LEVEL_H264_11    },
175     { "1.2" , NV_ENC_LEVEL_H264_12    },
176     { "1.3" , NV_ENC_LEVEL_H264_13    },
177     { "2"   , NV_ENC_LEVEL_H264_2     },
178     { "2.0" , NV_ENC_LEVEL_H264_2     },
179     { "2.1" , NV_ENC_LEVEL_H264_21    },
180     { "2.2" , NV_ENC_LEVEL_H264_22    },
181     { "3"   , NV_ENC_LEVEL_H264_3     },
182     { "3.0" , NV_ENC_LEVEL_H264_3     },
183     { "3.1" , NV_ENC_LEVEL_H264_31    },
184     { "3.2" , NV_ENC_LEVEL_H264_32    },
185     { "4"   , NV_ENC_LEVEL_H264_4     },
186     { "4.0" , NV_ENC_LEVEL_H264_4     },
187     { "4.1" , NV_ENC_LEVEL_H264_41    },
188     { "4.2" , NV_ENC_LEVEL_H264_42    },
189     { "5"   , NV_ENC_LEVEL_H264_5     },
190     { "5.0" , NV_ENC_LEVEL_H264_5     },
191     { "5.1" , NV_ENC_LEVEL_H264_51    },
192     { NULL }
193 };
194
195 static const NvencValuePair nvenc_hevc_level_pairs[] = {
196     { "auto", NV_ENC_LEVEL_AUTOSELECT },
197     { "1"   , NV_ENC_LEVEL_HEVC_1     },
198     { "1.0" , NV_ENC_LEVEL_HEVC_1     },
199     { "2"   , NV_ENC_LEVEL_HEVC_2     },
200     { "2.0" , NV_ENC_LEVEL_HEVC_2     },
201     { "2.1" , NV_ENC_LEVEL_HEVC_21    },
202     { "3"   , NV_ENC_LEVEL_HEVC_3     },
203     { "3.0" , NV_ENC_LEVEL_HEVC_3     },
204     { "3.1" , NV_ENC_LEVEL_HEVC_31    },
205     { "4"   , NV_ENC_LEVEL_HEVC_4     },
206     { "4.0" , NV_ENC_LEVEL_HEVC_4     },
207     { "4.1" , NV_ENC_LEVEL_HEVC_41    },
208     { "5"   , NV_ENC_LEVEL_HEVC_5     },
209     { "5.0" , NV_ENC_LEVEL_HEVC_5     },
210     { "5.1" , NV_ENC_LEVEL_HEVC_51    },
211     { "5.2" , NV_ENC_LEVEL_HEVC_52    },
212     { "6"   , NV_ENC_LEVEL_HEVC_6     },
213     { "6.0" , NV_ENC_LEVEL_HEVC_6     },
214     { "6.1" , NV_ENC_LEVEL_HEVC_61    },
215     { "6.2" , NV_ENC_LEVEL_HEVC_62    },
216     { NULL }
217 };
218
219 static int input_string_to_uint32(AVCodecContext *avctx, const NvencValuePair *pair, const char *input, uint32_t *output)
220 {
221     for (; pair->str; ++pair) {
222         if (!strcmp(input, pair->str)) {
223             *output = pair->num;
224             return 0;
225         }
226     }
227
228     return AVERROR(EINVAL);
229 }
230
231 static NvencData* data_queue_dequeue(NvencDataList* queue)
232 {
233     uint32_t mask;
234     uint32_t read_pos;
235
236     av_assert0(queue);
237     av_assert0(queue->size);
238     av_assert0(queue->data);
239
240     if (!queue->count)
241         return NULL;
242
243     /* Size always is a multiple of two */
244     mask = queue->size - 1;
245     read_pos = (queue->pos - queue->count) & mask;
246     queue->count--;
247
248     return &queue->data[read_pos];
249 }
250
251 static int data_queue_enqueue(NvencDataList* queue, NvencData *data)
252 {
253     NvencDataList new_queue;
254     NvencData* tmp_data;
255     uint32_t mask;
256
257     if (!queue->size) {
258         /* size always has to be a multiple of two */
259         queue->size = 4;
260         queue->pos = 0;
261         queue->count = 0;
262
263         queue->data = av_malloc(queue->size * sizeof(*(queue->data)));
264
265         if (!queue->data) {
266             queue->size = 0;
267             return AVERROR(ENOMEM);
268         }
269     }
270
271     if (queue->count == queue->size) {
272         new_queue.size = queue->size << 1;
273         new_queue.pos = 0;
274         new_queue.count = 0;
275         new_queue.data = av_malloc(new_queue.size * sizeof(*(queue->data)));
276
277         if (!new_queue.data)
278             return AVERROR(ENOMEM);
279
280         while (tmp_data = data_queue_dequeue(queue))
281             data_queue_enqueue(&new_queue, tmp_data);
282
283         av_free(queue->data);
284         *queue = new_queue;
285     }
286
287     mask = queue->size - 1;
288
289     queue->data[queue->pos] = *data;
290     queue->pos = (queue->pos + 1) & mask;
291     queue->count++;
292
293     return 0;
294 }
295
296 static int out_surf_queue_enqueue(NvencDataList* queue, NvencOutputSurface* surface)
297 {
298     NvencData data;
299     data.u.surface = surface;
300
301     return data_queue_enqueue(queue, &data);
302 }
303
304 static NvencOutputSurface* out_surf_queue_dequeue(NvencDataList* queue)
305 {
306     NvencData* res = data_queue_dequeue(queue);
307
308     if (!res)
309         return NULL;
310
311     return res->u.surface;
312 }
313
314 static int timestamp_queue_enqueue(NvencDataList* queue, int64_t timestamp)
315 {
316     NvencData data;
317     data.u.timestamp = timestamp;
318
319     return data_queue_enqueue(queue, &data);
320 }
321
322 static int64_t timestamp_queue_dequeue(NvencDataList* queue)
323 {
324     NvencData* res = data_queue_dequeue(queue);
325
326     if (!res)
327         return AV_NOPTS_VALUE;
328
329     return res->u.timestamp;
330 }
331
332 #define CHECK_LOAD_FUNC(t, f, s) \
333 do { \
334     (f) = (t)LOAD_FUNC(dl_fn->cuda_lib, s); \
335     if (!(f)) { \
336         av_log(avctx, AV_LOG_FATAL, "Failed loading %s from CUDA library\n", s); \
337         goto error; \
338     } \
339 } while (0)
340
341 static av_cold int nvenc_dyload_cuda(AVCodecContext *avctx)
342 {
343     NvencContext *ctx = avctx->priv_data;
344     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
345
346     if (dl_fn->cuda_lib)
347         return 1;
348
349 #if defined(_WIN32)
350     dl_fn->cuda_lib = LoadLibrary(TEXT("nvcuda.dll"));
351 #else
352     dl_fn->cuda_lib = dlopen("libcuda.so", RTLD_LAZY);
353 #endif
354
355     if (!dl_fn->cuda_lib) {
356         av_log(avctx, AV_LOG_FATAL, "Failed loading CUDA library\n");
357         goto error;
358     }
359
360     CHECK_LOAD_FUNC(PCUINIT, dl_fn->cu_init, "cuInit");
361     CHECK_LOAD_FUNC(PCUDEVICEGETCOUNT, dl_fn->cu_device_get_count, "cuDeviceGetCount");
362     CHECK_LOAD_FUNC(PCUDEVICEGET, dl_fn->cu_device_get, "cuDeviceGet");
363     CHECK_LOAD_FUNC(PCUDEVICEGETNAME, dl_fn->cu_device_get_name, "cuDeviceGetName");
364     CHECK_LOAD_FUNC(PCUDEVICECOMPUTECAPABILITY, dl_fn->cu_device_compute_capability, "cuDeviceComputeCapability");
365     CHECK_LOAD_FUNC(PCUCTXCREATE, dl_fn->cu_ctx_create, "cuCtxCreate_v2");
366     CHECK_LOAD_FUNC(PCUCTXPOPCURRENT, dl_fn->cu_ctx_pop_current, "cuCtxPopCurrent_v2");
367     CHECK_LOAD_FUNC(PCUCTXDESTROY, dl_fn->cu_ctx_destroy, "cuCtxDestroy_v2");
368
369     return 1;
370
371 error:
372
373     if (dl_fn->cuda_lib)
374         DL_CLOSE_FUNC(dl_fn->cuda_lib);
375
376     dl_fn->cuda_lib = NULL;
377
378     return 0;
379 }
380
381 static av_cold int check_cuda_errors(AVCodecContext *avctx, CUresult err, const char *func)
382 {
383     if (err != CUDA_SUCCESS) {
384         av_log(avctx, AV_LOG_FATAL, ">> %s - failed with error code 0x%x\n", func, err);
385         return 0;
386     }
387     return 1;
388 }
389 #define check_cuda_errors(f) if (!check_cuda_errors(avctx, f, #f)) goto error
390
391 static av_cold int nvenc_check_cuda(AVCodecContext *avctx)
392 {
393     int device_count = 0;
394     CUdevice cu_device = 0;
395     char gpu_name[128];
396     int smminor = 0, smmajor = 0;
397     int i, smver, target_smver;
398
399     NvencContext *ctx = avctx->priv_data;
400     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
401
402     switch (avctx->codec->id) {
403     case AV_CODEC_ID_H264:
404         target_smver = avctx->pix_fmt == AV_PIX_FMT_YUV444P ? 0x52 : 0x30;
405         break;
406     case AV_CODEC_ID_H265:
407         target_smver = 0x52;
408         break;
409     default:
410         av_log(avctx, AV_LOG_FATAL, "nvenc: Unknown codec name\n");
411         goto error;
412     }
413
414     if (!nvenc_dyload_cuda(avctx))
415         return 0;
416
417     if (dl_fn->nvenc_device_count > 0)
418         return 1;
419
420     check_cuda_errors(dl_fn->cu_init(0));
421
422     check_cuda_errors(dl_fn->cu_device_get_count(&device_count));
423
424     if (!device_count) {
425         av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
426         goto error;
427     }
428
429     av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", device_count);
430
431     dl_fn->nvenc_device_count = 0;
432
433     for (i = 0; i < device_count; ++i) {
434         check_cuda_errors(dl_fn->cu_device_get(&cu_device, i));
435         check_cuda_errors(dl_fn->cu_device_get_name(gpu_name, sizeof(gpu_name), cu_device));
436         check_cuda_errors(dl_fn->cu_device_compute_capability(&smmajor, &smminor, cu_device));
437
438         smver = (smmajor << 4) | smminor;
439
440         av_log(avctx, AV_LOG_VERBOSE, "[ GPU #%d - < %s > has Compute SM %d.%d, NVENC %s ]\n", i, gpu_name, smmajor, smminor, (smver >= target_smver) ? "Available" : "Not Available");
441
442         if (smver >= target_smver)
443             dl_fn->nvenc_devices[dl_fn->nvenc_device_count++] = cu_device;
444     }
445
446     if (!dl_fn->nvenc_device_count) {
447         av_log(avctx, AV_LOG_FATAL, "No NVENC capable devices found\n");
448         goto error;
449     }
450
451     return 1;
452
453 error:
454
455     dl_fn->nvenc_device_count = 0;
456
457     return 0;
458 }
459
460 static av_cold int nvenc_dyload_nvenc(AVCodecContext *avctx)
461 {
462     PNVENCODEAPICREATEINSTANCE nvEncodeAPICreateInstance = 0;
463     NVENCSTATUS nvstatus;
464
465     NvencContext *ctx = avctx->priv_data;
466     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
467
468     if (!nvenc_check_cuda(avctx))
469         return 0;
470
471     if (dl_fn->nvenc_lib)
472         return 1;
473
474 #if defined(_WIN32)
475     if (sizeof(void*) == 8) {
476         dl_fn->nvenc_lib = LoadLibrary(TEXT("nvEncodeAPI64.dll"));
477     } else {
478         dl_fn->nvenc_lib = LoadLibrary(TEXT("nvEncodeAPI.dll"));
479     }
480 #else
481     dl_fn->nvenc_lib = dlopen("libnvidia-encode.so.1", RTLD_LAZY);
482 #endif
483
484     if (!dl_fn->nvenc_lib) {
485         av_log(avctx, AV_LOG_FATAL, "Failed loading the nvenc library\n");
486         goto error;
487     }
488
489     nvEncodeAPICreateInstance = (PNVENCODEAPICREATEINSTANCE)LOAD_FUNC(dl_fn->nvenc_lib, "NvEncodeAPICreateInstance");
490
491     if (!nvEncodeAPICreateInstance) {
492         av_log(avctx, AV_LOG_FATAL, "Failed to load nvenc entrypoint\n");
493         goto error;
494     }
495
496     dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
497
498     nvstatus = nvEncodeAPICreateInstance(&dl_fn->nvenc_funcs);
499
500     if (nvstatus != NV_ENC_SUCCESS) {
501         av_log(avctx, AV_LOG_FATAL, "Failed to create nvenc instance\n");
502         goto error;
503     }
504
505     av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
506
507     return 1;
508
509 error:
510     if (dl_fn->nvenc_lib)
511         DL_CLOSE_FUNC(dl_fn->nvenc_lib);
512
513     dl_fn->nvenc_lib = NULL;
514
515     return 0;
516 }
517
518 static av_cold void nvenc_unload_nvenc(AVCodecContext *avctx)
519 {
520     NvencContext *ctx = avctx->priv_data;
521     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
522
523     DL_CLOSE_FUNC(dl_fn->nvenc_lib);
524     dl_fn->nvenc_lib = NULL;
525
526     dl_fn->nvenc_device_count = 0;
527
528     DL_CLOSE_FUNC(dl_fn->cuda_lib);
529     dl_fn->cuda_lib = NULL;
530
531     dl_fn->cu_init = NULL;
532     dl_fn->cu_device_get_count = NULL;
533     dl_fn->cu_device_get = NULL;
534     dl_fn->cu_device_get_name = NULL;
535     dl_fn->cu_device_compute_capability = NULL;
536     dl_fn->cu_ctx_create = NULL;
537     dl_fn->cu_ctx_pop_current = NULL;
538     dl_fn->cu_ctx_destroy = NULL;
539
540     av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
541 }
542
543 static av_cold int nvenc_encode_init(AVCodecContext *avctx)
544 {
545     NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS encode_session_params = { 0 };
546     NV_ENC_PRESET_CONFIG preset_config = { 0 };
547     CUcontext cu_context_curr;
548     CUresult cu_res;
549     GUID encoder_preset = NV_ENC_PRESET_HQ_GUID;
550     GUID codec;
551     NVENCSTATUS nv_status = NV_ENC_SUCCESS;
552     int surfaceCount = 0;
553     int i, num_mbs;
554     int isLL = 0;
555     int lossless = 0;
556     int res = 0;
557     int dw, dh;
558
559     NvencContext *ctx = avctx->priv_data;
560     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
561     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
562
563     if (!nvenc_dyload_nvenc(avctx))
564         return AVERROR_EXTERNAL;
565
566     avctx->coded_frame = av_frame_alloc();
567     if (!avctx->coded_frame) {
568         res = AVERROR(ENOMEM);
569         goto error;
570     }
571
572     ctx->last_dts = AV_NOPTS_VALUE;
573
574     ctx->encode_config.version = NV_ENC_CONFIG_VER;
575     ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
576     preset_config.version = NV_ENC_PRESET_CONFIG_VER;
577     preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
578     encode_session_params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
579     encode_session_params.apiVersion = NVENCAPI_VERSION;
580
581     if (ctx->gpu >= dl_fn->nvenc_device_count) {
582         av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->gpu, dl_fn->nvenc_device_count);
583         res = AVERROR(EINVAL);
584         goto error;
585     }
586
587     ctx->cu_context = NULL;
588     cu_res = dl_fn->cu_ctx_create(&ctx->cu_context, 0, dl_fn->nvenc_devices[ctx->gpu]);
589
590     if (cu_res != CUDA_SUCCESS) {
591         av_log(avctx, AV_LOG_FATAL, "Failed creating CUDA context for NVENC: 0x%x\n", (int)cu_res);
592         res = AVERROR_EXTERNAL;
593         goto error;
594     }
595
596     cu_res = dl_fn->cu_ctx_pop_current(&cu_context_curr);
597
598     if (cu_res != CUDA_SUCCESS) {
599         av_log(avctx, AV_LOG_FATAL, "Failed popping CUDA context: 0x%x\n", (int)cu_res);
600         res = AVERROR_EXTERNAL;
601         goto error;
602     }
603
604     encode_session_params.device = ctx->cu_context;
605     encode_session_params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
606
607     nv_status = p_nvenc->nvEncOpenEncodeSessionEx(&encode_session_params, &ctx->nvencoder);
608     if (nv_status != NV_ENC_SUCCESS) {
609         ctx->nvencoder = NULL;
610         av_log(avctx, AV_LOG_FATAL, "OpenEncodeSessionEx failed: 0x%x - invalid license key?\n", (int)nv_status);
611         res = AVERROR_EXTERNAL;
612         goto error;
613     }
614
615     if (ctx->preset) {
616         if (!strcmp(ctx->preset, "hp")) {
617             encoder_preset = NV_ENC_PRESET_HP_GUID;
618         } else if (!strcmp(ctx->preset, "hq")) {
619             encoder_preset = NV_ENC_PRESET_HQ_GUID;
620         } else if (!strcmp(ctx->preset, "bd")) {
621             encoder_preset = NV_ENC_PRESET_BD_GUID;
622         } else if (!strcmp(ctx->preset, "ll")) {
623             encoder_preset = NV_ENC_PRESET_LOW_LATENCY_DEFAULT_GUID;
624             isLL = 1;
625         } else if (!strcmp(ctx->preset, "llhp")) {
626             encoder_preset = NV_ENC_PRESET_LOW_LATENCY_HP_GUID;
627             isLL = 1;
628         } else if (!strcmp(ctx->preset, "llhq")) {
629             encoder_preset = NV_ENC_PRESET_LOW_LATENCY_HQ_GUID;
630             isLL = 1;
631         } else if (!strcmp(ctx->preset, "lossless")) {
632             encoder_preset = NV_ENC_PRESET_LOSSLESS_DEFAULT_GUID;
633             lossless = 1;
634         } else if (!strcmp(ctx->preset, "losslesshp")) {
635             encoder_preset = NV_ENC_PRESET_LOSSLESS_HP_GUID;
636             lossless = 1;
637         } else if (!strcmp(ctx->preset, "default")) {
638             encoder_preset = NV_ENC_PRESET_DEFAULT_GUID;
639         } else {
640             av_log(avctx, AV_LOG_FATAL, "Preset \"%s\" is unknown! Supported presets: hp, hq, bd, ll, llhp, llhq, lossless, losslesshp, default\n", ctx->preset);
641             res = AVERROR(EINVAL);
642             goto error;
643         }
644     }
645
646     switch (avctx->codec->id) {
647     case AV_CODEC_ID_H264:
648         codec = NV_ENC_CODEC_H264_GUID;
649         break;
650     case AV_CODEC_ID_H265:
651         codec = NV_ENC_CODEC_HEVC_GUID;
652         break;
653     default:
654         av_log(avctx, AV_LOG_ERROR, "nvenc: Unknown codec name\n");
655         res = AVERROR(EINVAL);
656         goto error;
657     }
658
659     nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder, codec, encoder_preset, &preset_config);
660     if (nv_status != NV_ENC_SUCCESS) {
661         av_log(avctx, AV_LOG_FATAL, "GetEncodePresetConfig failed: 0x%x\n", (int)nv_status);
662         res = AVERROR_EXTERNAL;
663         goto error;
664     }
665
666     ctx->init_encode_params.encodeGUID = codec;
667     ctx->init_encode_params.encodeHeight = avctx->height;
668     ctx->init_encode_params.encodeWidth = avctx->width;
669
670     if (avctx->sample_aspect_ratio.num && avctx->sample_aspect_ratio.den &&
671         (avctx->sample_aspect_ratio.num != 1 || avctx->sample_aspect_ratio.num != 1)) {
672         av_reduce(&dw, &dh,
673                   avctx->width * avctx->sample_aspect_ratio.num,
674                   avctx->height * avctx->sample_aspect_ratio.den,
675                   1024 * 1024);
676         ctx->init_encode_params.darHeight = dh;
677         ctx->init_encode_params.darWidth = dw;
678     } else {
679         ctx->init_encode_params.darHeight = avctx->height;
680         ctx->init_encode_params.darWidth = avctx->width;
681     }
682
683     // De-compensate for hardware, dubiously, trying to compensate for
684     // playback at 704 pixel width.
685     if (avctx->width == 720 &&
686         (avctx->height == 480 || avctx->height == 576)) {
687         av_reduce(&dw, &dh,
688                   ctx->init_encode_params.darWidth * 44,
689                   ctx->init_encode_params.darHeight * 45,
690                   1024 * 1024);
691         ctx->init_encode_params.darHeight = dh;
692         ctx->init_encode_params.darWidth = dw;
693     }
694
695     ctx->init_encode_params.frameRateNum = avctx->time_base.den;
696     ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
697
698     num_mbs = ((avctx->width + 15) >> 4) * ((avctx->height + 15) >> 4);
699     ctx->max_surface_count = (num_mbs >= 8160) ? 32 : 48;
700
701     ctx->init_encode_params.enableEncodeAsync = 0;
702     ctx->init_encode_params.enablePTD = 1;
703
704     ctx->init_encode_params.presetGUID = encoder_preset;
705
706     ctx->init_encode_params.encodeConfig = &ctx->encode_config;
707     memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
708     ctx->encode_config.version = NV_ENC_CONFIG_VER;
709
710     if (avctx->refs >= 0) {
711         /* 0 means "let the hardware decide" */
712         switch (avctx->codec->id) {
713         case AV_CODEC_ID_H264:
714             ctx->encode_config.encodeCodecConfig.h264Config.maxNumRefFrames = avctx->refs;
715             break;
716         case AV_CODEC_ID_H265:
717             ctx->encode_config.encodeCodecConfig.hevcConfig.maxNumRefFramesInDPB = avctx->refs;
718             break;
719         /* Earlier switch/case will return if unknown codec is passed. */
720         }
721     }
722
723     if (avctx->gop_size > 0) {
724         if (avctx->max_b_frames >= 0) {
725             /* 0 is intra-only, 1 is I/P only, 2 is one B Frame, 3 two B frames, and so on. */
726             ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
727         }
728
729         ctx->encode_config.gopLength = avctx->gop_size;
730         switch (avctx->codec->id) {
731         case AV_CODEC_ID_H264:
732             ctx->encode_config.encodeCodecConfig.h264Config.idrPeriod = avctx->gop_size;
733             break;
734         case AV_CODEC_ID_H265:
735             ctx->encode_config.encodeCodecConfig.hevcConfig.idrPeriod = avctx->gop_size;
736             break;
737         /* Earlier switch/case will return if unknown codec is passed. */
738         }
739     } else if (avctx->gop_size == 0) {
740         ctx->encode_config.frameIntervalP = 0;
741         ctx->encode_config.gopLength = 1;
742         switch (avctx->codec->id) {
743         case AV_CODEC_ID_H264:
744             ctx->encode_config.encodeCodecConfig.h264Config.idrPeriod = 1;
745             break;
746         case AV_CODEC_ID_H265:
747             ctx->encode_config.encodeCodecConfig.hevcConfig.idrPeriod = 1;
748             break;
749         /* Earlier switch/case will return if unknown codec is passed. */
750         }
751     }
752
753     /* when there're b frames, set dts offset */
754     if (ctx->encode_config.frameIntervalP >= 2)
755         ctx->last_dts = -2;
756
757     if (avctx->bit_rate > 0)
758         ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
759
760     if (avctx->rc_max_rate > 0)
761         ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
762
763     if (lossless) {
764       ctx->encode_config.encodeCodecConfig.h264Config.qpPrimeYZeroTransformBypassFlag = 1;
765       ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
766       ctx->encode_config.rcParams.constQP.qpInterB = 0;
767       ctx->encode_config.rcParams.constQP.qpInterP = 0;
768       ctx->encode_config.rcParams.constQP.qpIntra = 0;
769
770       avctx->qmin = -1;
771       avctx->qmax = -1;
772     } else if (ctx->cbr) {
773         if (!ctx->twopass) {
774             ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CBR;
775         } else if (ctx->twopass == 1 || isLL) {
776             ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_2_PASS_QUALITY;
777
778             if (avctx->codec->id == AV_CODEC_ID_H264) {
779                 ctx->encode_config.encodeCodecConfig.h264Config.adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
780                 ctx->encode_config.encodeCodecConfig.h264Config.fmoMode = NV_ENC_H264_FMO_DISABLE;
781             }
782
783             if (!isLL)
784                 av_log(avctx, AV_LOG_WARNING, "Twopass mode is only known to work with low latency (ll, llhq, llhp) presets.\n");
785         } else {
786             ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CBR;
787         }
788     } else if (avctx->global_quality > 0) {
789         ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
790         ctx->encode_config.rcParams.constQP.qpInterB = avctx->global_quality;
791         ctx->encode_config.rcParams.constQP.qpInterP = avctx->global_quality;
792         ctx->encode_config.rcParams.constQP.qpIntra = avctx->global_quality;
793
794         avctx->qmin = -1;
795         avctx->qmax = -1;
796     } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
797         ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
798
799         ctx->encode_config.rcParams.enableMinQP = 1;
800         ctx->encode_config.rcParams.enableMaxQP = 1;
801
802         ctx->encode_config.rcParams.minQP.qpInterB = avctx->qmin;
803         ctx->encode_config.rcParams.minQP.qpInterP = avctx->qmin;
804         ctx->encode_config.rcParams.minQP.qpIntra = avctx->qmin;
805
806         ctx->encode_config.rcParams.maxQP.qpInterB = avctx->qmax;
807         ctx->encode_config.rcParams.maxQP.qpInterP = avctx->qmax;
808         ctx->encode_config.rcParams.maxQP.qpIntra = avctx->qmax;
809     }
810
811     if (avctx->rc_buffer_size > 0)
812         ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
813
814     if (avctx->flags & CODEC_FLAG_INTERLACED_DCT) {
815         ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
816     } else {
817         ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
818     }
819
820     switch (avctx->codec->id) {
821     case AV_CODEC_ID_H264:
822         ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.colourDescriptionPresentFlag = 1;
823         ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.videoSignalTypePresentFlag = 1;
824
825         ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.colourMatrix = avctx->colorspace;
826         ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.colourPrimaries = avctx->color_primaries;
827         ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.transferCharacteristics = avctx->color_trc;
828
829         ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.videoFullRangeFlag = avctx->color_range == AVCOL_RANGE_JPEG;
830
831         ctx->encode_config.encodeCodecConfig.h264Config.disableSPSPPS = (avctx->flags & CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
832         ctx->encode_config.encodeCodecConfig.h264Config.repeatSPSPPS = (avctx->flags & CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
833
834         if (!ctx->profile) {
835             switch (avctx->profile) {
836             case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
837                 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
838                 break;
839             case FF_PROFILE_H264_BASELINE:
840                 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
841                 break;
842             case FF_PROFILE_H264_MAIN:
843                 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
844                 break;
845             case FF_PROFILE_H264_HIGH:
846             case FF_PROFILE_UNKNOWN:
847                 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
848                 break;
849             default:
850                 av_log(avctx, AV_LOG_WARNING, "Unsupported profile requested, falling back to high\n");
851                 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
852                 break;
853             }
854         } else {
855             if (!strcmp(ctx->profile, "high")) {
856                 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
857                 avctx->profile = FF_PROFILE_H264_HIGH;
858             } else if (!strcmp(ctx->profile, "main")) {
859                 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
860                 avctx->profile = FF_PROFILE_H264_MAIN;
861             } else if (!strcmp(ctx->profile, "baseline")) {
862                 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
863                 avctx->profile = FF_PROFILE_H264_BASELINE;
864             } else if (!strcmp(ctx->profile, "high444p")) {
865                 ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
866                 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
867             } else {
868                 av_log(avctx, AV_LOG_FATAL, "Profile \"%s\" is unknown! Supported profiles: high, main, baseline\n", ctx->profile);
869                 res = AVERROR(EINVAL);
870                 goto error;
871             }
872         }
873
874         ctx->encode_config.encodeCodecConfig.h264Config.chromaFormatIDC = avctx->profile == FF_PROFILE_H264_HIGH_444_PREDICTIVE ? 3 : 1;
875
876         if (ctx->level) {
877             res = input_string_to_uint32(avctx, nvenc_h264_level_pairs, ctx->level, &ctx->encode_config.encodeCodecConfig.h264Config.level);
878
879             if (res) {
880                 av_log(avctx, AV_LOG_FATAL, "Level \"%s\" is unknown! Supported levels: auto, 1, 1b, 1.1, 1.2, 1.3, 2, 2.1, 2.2, 3, 3.1, 3.2, 4, 4.1, 4.2, 5, 5.1\n", ctx->level);
881                 goto error;
882             }
883         } else {
884             ctx->encode_config.encodeCodecConfig.h264Config.level = NV_ENC_LEVEL_AUTOSELECT;
885         }
886
887         break;
888     case AV_CODEC_ID_H265:
889         ctx->encode_config.encodeCodecConfig.hevcConfig.disableSPSPPS = (avctx->flags & CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
890         ctx->encode_config.encodeCodecConfig.hevcConfig.repeatSPSPPS = (avctx->flags & CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
891
892         /* No other profile is supported in the current SDK version 5 */
893         ctx->encode_config.profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
894         avctx->profile = FF_PROFILE_HEVC_MAIN;
895
896         if (ctx->level) {
897             res = input_string_to_uint32(avctx, nvenc_hevc_level_pairs, ctx->level, &ctx->encode_config.encodeCodecConfig.hevcConfig.level);
898
899             if (res) {
900                 av_log(avctx, AV_LOG_FATAL, "Level \"%s\" is unknown! Supported levels: auto, 1, 2, 2.1, 3, 3.1, 4, 4.1, 5, 5.1, 5.2, 6, 6.1, 6.2\n", ctx->level);
901                 goto error;
902             }
903         } else {
904             ctx->encode_config.encodeCodecConfig.hevcConfig.level = NV_ENC_LEVEL_AUTOSELECT;
905         }
906
907         if (ctx->tier) {
908             if (!strcmp(ctx->tier, "main")) {
909                 ctx->encode_config.encodeCodecConfig.hevcConfig.tier = NV_ENC_TIER_HEVC_MAIN;
910             } else if (!strcmp(ctx->tier, "high")) {
911                 ctx->encode_config.encodeCodecConfig.hevcConfig.tier = NV_ENC_TIER_HEVC_HIGH;
912             } else {
913                 av_log(avctx, AV_LOG_FATAL, "Tier \"%s\" is unknown! Supported tiers: main, high\n", ctx->tier);
914                 res = AVERROR(EINVAL);
915                 goto error;
916             }
917         }
918
919         break;
920     /* Earlier switch/case will return if unknown codec is passed. */
921     }
922
923     nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
924     if (nv_status != NV_ENC_SUCCESS) {
925         av_log(avctx, AV_LOG_FATAL, "InitializeEncoder failed: 0x%x\n", (int)nv_status);
926         res = AVERROR_EXTERNAL;
927         goto error;
928     }
929
930     ctx->input_surfaces = av_malloc(ctx->max_surface_count * sizeof(*ctx->input_surfaces));
931
932     if (!ctx->input_surfaces) {
933         res = AVERROR(ENOMEM);
934         goto error;
935     }
936
937     ctx->output_surfaces = av_malloc(ctx->max_surface_count * sizeof(*ctx->output_surfaces));
938
939     if (!ctx->output_surfaces) {
940         res = AVERROR(ENOMEM);
941         goto error;
942     }
943
944     for (surfaceCount = 0; surfaceCount < ctx->max_surface_count; ++surfaceCount) {
945         NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
946         NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
947         allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
948         allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
949
950         allocSurf.width = (avctx->width + 31) & ~31;
951         allocSurf.height = (avctx->height + 31) & ~31;
952
953         allocSurf.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
954
955         switch (avctx->pix_fmt) {
956         case AV_PIX_FMT_YUV420P:
957             allocSurf.bufferFmt = NV_ENC_BUFFER_FORMAT_YV12_PL;
958             break;
959
960         case AV_PIX_FMT_NV12:
961             allocSurf.bufferFmt = NV_ENC_BUFFER_FORMAT_NV12_PL;
962             break;
963
964         case AV_PIX_FMT_YUV444P:
965             allocSurf.bufferFmt = NV_ENC_BUFFER_FORMAT_YUV444_PL;
966             break;
967
968         default:
969             av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format\n");
970             res = AVERROR(EINVAL);
971             goto error;
972         }
973
974         nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
975         if (nv_status != NV_ENC_SUCCESS) {
976             av_log(avctx, AV_LOG_FATAL, "CreateInputBuffer failed\n");
977             res = AVERROR_EXTERNAL;
978             goto error;
979         }
980
981         ctx->input_surfaces[surfaceCount].lockCount = 0;
982         ctx->input_surfaces[surfaceCount].input_surface = allocSurf.inputBuffer;
983         ctx->input_surfaces[surfaceCount].format = allocSurf.bufferFmt;
984         ctx->input_surfaces[surfaceCount].width = allocSurf.width;
985         ctx->input_surfaces[surfaceCount].height = allocSurf.height;
986
987         /* 1MB is large enough to hold most output frames. NVENC increases this automaticaly if it's not enough. */
988         allocOut.size = 1024 * 1024;
989
990         allocOut.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
991
992         nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
993         if (nv_status != NV_ENC_SUCCESS) {
994             av_log(avctx, AV_LOG_FATAL, "CreateBitstreamBuffer failed\n");
995             ctx->output_surfaces[surfaceCount++].output_surface = NULL;
996             res = AVERROR_EXTERNAL;
997             goto error;
998         }
999
1000         ctx->output_surfaces[surfaceCount].output_surface = allocOut.bitstreamBuffer;
1001         ctx->output_surfaces[surfaceCount].size = allocOut.size;
1002         ctx->output_surfaces[surfaceCount].busy = 0;
1003     }
1004
1005     if (avctx->flags & CODEC_FLAG_GLOBAL_HEADER) {
1006         uint32_t outSize = 0;
1007         char tmpHeader[256];
1008         NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1009         payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1010
1011         payload.spsppsBuffer = tmpHeader;
1012         payload.inBufferSize = sizeof(tmpHeader);
1013         payload.outSPSPPSPayloadSize = &outSize;
1014
1015         nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
1016         if (nv_status != NV_ENC_SUCCESS) {
1017             av_log(avctx, AV_LOG_FATAL, "GetSequenceParams failed\n");
1018             goto error;
1019         }
1020
1021         avctx->extradata_size = outSize;
1022         avctx->extradata = av_mallocz(outSize + FF_INPUT_BUFFER_PADDING_SIZE);
1023
1024         if (!avctx->extradata) {
1025             res = AVERROR(ENOMEM);
1026             goto error;
1027         }
1028
1029         memcpy(avctx->extradata, tmpHeader, outSize);
1030     }
1031
1032     if (ctx->encode_config.frameIntervalP > 1)
1033         avctx->has_b_frames = 2;
1034
1035     if (ctx->encode_config.rcParams.averageBitRate > 0)
1036         avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
1037
1038     return 0;
1039
1040 error:
1041
1042     for (i = 0; i < surfaceCount; ++i) {
1043         p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->input_surfaces[i].input_surface);
1044         if (ctx->output_surfaces[i].output_surface)
1045             p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->output_surfaces[i].output_surface);
1046     }
1047
1048     if (ctx->nvencoder)
1049         p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1050
1051     if (ctx->cu_context)
1052         dl_fn->cu_ctx_destroy(ctx->cu_context);
1053
1054     av_frame_free(&avctx->coded_frame);
1055
1056     nvenc_unload_nvenc(avctx);
1057
1058     ctx->nvencoder = NULL;
1059     ctx->cu_context = NULL;
1060
1061     return res;
1062 }
1063
1064 static av_cold int nvenc_encode_close(AVCodecContext *avctx)
1065 {
1066     NvencContext *ctx = avctx->priv_data;
1067     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1068     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1069     int i;
1070
1071     av_freep(&ctx->timestamp_list.data);
1072     av_freep(&ctx->output_surface_ready_queue.data);
1073     av_freep(&ctx->output_surface_queue.data);
1074
1075     for (i = 0; i < ctx->max_surface_count; ++i) {
1076         p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->input_surfaces[i].input_surface);
1077         p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->output_surfaces[i].output_surface);
1078     }
1079     ctx->max_surface_count = 0;
1080
1081     p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1082     ctx->nvencoder = NULL;
1083
1084     dl_fn->cu_ctx_destroy(ctx->cu_context);
1085     ctx->cu_context = NULL;
1086
1087     nvenc_unload_nvenc(avctx);
1088
1089     av_frame_free(&avctx->coded_frame);
1090
1091     return 0;
1092 }
1093
1094 static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, AVFrame *coded_frame, NvencOutputSurface *tmpoutsurf)
1095 {
1096     NvencContext *ctx = avctx->priv_data;
1097     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1098     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1099
1100     uint32_t slice_mode_data;
1101     uint32_t *slice_offsets;
1102     NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1103     NVENCSTATUS nv_status;
1104     int res = 0;
1105
1106     switch (avctx->codec->id) {
1107     case AV_CODEC_ID_H264:
1108       slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1109       break;
1110     case AV_CODEC_ID_H265:
1111       slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1112       break;
1113     default:
1114       av_log(avctx, AV_LOG_ERROR, "nvenc: Unknown codec name\n");
1115       res = AVERROR(EINVAL);
1116       goto error;
1117     }
1118     slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
1119
1120     if (!slice_offsets)
1121         return AVERROR(ENOMEM);
1122
1123     lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1124
1125     lock_params.doNotWait = 0;
1126     lock_params.outputBitstream = tmpoutsurf->output_surface;
1127     lock_params.sliceOffsets = slice_offsets;
1128
1129     nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
1130     if (nv_status != NV_ENC_SUCCESS) {
1131         av_log(avctx, AV_LOG_ERROR, "Failed locking bitstream buffer\n");
1132         res = AVERROR_EXTERNAL;
1133         goto error;
1134     }
1135
1136     if (res = ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes)) {
1137         p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1138         goto error;
1139     }
1140
1141     memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1142
1143     nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1144     if (nv_status != NV_ENC_SUCCESS)
1145         av_log(avctx, AV_LOG_ERROR, "Failed unlocking bitstream buffer, expect the gates of mordor to open\n");
1146
1147     switch (lock_params.pictureType) {
1148     case NV_ENC_PIC_TYPE_IDR:
1149         pkt->flags |= AV_PKT_FLAG_KEY;
1150     case NV_ENC_PIC_TYPE_I:
1151         avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
1152         break;
1153     case NV_ENC_PIC_TYPE_P:
1154         avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
1155         break;
1156     case NV_ENC_PIC_TYPE_B:
1157         avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;
1158         break;
1159     case NV_ENC_PIC_TYPE_BI:
1160         avctx->coded_frame->pict_type = AV_PICTURE_TYPE_BI;
1161         break;
1162     default:
1163         av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
1164         av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
1165         res = AVERROR_EXTERNAL;
1166         goto error;
1167     }
1168
1169     pkt->pts = lock_params.outputTimeStamp;
1170     pkt->dts = timestamp_queue_dequeue(&ctx->timestamp_list);
1171
1172     /* when there're b frame(s), set dts offset */
1173     if (ctx->encode_config.frameIntervalP >= 2)
1174         pkt->dts -= 1;
1175
1176     if (pkt->dts > pkt->pts)
1177         pkt->dts = pkt->pts;
1178
1179     if (ctx->last_dts != AV_NOPTS_VALUE && pkt->dts <= ctx->last_dts)
1180         pkt->dts = ctx->last_dts + 1;
1181
1182     ctx->last_dts = pkt->dts;
1183
1184     av_free(slice_offsets);
1185
1186     return 0;
1187
1188 error:
1189
1190     av_free(slice_offsets);
1191     timestamp_queue_dequeue(&ctx->timestamp_list);
1192
1193     return res;
1194 }
1195
1196 static int nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1197     const AVFrame *frame, int *got_packet)
1198 {
1199     NVENCSTATUS nv_status;
1200     NvencOutputSurface *tmpoutsurf;
1201     int res, i = 0;
1202
1203     NvencContext *ctx = avctx->priv_data;
1204     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1205     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1206
1207     NV_ENC_PIC_PARAMS pic_params = { 0 };
1208     pic_params.version = NV_ENC_PIC_PARAMS_VER;
1209
1210     if (frame) {
1211         NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1212         NvencInputSurface *inSurf = NULL;
1213
1214         for (i = 0; i < ctx->max_surface_count; ++i) {
1215             if (!ctx->input_surfaces[i].lockCount) {
1216                 inSurf = &ctx->input_surfaces[i];
1217                 break;
1218             }
1219         }
1220
1221         av_assert0(inSurf);
1222
1223         inSurf->lockCount = 1;
1224
1225         lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1226         lockBufferParams.inputBuffer = inSurf->input_surface;
1227
1228         nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
1229         if (nv_status != NV_ENC_SUCCESS) {
1230             av_log(avctx, AV_LOG_ERROR, "Failed locking nvenc input buffer\n");
1231             return 0;
1232         }
1233
1234         if (avctx->pix_fmt == AV_PIX_FMT_YUV420P) {
1235             uint8_t *buf = lockBufferParams.bufferDataPtr;
1236
1237             av_image_copy_plane(buf, lockBufferParams.pitch,
1238                 frame->data[0], frame->linesize[0],
1239                 avctx->width, avctx->height);
1240
1241             buf += inSurf->height * lockBufferParams.pitch;
1242
1243             av_image_copy_plane(buf, lockBufferParams.pitch >> 1,
1244                 frame->data[2], frame->linesize[2],
1245                 avctx->width >> 1, avctx->height >> 1);
1246
1247             buf += (inSurf->height * lockBufferParams.pitch) >> 2;
1248
1249             av_image_copy_plane(buf, lockBufferParams.pitch >> 1,
1250                 frame->data[1], frame->linesize[1],
1251                 avctx->width >> 1, avctx->height >> 1);
1252         } else if (avctx->pix_fmt == AV_PIX_FMT_NV12) {
1253             uint8_t *buf = lockBufferParams.bufferDataPtr;
1254
1255             av_image_copy_plane(buf, lockBufferParams.pitch,
1256                 frame->data[0], frame->linesize[0],
1257                 avctx->width, avctx->height);
1258
1259             buf += inSurf->height * lockBufferParams.pitch;
1260
1261             av_image_copy_plane(buf, lockBufferParams.pitch,
1262                 frame->data[1], frame->linesize[1],
1263                 avctx->width, avctx->height >> 1);
1264         } else if (avctx->pix_fmt == AV_PIX_FMT_YUV444P) {
1265             uint8_t *buf = lockBufferParams.bufferDataPtr;
1266
1267             av_image_copy_plane(buf, lockBufferParams.pitch,
1268                 frame->data[0], frame->linesize[0],
1269                 avctx->width, avctx->height);
1270
1271             buf += inSurf->height * lockBufferParams.pitch;
1272
1273             av_image_copy_plane(buf, lockBufferParams.pitch,
1274                 frame->data[1], frame->linesize[1],
1275                 avctx->width, avctx->height);
1276
1277             buf += inSurf->height * lockBufferParams.pitch;
1278
1279             av_image_copy_plane(buf, lockBufferParams.pitch,
1280                 frame->data[2], frame->linesize[2],
1281                 avctx->width, avctx->height);
1282         } else {
1283             av_log(avctx, AV_LOG_FATAL, "Invalid pixel format!\n");
1284             return AVERROR(EINVAL);
1285         }
1286
1287         nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, inSurf->input_surface);
1288         if (nv_status != NV_ENC_SUCCESS) {
1289             av_log(avctx, AV_LOG_FATAL, "Failed unlocking input buffer!\n");
1290             return AVERROR_EXTERNAL;
1291         }
1292
1293         for (i = 0; i < ctx->max_surface_count; ++i)
1294             if (!ctx->output_surfaces[i].busy)
1295                 break;
1296
1297         if (i == ctx->max_surface_count) {
1298             inSurf->lockCount = 0;
1299             av_log(avctx, AV_LOG_FATAL, "No free output surface found!\n");
1300             return AVERROR_EXTERNAL;
1301         }
1302
1303         ctx->output_surfaces[i].input_surface = inSurf;
1304
1305         pic_params.inputBuffer = inSurf->input_surface;
1306         pic_params.bufferFmt = inSurf->format;
1307         pic_params.inputWidth = avctx->width;
1308         pic_params.inputHeight = avctx->height;
1309         pic_params.outputBitstream = ctx->output_surfaces[i].output_surface;
1310         pic_params.completionEvent = 0;
1311
1312         if (avctx->flags & CODEC_FLAG_INTERLACED_DCT) {
1313             if (frame->top_field_first) {
1314                 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
1315             } else {
1316                 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
1317             }
1318         } else {
1319             pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1320         }
1321
1322         pic_params.encodePicFlags = 0;
1323         pic_params.inputTimeStamp = frame->pts;
1324         pic_params.inputDuration = 0;
1325         switch (avctx->codec->id) {
1326         case AV_CODEC_ID_H264:
1327           pic_params.codecPicParams.h264PicParams.sliceMode = ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1328           pic_params.codecPicParams.h264PicParams.sliceModeData = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1329           break;
1330         case AV_CODEC_ID_H265:
1331           pic_params.codecPicParams.hevcPicParams.sliceMode = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1332           pic_params.codecPicParams.hevcPicParams.sliceModeData = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1333           break;
1334         default:
1335           av_log(avctx, AV_LOG_ERROR, "nvenc: Unknown codec name\n");
1336           return AVERROR(EINVAL);
1337         }
1338
1339         res = timestamp_queue_enqueue(&ctx->timestamp_list, frame->pts);
1340
1341         if (res)
1342             return res;
1343     } else {
1344         pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1345     }
1346
1347     nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
1348
1349     if (frame && nv_status == NV_ENC_ERR_NEED_MORE_INPUT) {
1350         res = out_surf_queue_enqueue(&ctx->output_surface_queue, &ctx->output_surfaces[i]);
1351
1352         if (res)
1353             return res;
1354
1355         ctx->output_surfaces[i].busy = 1;
1356     }
1357
1358     if (nv_status != NV_ENC_SUCCESS && nv_status != NV_ENC_ERR_NEED_MORE_INPUT) {
1359         av_log(avctx, AV_LOG_ERROR, "EncodePicture failed!\n");
1360         return AVERROR_EXTERNAL;
1361     }
1362
1363     if (nv_status != NV_ENC_ERR_NEED_MORE_INPUT) {
1364         while (ctx->output_surface_queue.count) {
1365             tmpoutsurf = out_surf_queue_dequeue(&ctx->output_surface_queue);
1366             res = out_surf_queue_enqueue(&ctx->output_surface_ready_queue, tmpoutsurf);
1367
1368             if (res)
1369                 return res;
1370         }
1371
1372         if (frame) {
1373             res = out_surf_queue_enqueue(&ctx->output_surface_ready_queue, &ctx->output_surfaces[i]);
1374
1375             if (res)
1376                 return res;
1377
1378             ctx->output_surfaces[i].busy = 1;
1379         }
1380     }
1381
1382     if (ctx->output_surface_ready_queue.count) {
1383         tmpoutsurf = out_surf_queue_dequeue(&ctx->output_surface_ready_queue);
1384
1385         res = process_output_surface(avctx, pkt, avctx->coded_frame, tmpoutsurf);
1386
1387         if (res)
1388             return res;
1389
1390         tmpoutsurf->busy = 0;
1391         av_assert0(tmpoutsurf->input_surface->lockCount);
1392         tmpoutsurf->input_surface->lockCount--;
1393
1394         *got_packet = 1;
1395     } else {
1396         *got_packet = 0;
1397     }
1398
1399     return 0;
1400 }
1401
1402 static const enum AVPixelFormat pix_fmts_nvenc[] = {
1403     AV_PIX_FMT_YUV420P,
1404     AV_PIX_FMT_NV12,
1405     AV_PIX_FMT_YUV444P,
1406     AV_PIX_FMT_NONE
1407 };
1408
1409 #define OFFSET(x) offsetof(NvencContext, x)
1410 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
1411 static const AVOption options[] = {
1412     { "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 },
1413     { "profile", "Set the encoding profile (high, main or baseline)", OFFSET(profile), AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE },
1414     { "level", "Set the encoding level restriction (auto, 1.0, 1.0b, 1.1, 1.2, ..., 4.2, 5.0, 5.1)", OFFSET(level), AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE },
1415     { "tier", "Set the encoding tier (main or high)", OFFSET(tier), AV_OPT_TYPE_STRING, { 0 }, 0, 0, VE },
1416     { "cbr", "Use cbr encoding mode", OFFSET(cbr), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VE },
1417     { "2pass", "Use 2pass cbr encoding mode (low latency mode only)", OFFSET(twopass), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, VE },
1418     { "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 },
1419     { NULL }
1420 };
1421
1422 static const AVCodecDefault nvenc_defaults[] = {
1423     { "b", "0" },
1424     { "qmin", "-1" },
1425     { "qmax", "-1" },
1426     { "qdiff", "-1" },
1427     { "qblur", "-1" },
1428     { "qcomp", "-1" },
1429     { NULL },
1430 };
1431
1432 #if CONFIG_NVENC_ENCODER
1433 static const AVClass nvenc_class = {
1434     .class_name = "nvenc",
1435     .item_name = av_default_item_name,
1436     .option = options,
1437     .version = LIBAVUTIL_VERSION_INT,
1438 };
1439
1440 AVCodec ff_nvenc_encoder = {
1441     .name = "nvenc",
1442     .long_name = NULL_IF_CONFIG_SMALL("Nvidia NVENC h264 encoder"),
1443     .type = AVMEDIA_TYPE_VIDEO,
1444     .id = AV_CODEC_ID_H264,
1445     .priv_data_size = sizeof(NvencContext),
1446     .init = nvenc_encode_init,
1447     .encode2 = nvenc_encode_frame,
1448     .close = nvenc_encode_close,
1449     .capabilities = CODEC_CAP_DELAY,
1450     .priv_class = &nvenc_class,
1451     .defaults = nvenc_defaults,
1452     .pix_fmts = pix_fmts_nvenc,
1453 };
1454 #endif
1455
1456 /* Add an alias for nvenc_h264 */
1457 #if CONFIG_NVENC_H264_ENCODER
1458 static const AVClass nvenc_h264_class = {
1459     .class_name = "nvenc_h264",
1460     .item_name = av_default_item_name,
1461     .option = options,
1462     .version = LIBAVUTIL_VERSION_INT,
1463 };
1464
1465 AVCodec ff_nvenc_h264_encoder = {
1466     .name = "nvenc_h264",
1467     .long_name = NULL_IF_CONFIG_SMALL("Nvidia NVENC h264 encoder"),
1468     .type = AVMEDIA_TYPE_VIDEO,
1469     .id = AV_CODEC_ID_H264,
1470     .priv_data_size = sizeof(NvencContext),
1471     .init = nvenc_encode_init,
1472     .encode2 = nvenc_encode_frame,
1473     .close = nvenc_encode_close,
1474     .capabilities = CODEC_CAP_DELAY,
1475     .priv_class = &nvenc_h264_class,
1476     .defaults = nvenc_defaults,
1477     .pix_fmts = pix_fmts_nvenc,
1478 };
1479 #endif
1480
1481 #if CONFIG_NVENC_HEVC_ENCODER
1482 static const AVClass nvenc_hevc_class = {
1483     .class_name = "nvenc_hevc",
1484     .item_name = av_default_item_name,
1485     .option = options,
1486     .version = LIBAVUTIL_VERSION_INT,
1487 };
1488
1489 AVCodec ff_nvenc_hevc_encoder = {
1490     .name = "nvenc_hevc",
1491     .long_name = NULL_IF_CONFIG_SMALL("Nvidia NVENC hevc encoder"),
1492     .type = AVMEDIA_TYPE_VIDEO,
1493     .id = AV_CODEC_ID_H265,
1494     .priv_data_size = sizeof(NvencContext),
1495     .init = nvenc_encode_init,
1496     .encode2 = nvenc_encode_frame,
1497     .close = nvenc_encode_close,
1498     .capabilities = CODEC_CAP_DELAY,
1499     .priv_class = &nvenc_hevc_class,
1500     .defaults = nvenc_defaults,
1501     .pix_fmts = pix_fmts_nvenc,
1502 };
1503 #endif