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