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