]> git.sesse.net Git - ffmpeg/blob - libavcodec/nvenc.c
Allow linking to CUDA dynamically instead of dlopen()ing it at runtime
[ffmpeg] / libavcodec / nvenc.c
1 /*
2  * NVIDIA NVENC Support
3  * Copyright (C) 2015 Luca Barbato
4  *
5  * This file is part of Libav.
6  *
7  * Libav 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  * Libav 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 Libav; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "config.h"
23
24 #include <cuda.h>
25 #include <nvEncodeAPI.h>
26 #include <string.h>
27
28 #define CUDA_LIBNAME "libcuda.so"
29
30 #if HAVE_DLFCN_H
31 #include <dlfcn.h>
32
33 #define NVENC_LIBNAME "libnvidia-encode.so"
34
35 #elif HAVE_WINDOWS_H
36 #include <windows.h>
37
38 #if ARCH_X86_64
39 #define NVENC_LIBNAME "nvEncodeAPI64.dll"
40 #else
41 #define NVENC_LIBNAME "nvEncodeAPI.dll"
42 #endif
43
44 #define dlopen(filename, flags) LoadLibrary((filename))
45 #define dlsym(handle, symbol)   GetProcAddress(handle, symbol)
46 #define dlclose(handle)         FreeLibrary(handle)
47 #endif
48
49 #include "libavutil/common.h"
50 #include "libavutil/imgutils.h"
51 #include "libavutil/mem.h"
52 #include "avcodec.h"
53 #include "internal.h"
54 #include "nvenc.h"
55
56 #define NVENC_CAP 0x30
57 #define BITSTREAM_BUFFER_SIZE 1024 * 1024
58
59 #define LOAD_LIBRARY(l, path)                   \
60     do {                                        \
61         if (!((l) = dlopen(path, RTLD_LAZY))) { \
62             av_log(avctx, AV_LOG_ERROR,         \
63                    "Cannot load %s\n",          \
64                    path);                       \
65             return AVERROR_UNKNOWN;             \
66         }                                       \
67     } while (0)
68
69 #define LOAD_SYMBOL(fun, lib, symbol)        \
70     do {                                     \
71         if (!((fun) = dlsym(lib, symbol))) { \
72             av_log(avctx, AV_LOG_ERROR,      \
73                    "Cannot load %s\n",       \
74                    symbol);                  \
75             return AVERROR_UNKNOWN;          \
76         }                                    \
77     } while (0)
78
79 const enum AVPixelFormat ff_nvenc_pix_fmts[] = {
80     AV_PIX_FMT_NV12,
81     AV_PIX_FMT_YUV420P,
82     AV_PIX_FMT_YUV444P,
83     AV_PIX_FMT_NONE
84 };
85
86 static const struct {
87     NVENCSTATUS nverr;
88     int         averr;
89     const char *desc;
90 } nvenc_errors[] = {
91     { NV_ENC_SUCCESS,                      0,                "success"                  },
92     { NV_ENC_ERR_NO_ENCODE_DEVICE,         AVERROR(ENOENT),  "no encode device"         },
93     { NV_ENC_ERR_UNSUPPORTED_DEVICE,       AVERROR(ENOSYS),  "unsupported device"       },
94     { NV_ENC_ERR_INVALID_ENCODERDEVICE,    AVERROR(EINVAL),  "invalid encoder device"   },
95     { NV_ENC_ERR_INVALID_DEVICE,           AVERROR(EINVAL),  "invalid device"           },
96     { NV_ENC_ERR_DEVICE_NOT_EXIST,         AVERROR(EIO),     "device does not exist"    },
97     { NV_ENC_ERR_INVALID_PTR,              AVERROR(EFAULT),  "invalid ptr"              },
98     { NV_ENC_ERR_INVALID_EVENT,            AVERROR(EINVAL),  "invalid event"            },
99     { NV_ENC_ERR_INVALID_PARAM,            AVERROR(EINVAL),  "invalid param"            },
100     { NV_ENC_ERR_INVALID_CALL,             AVERROR(EINVAL),  "invalid call"             },
101     { NV_ENC_ERR_OUT_OF_MEMORY,            AVERROR(ENOMEM),  "out of memory"            },
102     { NV_ENC_ERR_ENCODER_NOT_INITIALIZED,  AVERROR(EINVAL),  "encoder not initialized"  },
103     { NV_ENC_ERR_UNSUPPORTED_PARAM,        AVERROR(ENOSYS),  "unsupported param"        },
104     { NV_ENC_ERR_LOCK_BUSY,                AVERROR(EAGAIN),  "lock busy"                },
105     { NV_ENC_ERR_NOT_ENOUGH_BUFFER,        AVERROR(ENOBUFS), "not enough buffer"        },
106     { NV_ENC_ERR_INVALID_VERSION,          AVERROR(EINVAL),  "invalid version"          },
107     { NV_ENC_ERR_MAP_FAILED,               AVERROR(EIO),     "map failed"               },
108     { NV_ENC_ERR_NEED_MORE_INPUT,          AVERROR(EAGAIN),  "need more input"          },
109     { NV_ENC_ERR_ENCODER_BUSY,             AVERROR(EAGAIN),  "encoder busy"             },
110     { NV_ENC_ERR_EVENT_NOT_REGISTERD,      AVERROR(EBADF),   "event not registered"     },
111     { NV_ENC_ERR_GENERIC,                  AVERROR_UNKNOWN,  "generic error"            },
112     { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY,  AVERROR(EINVAL),  "incompatible client key"  },
113     { NV_ENC_ERR_UNIMPLEMENTED,            AVERROR(ENOSYS),  "unimplemented"            },
114     { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO),     "resource register failed" },
115     { NV_ENC_ERR_RESOURCE_NOT_REGISTERED,  AVERROR(EBADF),   "resource not registered"  },
116     { NV_ENC_ERR_RESOURCE_NOT_MAPPED,      AVERROR(EBADF),   "resource not mapped"      },
117 };
118
119 static int nvenc_map_error(NVENCSTATUS err, const char **desc)
120 {
121     int i;
122     for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
123         if (nvenc_errors[i].nverr == err) {
124             if (desc)
125                 *desc = nvenc_errors[i].desc;
126             return nvenc_errors[i].averr;
127         }
128     }
129     if (desc)
130         *desc = "unknown error";
131     return AVERROR_UNKNOWN;
132 }
133
134 static int nvenc_print_error(void *log_ctx, NVENCSTATUS err,
135                              const char *error_string)
136 {
137     const char *desc;
138     int ret;
139     ret = nvenc_map_error(err, &desc);
140     av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
141     return ret;
142 }
143
144 static av_cold int nvenc_load_libraries(AVCodecContext *avctx)
145 {
146     NVENCContext *ctx         = avctx->priv_data;
147     NVENCLibraryContext *nvel = &ctx->nvel;
148     PNVENCODEAPICREATEINSTANCE nvenc_create_instance;
149     NVENCSTATUS err;
150
151 #if CONFIG_CUDA
152     nvel->cu_init                      = cuInit;
153     nvel->cu_device_get_count          = cuDeviceGetCount;
154     nvel->cu_device_get                = cuDeviceGet;
155     nvel->cu_device_get_name           = cuDeviceGetName;
156     nvel->cu_device_compute_capability = cuDeviceComputeCapability;
157     nvel->cu_ctx_create                = cuCtxCreate_v2;
158     nvel->cu_ctx_pop_current           = cuCtxPopCurrent_v2;
159     nvel->cu_ctx_destroy               = cuCtxDestroy_v2;
160 #else
161     LOAD_LIBRARY(nvel->cuda, CUDA_LIBNAME);
162
163     LOAD_SYMBOL(nvel->cu_init, nvel->cuda, "cuInit");
164     LOAD_SYMBOL(nvel->cu_device_get_count, nvel->cuda, "cuDeviceGetCount");
165     LOAD_SYMBOL(nvel->cu_device_get, nvel->cuda, "cuDeviceGet");
166     LOAD_SYMBOL(nvel->cu_device_get_name, nvel->cuda, "cuDeviceGetName");
167     LOAD_SYMBOL(nvel->cu_device_compute_capability, nvel->cuda,
168                 "cuDeviceComputeCapability");
169     LOAD_SYMBOL(nvel->cu_ctx_create, nvel->cuda, "cuCtxCreate_v2");
170     LOAD_SYMBOL(nvel->cu_ctx_pop_current, nvel->cuda, "cuCtxPopCurrent_v2");
171     LOAD_SYMBOL(nvel->cu_ctx_destroy, nvel->cuda, "cuCtxDestroy_v2");
172 #endif
173
174     LOAD_LIBRARY(nvel->nvenc, NVENC_LIBNAME);
175
176     LOAD_SYMBOL(nvenc_create_instance, nvel->nvenc,
177                 "NvEncodeAPICreateInstance");
178
179     nvel->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
180
181     err = nvenc_create_instance(&nvel->nvenc_funcs);
182     if (err != NV_ENC_SUCCESS)
183         return nvenc_print_error(avctx, err, "Cannot create the NVENC instance");
184
185     return 0;
186 }
187
188 static int nvenc_open_session(AVCodecContext *avctx)
189 {
190     NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
191     NVENCContext *ctx                           = avctx->priv_data;
192     NV_ENCODE_API_FUNCTION_LIST *nv             = &ctx->nvel.nvenc_funcs;
193     int ret;
194
195     params.version    = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
196     params.apiVersion = NVENCAPI_VERSION;
197     params.device     = ctx->cu_context;
198     params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
199
200     ret = nv->nvEncOpenEncodeSessionEx(&params, &ctx->nvenc_ctx);
201     if (ret != NV_ENC_SUCCESS) {
202         ctx->nvenc_ctx = NULL;
203         return nvenc_print_error(avctx, ret, "Cannot open the NVENC Session");
204     }
205
206     return 0;
207 }
208
209 static int nvenc_check_codec_support(AVCodecContext *avctx)
210 {
211     NVENCContext *ctx               = avctx->priv_data;
212     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
213     int i, ret, count = 0;
214     GUID *guids = NULL;
215
216     ret = nv->nvEncGetEncodeGUIDCount(ctx->nvenc_ctx, &count);
217
218     if (ret != NV_ENC_SUCCESS || !count)
219         return AVERROR(ENOSYS);
220
221     guids = av_malloc(count * sizeof(GUID));
222     if (!guids)
223         return AVERROR(ENOMEM);
224
225     ret = nv->nvEncGetEncodeGUIDs(ctx->nvenc_ctx, guids, count, &count);
226     if (ret != NV_ENC_SUCCESS) {
227         ret = AVERROR(ENOSYS);
228         goto fail;
229     }
230
231     ret = AVERROR(ENOSYS);
232     for (i = 0; i < count; i++) {
233         if (!memcmp(&guids[i], &ctx->params.encodeGUID, sizeof(*guids))) {
234             ret = 0;
235             break;
236         }
237     }
238
239 fail:
240     av_free(guids);
241
242     return ret;
243 }
244
245 static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
246 {
247     NVENCContext *ctx               = avctx->priv_data;
248     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
249     NV_ENC_CAPS_PARAM params        = { 0 };
250     int ret, val = 0;
251
252     params.version     = NV_ENC_CAPS_PARAM_VER;
253     params.capsToQuery = cap;
254
255     ret = nv->nvEncGetEncodeCaps(ctx->nvenc_ctx, ctx->params.encodeGUID, &params, &val);
256
257     if (ret == NV_ENC_SUCCESS)
258         return val;
259     return 0;
260 }
261
262 static int nvenc_check_capabilities(AVCodecContext *avctx)
263 {
264     int ret;
265
266     ret = nvenc_check_codec_support(avctx);
267     if (ret < 0) {
268         av_log(avctx, AV_LOG_VERBOSE, "Codec not supported\n");
269         return ret;
270     }
271
272     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
273     if (avctx->pix_fmt == AV_PIX_FMT_YUV444P && ret <= 0) {
274         av_log(avctx, AV_LOG_VERBOSE, "YUV444P not supported\n");
275         return AVERROR(ENOSYS);
276     }
277
278     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
279     if (ret < avctx->width) {
280         av_log(avctx, AV_LOG_VERBOSE, "Width %d exceeds %d\n",
281                avctx->width, ret);
282         return AVERROR(ENOSYS);
283     }
284
285     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
286     if (ret < avctx->height) {
287         av_log(avctx, AV_LOG_VERBOSE, "Height %d exceeds %d\n",
288                avctx->height, ret);
289         return AVERROR(ENOSYS);
290     }
291
292     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
293     if (ret < avctx->max_b_frames) {
294         av_log(avctx, AV_LOG_VERBOSE, "Max b-frames %d exceed %d\n",
295                avctx->max_b_frames, ret);
296
297         return AVERROR(ENOSYS);
298     }
299
300     return 0;
301 }
302
303 static int nvenc_check_device(AVCodecContext *avctx, int idx)
304 {
305     NVENCContext *ctx               = avctx->priv_data;
306     NVENCLibraryContext *nvel       = &ctx->nvel;
307     char name[128]                  = { 0 };
308     int major, minor, ret;
309     CUdevice cu_device;
310     CUcontext dummy;
311     int loglevel = AV_LOG_VERBOSE;
312
313     if (ctx->device == LIST_DEVICES)
314         loglevel = AV_LOG_INFO;
315
316     ret = nvel->cu_device_get(&cu_device, idx);
317     if (ret != CUDA_SUCCESS) {
318         av_log(avctx, AV_LOG_ERROR,
319                "Cannot access the CUDA device %d\n",
320                idx);
321         return -1;
322     }
323
324     ret = nvel->cu_device_get_name(name, sizeof(name), cu_device);
325     if (ret != CUDA_SUCCESS)
326         return -1;
327
328     ret = nvel->cu_device_compute_capability(&major, &minor, cu_device);
329     if (ret != CUDA_SUCCESS)
330         return -1;
331
332     av_log(avctx, loglevel, "Device %d [%s] ", cu_device, name);
333
334     if (((major << 4) | minor) < NVENC_CAP)
335         goto fail;
336
337     ret = nvel->cu_ctx_create(&ctx->cu_context, 0, cu_device);
338     if (ret != CUDA_SUCCESS)
339         goto fail;
340
341     ret = nvel->cu_ctx_pop_current(&dummy);
342     if (ret != CUDA_SUCCESS)
343         goto fail2;
344
345     if ((ret = nvenc_open_session(avctx)) < 0)
346         goto fail2;
347
348     if ((ret = nvenc_check_capabilities(avctx)) < 0)
349         goto fail3;
350
351     av_log(avctx, loglevel, "supports NVENC\n");
352
353     if (ctx->device == cu_device || ctx->device == ANY_DEVICE)
354         return 0;
355
356 fail3:
357     nvel->nvenc_funcs.nvEncDestroyEncoder(ctx->nvenc_ctx);
358     ctx->nvenc_ctx = NULL;
359
360 fail2:
361     nvel->cu_ctx_destroy(ctx->cu_context);
362     ctx->cu_context = NULL;
363
364 fail:
365     if (ret != 0)
366         av_log(avctx, loglevel, "does not support NVENC (major %d minor %d)\n",
367                major, minor);
368
369     return AVERROR(ENOSYS);
370 }
371
372 static int nvenc_setup_device(AVCodecContext *avctx)
373 {
374     NVENCContext *ctx         = avctx->priv_data;
375     NVENCLibraryContext *nvel = &ctx->nvel;
376     int i, nb_devices = 0;
377
378     if ((nvel->cu_init(0)) != CUDA_SUCCESS) {
379         av_log(avctx, AV_LOG_ERROR,
380                "Cannot init CUDA\n");
381         return AVERROR_UNKNOWN;
382     }
383
384     if ((nvel->cu_device_get_count(&nb_devices)) != CUDA_SUCCESS) {
385         av_log(avctx, AV_LOG_ERROR,
386                "Cannot enumerate the CUDA devices\n");
387         return AVERROR_UNKNOWN;
388     }
389
390     switch (avctx->codec->id) {
391     case AV_CODEC_ID_H264:
392         ctx->params.encodeGUID = NV_ENC_CODEC_H264_GUID;
393         break;
394     case AV_CODEC_ID_HEVC:
395         ctx->params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
396         break;
397     default:
398         return AVERROR_BUG;
399     }
400
401     for (i = 0; i < nb_devices; ++i) {
402         if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
403             return 0;
404     }
405
406     if (ctx->device == LIST_DEVICES)
407         return AVERROR_EXIT;
408
409     return AVERROR(ENOSYS);
410 }
411
412 typedef struct GUIDTuple {
413     const GUID guid;
414     int flags;
415 } GUIDTuple;
416
417 static int nvec_map_preset(NVENCContext *ctx)
418 {
419     GUIDTuple presets[] = {
420         { NV_ENC_PRESET_DEFAULT_GUID },
421         { NV_ENC_PRESET_HP_GUID },
422         { NV_ENC_PRESET_HQ_GUID },
423         { NV_ENC_PRESET_BD_GUID },
424         { NV_ENC_PRESET_LOW_LATENCY_DEFAULT_GUID, NVENC_LOWLATENCY },
425         { NV_ENC_PRESET_LOW_LATENCY_HP_GUID,      NVENC_LOWLATENCY },
426         { NV_ENC_PRESET_LOW_LATENCY_HQ_GUID,      NVENC_LOWLATENCY },
427         { NV_ENC_PRESET_LOSSLESS_DEFAULT_GUID,    NVENC_LOSSLESS },
428         { NV_ENC_PRESET_LOSSLESS_HP_GUID,         NVENC_LOSSLESS },
429         { { 0 } }
430     };
431
432     GUIDTuple *t = &presets[ctx->preset];
433
434     ctx->params.presetGUID = t->guid;
435     ctx->flags             = t->flags;
436
437     return AVERROR(EINVAL);
438 }
439
440 static void set_constqp(AVCodecContext *avctx, NV_ENC_RC_PARAMS *rc)
441 {
442     rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
443     rc->constQP.qpInterB = avctx->global_quality;
444     rc->constQP.qpInterP = avctx->global_quality;
445     rc->constQP.qpIntra  = avctx->global_quality;
446 }
447
448 static void set_vbr(AVCodecContext *avctx, NV_ENC_RC_PARAMS *rc)
449 {
450     if (avctx->qmin >= 0) {
451         rc->enableMinQP    = 1;
452         rc->minQP.qpInterB = avctx->qmin;
453         rc->minQP.qpInterP = avctx->qmin;
454         rc->minQP.qpIntra  = avctx->qmin;
455     }
456
457     if (avctx->qmax >= 0) {
458         rc->enableMaxQP = 1;
459         rc->maxQP.qpInterB = avctx->qmax;
460         rc->maxQP.qpInterP = avctx->qmax;
461         rc->maxQP.qpIntra  = avctx->qmax;
462     }
463 }
464
465 static void nvenc_override_rate_control(AVCodecContext *avctx,
466                                         NV_ENC_RC_PARAMS *rc)
467 {
468     NVENCContext *ctx    = avctx->priv_data;
469
470     switch (ctx->rc) {
471     case NV_ENC_PARAMS_RC_CONSTQP:
472         if (avctx->global_quality < 0) {
473             av_log(avctx, AV_LOG_WARNING,
474                    "The constant quality rate-control requires "
475                    "the 'global_quality' option set.\n");
476             return;
477         }
478         set_constqp(avctx, rc);
479         return;
480     case NV_ENC_PARAMS_RC_2_PASS_VBR:
481     case NV_ENC_PARAMS_RC_VBR:
482         if (avctx->qmin < 0 && avctx->qmax < 0) {
483             av_log(avctx, AV_LOG_WARNING,
484                    "The variable bitrate rate-control requires "
485                    "the 'qmin' and/or 'qmax' option set.\n");
486             return;
487         }
488     case NV_ENC_PARAMS_RC_VBR_MINQP:
489         if (avctx->qmin < 0) {
490             av_log(avctx, AV_LOG_WARNING,
491                    "The variable bitrate rate-control requires "
492                    "the 'qmin' option set.\n");
493             return;
494         }
495         set_vbr(avctx, rc);
496         break;
497     case NV_ENC_PARAMS_RC_CBR:
498         break;
499     case NV_ENC_PARAMS_RC_2_PASS_QUALITY:
500     case NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP:
501         if (!(ctx->flags & NVENC_LOWLATENCY)) {
502             av_log(avctx, AV_LOG_WARNING,
503                    "The multipass rate-control requires "
504                    "a low-latency preset.\n");
505             return;
506         }
507     }
508
509     rc->rateControlMode = ctx->rc;
510 }
511
512 static void nvenc_setup_rate_control(AVCodecContext *avctx)
513 {
514     NVENCContext *ctx    = avctx->priv_data;
515     NV_ENC_RC_PARAMS *rc = &ctx->config.rcParams;
516
517     if (avctx->bit_rate > 0)
518         rc->averageBitRate = avctx->bit_rate;
519
520     if (avctx->rc_max_rate > 0)
521         rc->maxBitRate = avctx->rc_max_rate;
522
523     if (ctx->rc > 0) {
524         nvenc_override_rate_control(avctx, rc);
525     } else if (avctx->global_quality > 0) {
526         set_constqp(avctx, rc);
527     } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
528         rc->rateControlMode = NV_ENC_PARAMS_RC_VBR;
529         set_vbr(avctx, rc);
530     }
531
532     if (avctx->rc_buffer_size > 0)
533         rc->vbvBufferSize = avctx->rc_buffer_size;
534
535     if (rc->averageBitRate > 0)
536         avctx->bit_rate = rc->averageBitRate;
537 }
538
539 static int nvenc_setup_h264_config(AVCodecContext *avctx)
540 {
541     NVENCContext *ctx                      = avctx->priv_data;
542     NV_ENC_CONFIG *cc                      = &ctx->config;
543     NV_ENC_CONFIG_H264 *h264               = &cc->encodeCodecConfig.h264Config;
544     NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
545
546     vui->colourDescriptionPresentFlag = 1;
547     vui->videoSignalTypePresentFlag   = 1;
548
549     vui->colourMatrix            = avctx->colorspace;
550     vui->colourPrimaries         = avctx->color_primaries;
551     vui->transferCharacteristics = avctx->color_trc;
552
553     vui->videoFullRangeFlag = avctx->color_range == AVCOL_RANGE_JPEG;
554
555     h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
556     h264->repeatSPSPPS  = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
557
558     h264->maxNumRefFrames = avctx->refs;
559     h264->idrPeriod       = cc->gopLength;
560
561     if (ctx->profile)
562         avctx->profile = ctx->profile;
563
564     if (avctx->pix_fmt == AV_PIX_FMT_YUV444P)
565         h264->chromaFormatIDC = 3;
566     else
567         h264->chromaFormatIDC = 1;
568
569     switch (ctx->profile) {
570     case NV_ENC_H264_PROFILE_BASELINE:
571         cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
572         break;
573     case NV_ENC_H264_PROFILE_MAIN:
574         cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
575         break;
576     case NV_ENC_H264_PROFILE_HIGH:
577         cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
578         break;
579     case NV_ENC_H264_PROFILE_HIGH_444:
580         cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
581         break;
582     case NV_ENC_H264_PROFILE_CONSTRAINED_HIGH:
583         cc->profileGUID = NV_ENC_H264_PROFILE_CONSTRAINED_HIGH_GUID;
584         break;
585     }
586
587     h264->level = ctx->level;
588
589     return 0;
590 }
591
592 static int nvenc_setup_hevc_config(AVCodecContext *avctx)
593 {
594     NVENCContext *ctx                      = avctx->priv_data;
595     NV_ENC_CONFIG *cc                      = &ctx->config;
596     NV_ENC_CONFIG_HEVC *hevc               = &cc->encodeCodecConfig.hevcConfig;
597
598     hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
599     hevc->repeatSPSPPS  = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
600
601     hevc->maxNumRefFramesInDPB = avctx->refs;
602     hevc->idrPeriod            = cc->gopLength;
603
604     /* No other profile is supported in the current SDK version 5 */
605     cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
606     avctx->profile  = FF_PROFILE_HEVC_MAIN;
607
608     if (ctx->level) {
609         hevc->level = ctx->level;
610     } else {
611         hevc->level = NV_ENC_LEVEL_AUTOSELECT;
612     }
613
614     if (ctx->tier) {
615         hevc->tier = ctx->tier;
616     }
617
618     return 0;
619 }
620 static int nvenc_setup_codec_config(AVCodecContext *avctx)
621 {
622     switch (avctx->codec->id) {
623     case AV_CODEC_ID_H264:
624         return nvenc_setup_h264_config(avctx);
625     case AV_CODEC_ID_HEVC:
626         return nvenc_setup_hevc_config(avctx);
627     }
628     return 0;
629 }
630
631 static int nvenc_setup_encoder(AVCodecContext *avctx)
632 {
633     NVENCContext *ctx               = avctx->priv_data;
634     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
635     NV_ENC_PRESET_CONFIG preset_cfg = { 0 };
636     AVCPBProperties *cpb_props;
637     int ret;
638
639     ctx->params.version = NV_ENC_INITIALIZE_PARAMS_VER;
640
641     ctx->params.encodeHeight = avctx->height;
642     ctx->params.encodeWidth  = avctx->width;
643
644     if (avctx->sample_aspect_ratio.num &&
645         avctx->sample_aspect_ratio.den &&
646         (avctx->sample_aspect_ratio.num != 1 ||
647          avctx->sample_aspect_ratio.den != 1)) {
648         av_reduce(&ctx->params.darWidth,
649                   &ctx->params.darHeight,
650                   avctx->width * avctx->sample_aspect_ratio.num,
651                   avctx->height * avctx->sample_aspect_ratio.den,
652                   INT_MAX / 8);
653     } else {
654         ctx->params.darHeight = avctx->height;
655         ctx->params.darWidth  = avctx->width;
656     }
657
658     ctx->params.frameRateNum = avctx->time_base.den;
659     ctx->params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
660
661     ctx->params.enableEncodeAsync = 0;
662     ctx->params.enablePTD         = 1;
663
664     ctx->params.encodeConfig = &ctx->config;
665
666     nvec_map_preset(ctx);
667
668     preset_cfg.version           = NV_ENC_PRESET_CONFIG_VER;
669     preset_cfg.presetCfg.version = NV_ENC_CONFIG_VER;
670
671     ret = nv->nvEncGetEncodePresetConfig(ctx->nvenc_ctx,
672                                          ctx->params.encodeGUID,
673                                          ctx->params.presetGUID,
674                                          &preset_cfg);
675     if (ret != NV_ENC_SUCCESS)
676         return nvenc_print_error(avctx, ret, "Cannot get the preset configuration");
677
678     memcpy(&ctx->config, &preset_cfg.presetCfg, sizeof(ctx->config));
679
680     ctx->config.version = NV_ENC_CONFIG_VER;
681
682     if (avctx->gop_size > 0) {
683         if (avctx->max_b_frames > 0) {
684             /* 0 is intra-only,
685              * 1 is I/P only,
686              * 2 is one B Frame,
687              * 3 two B frames, and so on. */
688             ctx->config.frameIntervalP = avctx->max_b_frames + 1;
689         } else if (avctx->max_b_frames == 0) {
690             ctx->config.frameIntervalP = 1;
691         }
692         ctx->config.gopLength = avctx->gop_size;
693     } else if (avctx->gop_size == 0) {
694         ctx->config.frameIntervalP = 0;
695         ctx->config.gopLength      = 1;
696     }
697
698     if (ctx->config.frameIntervalP > 1)
699         avctx->max_b_frames = ctx->config.frameIntervalP - 1;
700
701     ctx->initial_pts[0] = AV_NOPTS_VALUE;
702     ctx->initial_pts[1] = AV_NOPTS_VALUE;
703
704     nvenc_setup_rate_control(avctx);
705
706     if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
707         ctx->config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
708     } else {
709         ctx->config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
710     }
711
712     if ((ret = nvenc_setup_codec_config(avctx)) < 0)
713         return ret;
714
715     ret = nv->nvEncInitializeEncoder(ctx->nvenc_ctx, &ctx->params);
716     if (ret != NV_ENC_SUCCESS)
717         return nvenc_print_error(avctx, ret, "Cannot initialize the decoder");
718
719     cpb_props = ff_add_cpb_side_data(avctx);
720     if (!cpb_props)
721         return AVERROR(ENOMEM);
722     cpb_props->max_bitrate = avctx->rc_max_rate;
723     cpb_props->min_bitrate = avctx->rc_min_rate;
724     cpb_props->avg_bitrate = avctx->bit_rate;
725     cpb_props->buffer_size = avctx->rc_buffer_size;
726
727     return 0;
728 }
729
730 static int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
731 {
732     NVENCContext *ctx               = avctx->priv_data;
733     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
734     int ret;
735     NV_ENC_CREATE_INPUT_BUFFER in_buffer      = { 0 };
736     NV_ENC_CREATE_BITSTREAM_BUFFER out_buffer = { 0 };
737
738     in_buffer.version  = NV_ENC_CREATE_INPUT_BUFFER_VER;
739     out_buffer.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
740
741     in_buffer.width  = avctx->width;
742     in_buffer.height = avctx->height;
743
744     in_buffer.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED;
745
746     switch (avctx->pix_fmt) {
747     case AV_PIX_FMT_YUV420P:
748         in_buffer.bufferFmt = NV_ENC_BUFFER_FORMAT_YV12_PL;
749         break;
750     case AV_PIX_FMT_NV12:
751         in_buffer.bufferFmt = NV_ENC_BUFFER_FORMAT_NV12_PL;
752         break;
753     case AV_PIX_FMT_YUV444P:
754         in_buffer.bufferFmt = NV_ENC_BUFFER_FORMAT_YUV444_PL;
755         break;
756     default:
757         return AVERROR_BUG;
758     }
759
760     ret = nv->nvEncCreateInputBuffer(ctx->nvenc_ctx, &in_buffer);
761     if (ret != NV_ENC_SUCCESS)
762         return nvenc_print_error(avctx, ret, "CreateInputBuffer failed");
763
764     ctx->frames[idx].in     = in_buffer.inputBuffer;
765     ctx->frames[idx].format = in_buffer.bufferFmt;
766
767     /* 1MB is large enough to hold most output frames.
768      * NVENC increases this automaticaly if it's not enough. */
769     out_buffer.size = BITSTREAM_BUFFER_SIZE;
770
771     out_buffer.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED;
772
773     ret = nv->nvEncCreateBitstreamBuffer(ctx->nvenc_ctx, &out_buffer);
774     if (ret != NV_ENC_SUCCESS)
775         return nvenc_print_error(avctx, ret, "CreateBitstreamBuffer failed");
776
777     ctx->frames[idx].out  = out_buffer.bitstreamBuffer;
778
779     return 0;
780 }
781
782 static int nvenc_setup_surfaces(AVCodecContext *avctx)
783 {
784     NVENCContext *ctx = avctx->priv_data;
785     int i, ret;
786
787     ctx->nb_surfaces = FFMAX(4 + avctx->max_b_frames,
788                              ctx->nb_surfaces);
789
790     ctx->frames = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->frames));
791     if (!ctx->frames)
792         return AVERROR(ENOMEM);
793
794     ctx->timestamps = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
795     if (!ctx->timestamps)
796         return AVERROR(ENOMEM);
797     ctx->pending = av_fifo_alloc(ctx->nb_surfaces * sizeof(*ctx->frames));
798     if (!ctx->pending)
799         return AVERROR(ENOMEM);
800     ctx->ready = av_fifo_alloc(ctx->nb_surfaces * sizeof(*ctx->frames));
801     if (!ctx->ready)
802         return AVERROR(ENOMEM);
803
804     for (i = 0; i < ctx->nb_surfaces; i++) {
805         if ((ret = nvenc_alloc_surface(avctx, i)) < 0)
806             return ret;
807     }
808
809     return 0;
810 }
811
812 #define EXTRADATA_SIZE 512
813
814 static int nvenc_setup_extradata(AVCodecContext *avctx)
815 {
816     NVENCContext *ctx                     = avctx->priv_data;
817     NV_ENCODE_API_FUNCTION_LIST *nv       = &ctx->nvel.nvenc_funcs;
818     NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
819     int ret;
820
821     avctx->extradata = av_mallocz(EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
822     if (!avctx->extradata)
823         return AVERROR(ENOMEM);
824
825     payload.version              = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
826     payload.spsppsBuffer         = avctx->extradata;
827     payload.inBufferSize         = EXTRADATA_SIZE;
828     payload.outSPSPPSPayloadSize = &avctx->extradata_size;
829
830     ret = nv->nvEncGetSequenceParams(ctx->nvenc_ctx, &payload);
831     if (ret != NV_ENC_SUCCESS)
832         return nvenc_print_error(avctx, ret, "Cannot get the extradata");
833
834     return 0;
835 }
836
837 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
838 {
839     NVENCContext *ctx               = avctx->priv_data;
840     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
841     int i;
842
843     /* the encoder has to be flushed before it can be closed */
844     if (ctx->nvenc_ctx) {
845         NV_ENC_PIC_PARAMS params        = { .version        = NV_ENC_PIC_PARAMS_VER,
846                                             .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
847
848         nv->nvEncEncodePicture(ctx->nvenc_ctx, &params);
849     }
850
851     av_fifo_free(ctx->timestamps);
852     av_fifo_free(ctx->pending);
853     av_fifo_free(ctx->ready);
854
855     if (ctx->frames) {
856         for (i = 0; i < ctx->nb_surfaces; ++i) {
857             nv->nvEncDestroyInputBuffer(ctx->nvenc_ctx,     ctx->frames[i].in);
858             nv->nvEncDestroyBitstreamBuffer(ctx->nvenc_ctx, ctx->frames[i].out);
859         }
860     }
861
862     av_freep(&ctx->frames);
863
864     if (ctx->nvenc_ctx)
865         nv->nvEncDestroyEncoder(ctx->nvenc_ctx);
866
867     if (ctx->cu_context)
868         ctx->nvel.cu_ctx_destroy(ctx->cu_context);
869
870     if (ctx->nvel.nvenc)
871         dlclose(ctx->nvel.nvenc);
872
873 #if !CONFIG_CUDA
874     if (ctx->nvel.cuda)
875         dlclose(ctx->nvel.cuda);
876 #endif
877
878     return 0;
879 }
880
881 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
882 {
883     int ret;
884
885     if ((ret = nvenc_load_libraries(avctx)) < 0)
886         return ret;
887
888     if ((ret = nvenc_setup_device(avctx)) < 0)
889         return ret;
890
891     if ((ret = nvenc_setup_encoder(avctx)) < 0)
892         return ret;
893
894     if ((ret = nvenc_setup_surfaces(avctx)) < 0)
895         return ret;
896
897     if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
898         if ((ret = nvenc_setup_extradata(avctx)) < 0)
899             return ret;
900     }
901
902     return 0;
903 }
904
905 static NVENCFrame *get_free_frame(NVENCContext *ctx)
906 {
907     int i;
908
909     for (i = 0; i < ctx->nb_surfaces; i++) {
910         if (!ctx->frames[i].locked) {
911             ctx->frames[i].locked = 1;
912             return &ctx->frames[i];
913         }
914     }
915
916     return NULL;
917 }
918
919 static int nvenc_copy_frame(NV_ENC_LOCK_INPUT_BUFFER *in, const AVFrame *frame)
920 {
921     uint8_t *buf = in->bufferDataPtr;
922     int off      = frame->height * in->pitch;
923
924     switch (frame->format) {
925     case AV_PIX_FMT_YUV420P:
926         av_image_copy_plane(buf, in->pitch,
927                             frame->data[0], frame->linesize[0],
928                             frame->width, frame->height);
929         buf += off;
930
931         av_image_copy_plane(buf, in->pitch >> 1,
932                             frame->data[2], frame->linesize[2],
933                             frame->width >> 1, frame->height >> 1);
934
935         buf += off >> 2;
936
937         av_image_copy_plane(buf, in->pitch >> 1,
938                             frame->data[1], frame->linesize[1],
939                             frame->width >> 1, frame->height >> 1);
940         break;
941     case AV_PIX_FMT_NV12:
942         av_image_copy_plane(buf, in->pitch,
943                             frame->data[0], frame->linesize[0],
944                             frame->width, frame->height);
945         buf += off;
946
947         av_image_copy_plane(buf, in->pitch,
948                             frame->data[1], frame->linesize[1],
949                             frame->width, frame->height >> 1);
950         break;
951     case AV_PIX_FMT_YUV444P:
952         av_image_copy_plane(buf, in->pitch,
953                             frame->data[0], frame->linesize[0],
954                             frame->width, frame->height);
955         buf += off;
956
957         av_image_copy_plane(buf, in->pitch,
958                             frame->data[1], frame->linesize[1],
959                             frame->width, frame->height);
960         buf += off;
961
962         av_image_copy_plane(buf, in->pitch,
963                             frame->data[2], frame->linesize[2],
964                             frame->width, frame->height);
965         break;
966     default:
967         return AVERROR_BUG;
968     }
969
970     return 0;
971 }
972
973 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
974                               NVENCFrame *nvenc_frame)
975 {
976     NVENCContext *ctx               = avctx->priv_data;
977     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
978     NV_ENC_LOCK_INPUT_BUFFER params = { 0 };
979     int ret;
980
981     params.version     = NV_ENC_LOCK_INPUT_BUFFER_VER;
982     params.inputBuffer = nvenc_frame->in;
983
984
985     ret = nv->nvEncLockInputBuffer(ctx->nvenc_ctx, &params);
986     if (ret != NV_ENC_SUCCESS)
987         return nvenc_print_error(avctx, ret, "Cannot lock the buffer");
988
989     ret = nvenc_copy_frame(&params, frame);
990     if (ret < 0)
991         goto fail;
992
993     ret = nv->nvEncUnlockInputBuffer(ctx->nvenc_ctx, nvenc_frame->in);
994     if (ret != NV_ENC_SUCCESS)
995         return nvenc_print_error(avctx, ret, "Cannot unlock the buffer");
996
997     return 0;
998
999 fail:
1000     nv->nvEncUnlockInputBuffer(ctx->nvenc_ctx, nvenc_frame->in);
1001
1002     return ret;
1003 }
1004
1005 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1006                                             NV_ENC_PIC_PARAMS *params)
1007 {
1008     NVENCContext *ctx = avctx->priv_data;
1009
1010     switch (avctx->codec->id) {
1011     case AV_CODEC_ID_H264:
1012         params->codecPicParams.h264PicParams.sliceMode =
1013             ctx->config.encodeCodecConfig.h264Config.sliceMode;
1014         params->codecPicParams.h264PicParams.sliceModeData =
1015             ctx->config.encodeCodecConfig.h264Config.sliceModeData;
1016         break;
1017     case AV_CODEC_ID_HEVC:
1018         params->codecPicParams.hevcPicParams.sliceMode =
1019             ctx->config.encodeCodecConfig.hevcConfig.sliceMode;
1020         params->codecPicParams.hevcPicParams.sliceModeData =
1021             ctx->config.encodeCodecConfig.hevcConfig.sliceModeData;
1022         break;
1023     }
1024 }
1025
1026 static inline int nvenc_enqueue_timestamp(AVFifoBuffer *f, int64_t pts)
1027 {
1028     return av_fifo_generic_write(f, &pts, sizeof(pts), NULL);
1029 }
1030
1031 static inline int nvenc_dequeue_timestamp(AVFifoBuffer *f, int64_t *pts)
1032 {
1033     return av_fifo_generic_read(f, pts, sizeof(*pts), NULL);
1034 }
1035
1036 static int nvenc_set_timestamp(AVCodecContext *avctx,
1037                                NV_ENC_LOCK_BITSTREAM *params,
1038                                AVPacket *pkt)
1039 {
1040     NVENCContext *ctx = avctx->priv_data;
1041
1042     pkt->pts      = params->outputTimeStamp;
1043     pkt->duration = params->outputDuration;
1044
1045     /* generate the first dts by linearly extrapolating the
1046      * first two pts values to the past */
1047     if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
1048         ctx->initial_pts[1] != AV_NOPTS_VALUE) {
1049         int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
1050         int64_t delta;
1051
1052         if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
1053             (ts0 > 0 && ts1 < INT64_MIN + ts0))
1054             return AVERROR(ERANGE);
1055         delta = ts1 - ts0;
1056
1057         if ((delta < 0 && ts0 > INT64_MAX + delta) ||
1058             (delta > 0 && ts0 < INT64_MIN + delta))
1059             return AVERROR(ERANGE);
1060         pkt->dts = ts0 - delta;
1061
1062         ctx->first_packet_output = 1;
1063         return 0;
1064     }
1065     return nvenc_dequeue_timestamp(ctx->timestamps, &pkt->dts);
1066 }
1067
1068 static int nvenc_get_output(AVCodecContext *avctx, AVPacket *pkt)
1069 {
1070     NVENCContext *ctx               = avctx->priv_data;
1071     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1072     NV_ENC_LOCK_BITSTREAM params    = { 0 };
1073     NVENCFrame *frame;
1074     int ret;
1075
1076     ret = av_fifo_generic_read(ctx->ready, &frame, sizeof(frame), NULL);
1077     if (ret)
1078         return ret;
1079
1080     params.version         = NV_ENC_LOCK_BITSTREAM_VER;
1081     params.outputBitstream = frame->out;
1082
1083     ret = nv->nvEncLockBitstream(ctx->nvenc_ctx, &params);
1084     if (ret < 0)
1085         return nvenc_print_error(avctx, ret, "Cannot lock the bitstream");
1086
1087     ret = ff_alloc_packet(pkt, params.bitstreamSizeInBytes);
1088     if (ret < 0)
1089         return ret;
1090
1091     memcpy(pkt->data, params.bitstreamBufferPtr, pkt->size);
1092
1093     ret = nv->nvEncUnlockBitstream(ctx->nvenc_ctx, frame->out);
1094     if (ret < 0)
1095         return nvenc_print_error(avctx, ret, "Cannot unlock the bitstream");
1096
1097     frame->locked = 0;
1098
1099     ret = nvenc_set_timestamp(avctx, &params, pkt);
1100     if (ret < 0)
1101         return ret;
1102
1103     switch (params.pictureType) {
1104     case NV_ENC_PIC_TYPE_IDR:
1105         pkt->flags |= AV_PKT_FLAG_KEY;
1106 #if FF_API_CODED_FRAME
1107 FF_DISABLE_DEPRECATION_WARNINGS
1108     case NV_ENC_PIC_TYPE_INTRA_REFRESH:
1109     case NV_ENC_PIC_TYPE_I:
1110         avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
1111         break;
1112     case NV_ENC_PIC_TYPE_P:
1113         avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
1114         break;
1115     case NV_ENC_PIC_TYPE_B:
1116         avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;
1117         break;
1118     case NV_ENC_PIC_TYPE_BI:
1119         avctx->coded_frame->pict_type = AV_PICTURE_TYPE_BI;
1120         break;
1121 FF_ENABLE_DEPRECATION_WARNINGS
1122 #endif
1123     }
1124
1125     return 0;
1126 }
1127
1128 static int output_ready(AVCodecContext *avctx, int flush)
1129 {
1130     NVENCContext *ctx = avctx->priv_data;
1131
1132     /* when B-frames are enabled, we wait for two initial timestamps to
1133      * calculate the first dts */
1134     if (!flush && avctx->max_b_frames > 0 &&
1135         (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
1136         return 0;
1137     return av_fifo_size(ctx->ready) > 0;
1138 }
1139
1140 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1141                           const AVFrame *frame, int *got_packet)
1142 {
1143     NVENCContext *ctx               = avctx->priv_data;
1144     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1145     NV_ENC_PIC_PARAMS params        = { 0 };
1146     NVENCFrame         *nvenc_frame = NULL;
1147     int enc_ret, ret;
1148
1149     params.version = NV_ENC_PIC_PARAMS_VER;
1150
1151     if (frame) {
1152         nvenc_frame = get_free_frame(ctx);
1153         if (!nvenc_frame) {
1154             av_log(avctx, AV_LOG_ERROR, "No free surfaces\n");
1155             return AVERROR_BUG;
1156         }
1157
1158         ret = nvenc_upload_frame(avctx, frame, nvenc_frame);
1159         if (ret < 0)
1160             return ret;
1161
1162         params.inputBuffer     = nvenc_frame->in;
1163         params.bufferFmt       = nvenc_frame->format;
1164         params.inputWidth      = frame->width;
1165         params.inputHeight     = frame->height;
1166         params.outputBitstream = nvenc_frame->out;
1167         params.inputTimeStamp  = frame->pts;
1168
1169         if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1170             if (frame->top_field_first)
1171                 params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
1172             else
1173                 params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
1174         } else {
1175             params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1176         }
1177
1178         nvenc_codec_specific_pic_params(avctx, &params);
1179
1180         ret = nvenc_enqueue_timestamp(ctx->timestamps, frame->pts);
1181         if (ret < 0)
1182             return ret;
1183
1184         if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
1185             ctx->initial_pts[0] = frame->pts;
1186         else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
1187             ctx->initial_pts[1] = frame->pts;
1188     } else {
1189         params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1190     }
1191
1192     enc_ret = nv->nvEncEncodePicture(ctx->nvenc_ctx, &params);
1193     if (enc_ret != NV_ENC_SUCCESS &&
1194         enc_ret != NV_ENC_ERR_NEED_MORE_INPUT)
1195         return nvenc_print_error(avctx, enc_ret, "Error encoding the frame");
1196
1197     if (nvenc_frame) {
1198         ret = av_fifo_generic_write(ctx->pending, &nvenc_frame, sizeof(nvenc_frame), NULL);
1199         if (ret < 0)
1200             return ret;
1201     }
1202
1203     /* all the pending buffers are now ready for output */
1204     if (enc_ret == NV_ENC_SUCCESS) {
1205         while (av_fifo_size(ctx->pending) > 0) {
1206             av_fifo_generic_read(ctx->pending, &nvenc_frame, sizeof(nvenc_frame), NULL);
1207             av_fifo_generic_write(ctx->ready,  &nvenc_frame, sizeof(nvenc_frame), NULL);
1208         }
1209     }
1210
1211     if (output_ready(avctx, !frame)) {
1212         ret = nvenc_get_output(avctx, pkt);
1213         if (ret < 0)
1214             return ret;
1215         *got_packet = 1;
1216     } else {
1217         *got_packet = 0;
1218     }
1219
1220     return 0;
1221 }