nvenc: generate dts properly
[libav.git] / 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 static 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
112 static 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
127 static 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
137 static 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;
142 NVENCSTATUS err;
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
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");
166
167 return 0;
168 }
169
170 static 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;
185 return nvenc_print_error(avctx, ret, "Cannot open the NVENC Session");
186 }
187
188 return 0;
189 }
190
191 static 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
221 fail:
222 av_free(guids);
223
224 return ret;
225 }
226
227 static 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
244 static 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
285 static 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
338 fail3:
339 nvel->nvenc_funcs.nvEncDestroyEncoder(ctx->nvenc_ctx);
340 ctx->nvenc_ctx = NULL;
341
342 fail2:
343 nvel->cu_ctx_destroy(ctx->cu_context);
344 ctx->cu_context = NULL;
345
346 fail:
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
354 static 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
394 typedef struct GUIDTuple {
395 const GUID guid;
396 int flags;
397 } GUIDTuple;
398
399 static 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
422 static 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
430 static 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
447 static 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
494 static 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
521 static 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
537 h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
538 h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
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
574 static 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
580 hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
581 hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
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 }
602 static 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
613 static 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 };
618 AVCPBProperties *cpb_props;
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);
657 if (ret != NV_ENC_SUCCESS)
658 return nvenc_print_error(avctx, ret, "Cannot get the preset configuration");
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 /* 0 is intra-only,
667 * 1 is I/P only,
668 * 2 is one B Frame,
669 * 3 two B frames, and so on. */
670 ctx->config.frameIntervalP = avctx->max_b_frames + 1;
671 } else if (avctx->max_b_frames == 0) {
672 ctx->config.frameIntervalP = 1;
673 }
674 ctx->config.gopLength = avctx->gop_size;
675 } else if (avctx->gop_size == 0) {
676 ctx->config.frameIntervalP = 0;
677 ctx->config.gopLength = 1;
678 }
679
680 if (ctx->config.frameIntervalP > 1)
681 avctx->max_b_frames = ctx->config.frameIntervalP - 1;
682
683 ctx->initial_pts[0] = AV_NOPTS_VALUE;
684 ctx->initial_pts[1] = AV_NOPTS_VALUE;
685
686 nvenc_setup_rate_control(avctx);
687
688 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
689 ctx->config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
690 } else {
691 ctx->config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
692 }
693
694 if ((ret = nvenc_setup_codec_config(avctx)) < 0)
695 return ret;
696
697 ret = nv->nvEncInitializeEncoder(ctx->nvenc_ctx, &ctx->params);
698 if (ret != NV_ENC_SUCCESS)
699 return nvenc_print_error(avctx, ret, "Cannot initialize the decoder");
700
701 cpb_props = ff_add_cpb_side_data(avctx);
702 if (!cpb_props)
703 return AVERROR(ENOMEM);
704 cpb_props->max_bitrate = avctx->rc_max_rate;
705 cpb_props->min_bitrate = avctx->rc_min_rate;
706 cpb_props->avg_bitrate = avctx->bit_rate;
707 cpb_props->buffer_size = avctx->rc_buffer_size;
708
709 return 0;
710 }
711
712 static int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
713 {
714 NVENCContext *ctx = avctx->priv_data;
715 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
716 int ret;
717 NV_ENC_CREATE_INPUT_BUFFER in_buffer = { 0 };
718 NV_ENC_CREATE_BITSTREAM_BUFFER out_buffer = { 0 };
719
720 in_buffer.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
721 out_buffer.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
722
723 in_buffer.width = avctx->width;
724 in_buffer.height = avctx->height;
725
726 in_buffer.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED;
727
728 switch (avctx->pix_fmt) {
729 case AV_PIX_FMT_YUV420P:
730 in_buffer.bufferFmt = NV_ENC_BUFFER_FORMAT_YV12_PL;
731 break;
732 case AV_PIX_FMT_NV12:
733 in_buffer.bufferFmt = NV_ENC_BUFFER_FORMAT_NV12_PL;
734 break;
735 case AV_PIX_FMT_YUV444P:
736 in_buffer.bufferFmt = NV_ENC_BUFFER_FORMAT_YUV444_PL;
737 break;
738 default:
739 return AVERROR_BUG;
740 }
741
742 ret = nv->nvEncCreateInputBuffer(ctx->nvenc_ctx, &in_buffer);
743 if (ret != NV_ENC_SUCCESS)
744 return nvenc_print_error(avctx, ret, "CreateInputBuffer failed");
745
746 ctx->in[idx].in = in_buffer.inputBuffer;
747 ctx->in[idx].format = in_buffer.bufferFmt;
748
749 /* 1MB is large enough to hold most output frames.
750 * NVENC increases this automaticaly if it's not enough. */
751 out_buffer.size = BITSTREAM_BUFFER_SIZE;
752
753 out_buffer.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED;
754
755 ret = nv->nvEncCreateBitstreamBuffer(ctx->nvenc_ctx, &out_buffer);
756 if (ret != NV_ENC_SUCCESS)
757 return nvenc_print_error(avctx, ret, "CreateBitstreamBuffer failed");
758
759 ctx->out[idx].out = out_buffer.bitstreamBuffer;
760 ctx->out[idx].busy = 0;
761
762 return 0;
763 }
764
765 static int nvenc_setup_surfaces(AVCodecContext *avctx)
766 {
767 NVENCContext *ctx = avctx->priv_data;
768 int i, ret;
769
770 ctx->nb_surfaces = FFMAX(4 + avctx->max_b_frames,
771 ctx->nb_surfaces);
772
773 ctx->in = av_mallocz(ctx->nb_surfaces * sizeof(*ctx->in));
774 if (!ctx->in)
775 return AVERROR(ENOMEM);
776
777 ctx->out = av_mallocz(ctx->nb_surfaces * sizeof(*ctx->out));
778 if (!ctx->out)
779 return AVERROR(ENOMEM);
780
781 ctx->timestamps = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
782 if (!ctx->timestamps)
783 return AVERROR(ENOMEM);
784 ctx->pending = av_fifo_alloc(ctx->nb_surfaces * sizeof(ctx->out));
785 if (!ctx->pending)
786 return AVERROR(ENOMEM);
787 ctx->ready = av_fifo_alloc(ctx->nb_surfaces * sizeof(ctx->out));
788 if (!ctx->ready)
789 return AVERROR(ENOMEM);
790
791 for (i = 0; i < ctx->nb_surfaces; i++) {
792 if ((ret = nvenc_alloc_surface(avctx, i)) < 0)
793 return ret;
794 }
795
796 return 0;
797 }
798
799 #define EXTRADATA_SIZE 512
800
801 static int nvenc_setup_extradata(AVCodecContext *avctx)
802 {
803 NVENCContext *ctx = avctx->priv_data;
804 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
805 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
806 int ret;
807
808 avctx->extradata = av_mallocz(EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
809 if (!avctx->extradata)
810 return AVERROR(ENOMEM);
811
812 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
813 payload.spsppsBuffer = avctx->extradata;
814 payload.inBufferSize = EXTRADATA_SIZE;
815 payload.outSPSPPSPayloadSize = &avctx->extradata_size;
816
817 ret = nv->nvEncGetSequenceParams(ctx->nvenc_ctx, &payload);
818 if (ret != NV_ENC_SUCCESS)
819 return nvenc_print_error(avctx, ret, "Cannot get the extradata");
820
821 return 0;
822 }
823
824 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
825 {
826 NVENCContext *ctx = avctx->priv_data;
827 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
828 int i;
829
830 /* the encoder has to be flushed before it can be closed */
831 if (ctx->nvenc_ctx) {
832 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
833 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
834
835 nv->nvEncEncodePicture(ctx->nvenc_ctx, &params);
836 }
837
838 av_fifo_free(ctx->timestamps);
839 av_fifo_free(ctx->pending);
840 av_fifo_free(ctx->ready);
841
842 if (ctx->in) {
843 for (i = 0; i < ctx->nb_surfaces; ++i) {
844 nv->nvEncDestroyInputBuffer(ctx->nvenc_ctx, ctx->in[i].in);
845 nv->nvEncDestroyBitstreamBuffer(ctx->nvenc_ctx, ctx->out[i].out);
846 }
847 }
848
849 av_freep(&ctx->in);
850 av_freep(&ctx->out);
851
852 if (ctx->nvenc_ctx)
853 nv->nvEncDestroyEncoder(ctx->nvenc_ctx);
854
855 if (ctx->cu_context)
856 ctx->nvel.cu_ctx_destroy(ctx->cu_context);
857
858 if (ctx->nvel.nvenc)
859 dlclose(ctx->nvel.nvenc);
860
861 if (ctx->nvel.cuda)
862 dlclose(ctx->nvel.cuda);
863
864 return 0;
865 }
866
867 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
868 {
869 int ret;
870
871 if ((ret = nvenc_load_libraries(avctx)) < 0)
872 return ret;
873
874 if ((ret = nvenc_setup_device(avctx)) < 0)
875 return ret;
876
877 if ((ret = nvenc_setup_encoder(avctx)) < 0)
878 return ret;
879
880 if ((ret = nvenc_setup_surfaces(avctx)) < 0)
881 return ret;
882
883 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
884 if ((ret = nvenc_setup_extradata(avctx)) < 0)
885 return ret;
886 }
887
888 return 0;
889 }
890
891 static NVENCInputSurface *get_input_surface(NVENCContext *ctx)
892 {
893 int i;
894
895 for (i = 0; i < ctx->nb_surfaces; i++) {
896 if (!ctx->in[i].locked) {
897 ctx->in[i].locked = 1;
898 return &ctx->in[i];
899 }
900 }
901
902 return NULL;
903 }
904
905 static NVENCOutputSurface *get_output_surface(NVENCContext *ctx)
906 {
907 int i;
908
909 for (i = 0; i < ctx->nb_surfaces; i++) {
910 if (!ctx->out[i].busy) {
911 return &ctx->out[i];
912 }
913 }
914
915 return NULL;
916 }
917
918 static int nvenc_copy_frame(NV_ENC_LOCK_INPUT_BUFFER *in, const AVFrame *frame)
919 {
920 uint8_t *buf = in->bufferDataPtr;
921 int off = frame->height * in->pitch;
922
923 switch (frame->format) {
924 case AV_PIX_FMT_YUV420P:
925 av_image_copy_plane(buf, in->pitch,
926 frame->data[0], frame->linesize[0],
927 frame->width, frame->height);
928 buf += off;
929
930 av_image_copy_plane(buf, in->pitch >> 1,
931 frame->data[2], frame->linesize[2],
932 frame->width >> 1, frame->height >> 1);
933
934 buf += off >> 2;
935
936 av_image_copy_plane(buf, in->pitch >> 1,
937 frame->data[1], frame->linesize[1],
938 frame->width >> 1, frame->height >> 1);
939 break;
940 case AV_PIX_FMT_NV12:
941 av_image_copy_plane(buf, in->pitch,
942 frame->data[0], frame->linesize[0],
943 frame->width, frame->height);
944 buf += off;
945
946 av_image_copy_plane(buf, in->pitch,
947 frame->data[1], frame->linesize[1],
948 frame->width, frame->height >> 1);
949 break;
950 case AV_PIX_FMT_YUV444P:
951 av_image_copy_plane(buf, in->pitch,
952 frame->data[0], frame->linesize[0],
953 frame->width, frame->height);
954 buf += off;
955
956 av_image_copy_plane(buf, in->pitch,
957 frame->data[1], frame->linesize[1],
958 frame->width, frame->height);
959 buf += off;
960
961 av_image_copy_plane(buf, in->pitch,
962 frame->data[2], frame->linesize[2],
963 frame->width, frame->height);
964 break;
965 default:
966 return AVERROR_BUG;
967 }
968
969 return 0;
970 }
971
972 static int nvenc_enqueue_frame(AVCodecContext *avctx, const AVFrame *frame,
973 NVENCInputSurface **in_surf)
974 {
975 NVENCContext *ctx = avctx->priv_data;
976 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
977 NV_ENC_LOCK_INPUT_BUFFER params = { 0 };
978 NVENCInputSurface *in = get_input_surface(ctx);
979 int ret;
980
981 if (!in)
982 return AVERROR_BUG;
983
984 params.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
985 params.inputBuffer = in->in;
986
987
988 ret = nv->nvEncLockInputBuffer(ctx->nvenc_ctx, &params);
989 if (ret != NV_ENC_SUCCESS)
990 return nvenc_print_error(avctx, ret, "Cannot lock the buffer");
991
992 ret = nvenc_copy_frame(&params, frame);
993 if (ret < 0)
994 goto fail;
995
996 ret = nv->nvEncUnlockInputBuffer(ctx->nvenc_ctx, in->in);
997 if (ret != NV_ENC_SUCCESS)
998 return nvenc_print_error(avctx, ret, "Cannot unlock the buffer");
999
1000 *in_surf = in;
1001
1002 return 0;
1003
1004 fail:
1005 nv->nvEncUnlockInputBuffer(ctx->nvenc_ctx, in->in);
1006
1007 return ret;
1008 }
1009
1010 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1011 NV_ENC_PIC_PARAMS *params)
1012 {
1013 NVENCContext *ctx = avctx->priv_data;
1014
1015 switch (avctx->codec->id) {
1016 case AV_CODEC_ID_H264:
1017 params->codecPicParams.h264PicParams.sliceMode =
1018 ctx->config.encodeCodecConfig.h264Config.sliceMode;
1019 params->codecPicParams.h264PicParams.sliceModeData =
1020 ctx->config.encodeCodecConfig.h264Config.sliceModeData;
1021 break;
1022 case AV_CODEC_ID_HEVC:
1023 params->codecPicParams.hevcPicParams.sliceMode =
1024 ctx->config.encodeCodecConfig.hevcConfig.sliceMode;
1025 params->codecPicParams.hevcPicParams.sliceModeData =
1026 ctx->config.encodeCodecConfig.hevcConfig.sliceModeData;
1027 break;
1028 }
1029 }
1030
1031 static inline int nvenc_enqueue_timestamp(AVFifoBuffer *f, int64_t pts)
1032 {
1033 return av_fifo_generic_write(f, &pts, sizeof(pts), NULL);
1034 }
1035
1036 static inline int nvenc_dequeue_timestamp(AVFifoBuffer *f, int64_t *pts)
1037 {
1038 return av_fifo_generic_read(f, pts, sizeof(*pts), NULL);
1039 }
1040
1041 static inline int nvenc_enqueue_surface(AVFifoBuffer *f,
1042 NVENCOutputSurface *surf)
1043 {
1044 surf->busy = 1;
1045 return av_fifo_generic_write(f, &surf, sizeof(surf), NULL);
1046 }
1047
1048 static inline int nvenc_dequeue_surface(AVFifoBuffer *f,
1049 NVENCOutputSurface **surf)
1050 {
1051 return av_fifo_generic_read(f, surf, sizeof(*surf), NULL);
1052 }
1053
1054 static int nvenc_set_timestamp(AVCodecContext *avctx,
1055 NV_ENC_LOCK_BITSTREAM *params,
1056 AVPacket *pkt)
1057 {
1058 NVENCContext *ctx = avctx->priv_data;
1059
1060 pkt->pts = params->outputTimeStamp;
1061 pkt->duration = params->outputDuration;
1062
1063 /* generate the first dts by linearly extrapolating the
1064 * first two pts values to the past */
1065 if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
1066 ctx->initial_pts[1] != AV_NOPTS_VALUE) {
1067 int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
1068 int64_t delta;
1069
1070 if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
1071 (ts0 > 0 && ts1 < INT64_MIN + ts0))
1072 return AVERROR(ERANGE);
1073 delta = ts1 - ts0;
1074
1075 if ((delta < 0 && ts0 > INT64_MAX + delta) ||
1076 (delta > 0 && ts0 < INT64_MIN + delta))
1077 return AVERROR(ERANGE);
1078 pkt->dts = ts0 - delta;
1079
1080 ctx->first_packet_output = 1;
1081 return 0;
1082 }
1083 return nvenc_dequeue_timestamp(ctx->timestamps, &pkt->dts);
1084 }
1085
1086 static int nvenc_get_frame(AVCodecContext *avctx, AVPacket *pkt)
1087 {
1088 NVENCContext *ctx = avctx->priv_data;
1089 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1090 NV_ENC_LOCK_BITSTREAM params = { 0 };
1091 NVENCOutputSurface *out = NULL;
1092 int ret;
1093
1094 ret = nvenc_dequeue_surface(ctx->ready, &out);
1095 if (ret)
1096 return ret;
1097
1098 params.version = NV_ENC_LOCK_BITSTREAM_VER;
1099 params.outputBitstream = out->out;
1100
1101 ret = nv->nvEncLockBitstream(ctx->nvenc_ctx, &params);
1102 if (ret < 0)
1103 return nvenc_print_error(avctx, ret, "Cannot lock the bitstream");
1104
1105 ret = ff_alloc_packet(pkt, params.bitstreamSizeInBytes);
1106 if (ret < 0)
1107 return ret;
1108
1109 memcpy(pkt->data, params.bitstreamBufferPtr, pkt->size);
1110
1111 ret = nv->nvEncUnlockBitstream(ctx->nvenc_ctx, out->out);
1112 if (ret < 0)
1113 return nvenc_print_error(avctx, ret, "Cannot unlock the bitstream");
1114
1115 out->busy = out->in->locked = 0;
1116
1117 ret = nvenc_set_timestamp(avctx, &params, pkt);
1118 if (ret < 0)
1119 return ret;
1120
1121 switch (params.pictureType) {
1122 case NV_ENC_PIC_TYPE_IDR:
1123 pkt->flags |= AV_PKT_FLAG_KEY;
1124 #if FF_API_CODED_FRAME
1125 FF_DISABLE_DEPRECATION_WARNINGS
1126 case NV_ENC_PIC_TYPE_INTRA_REFRESH:
1127 case NV_ENC_PIC_TYPE_I:
1128 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
1129 break;
1130 case NV_ENC_PIC_TYPE_P:
1131 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
1132 break;
1133 case NV_ENC_PIC_TYPE_B:
1134 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;
1135 break;
1136 case NV_ENC_PIC_TYPE_BI:
1137 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_BI;
1138 break;
1139 FF_ENABLE_DEPRECATION_WARNINGS
1140 #endif
1141 }
1142
1143 return 0;
1144 }
1145
1146 static int output_ready(AVCodecContext *avctx, int flush)
1147 {
1148 NVENCContext *ctx = avctx->priv_data;
1149
1150 /* when B-frames are enabled, we wait for two initial timestamps to
1151 * calculate the first dts */
1152 if (!flush && avctx->max_b_frames > 0 &&
1153 (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
1154 return 0;
1155 return av_fifo_size(ctx->ready) > 0;
1156 }
1157
1158 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1159 const AVFrame *frame, int *got_packet)
1160 {
1161 NVENCContext *ctx = avctx->priv_data;
1162 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1163 NV_ENC_PIC_PARAMS params = { 0 };
1164 NVENCInputSurface *in = NULL;
1165 NVENCOutputSurface *out = NULL;
1166 int enc_ret, ret;
1167
1168 params.version = NV_ENC_PIC_PARAMS_VER;
1169
1170 if (frame) {
1171 ret = nvenc_enqueue_frame(avctx, frame, &in);
1172 if (ret < 0)
1173 return ret;
1174 out = get_output_surface(ctx);
1175 if (!out)
1176 return AVERROR_BUG;
1177
1178 out->in = in;
1179
1180 params.inputBuffer = in->in;
1181 params.bufferFmt = in->format;
1182 params.inputWidth = frame->width;
1183 params.inputHeight = frame->height;
1184 params.outputBitstream = out->out;
1185 params.inputTimeStamp = frame->pts;
1186
1187 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1188 if (frame->top_field_first)
1189 params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
1190 else
1191 params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
1192 } else {
1193 params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1194 }
1195
1196 nvenc_codec_specific_pic_params(avctx, &params);
1197
1198 ret = nvenc_enqueue_timestamp(ctx->timestamps, frame->pts);
1199 if (ret < 0)
1200 return ret;
1201
1202 if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
1203 ctx->initial_pts[0] = frame->pts;
1204 else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
1205 ctx->initial_pts[1] = frame->pts;
1206 } else {
1207 params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1208 }
1209
1210 enc_ret = nv->nvEncEncodePicture(ctx->nvenc_ctx, &params);
1211 if (enc_ret != NV_ENC_SUCCESS &&
1212 enc_ret != NV_ENC_ERR_NEED_MORE_INPUT)
1213 return nvenc_print_error(avctx, enc_ret, "Error encoding the frame");
1214
1215 if (out) {
1216 ret = nvenc_enqueue_surface(ctx->pending, out);
1217 if (ret < 0)
1218 return ret;
1219 }
1220
1221 /* all the pending buffers are now ready for output */
1222 if (enc_ret == NV_ENC_SUCCESS) {
1223 while (av_fifo_size(ctx->pending) > 0) {
1224 av_fifo_generic_read(ctx->pending, &out, sizeof(out), NULL);
1225 av_fifo_generic_write(ctx->ready, &out, sizeof(out), NULL);
1226 }
1227 }
1228
1229 if (output_ready(avctx, !frame)) {
1230 ret = nvenc_get_frame(avctx, pkt);
1231 if (ret < 0)
1232 return ret;
1233 *got_packet = 1;
1234 } else {
1235 *got_packet = 0;
1236 }
1237
1238 return 0;
1239 }