]> git.sesse.net Git - ffmpeg/blob - libavcodec/nvenc.c
vp9: Add bsf to merge superframes
[ffmpeg] / libavcodec / nvenc.c
1 /*
2  * NVIDIA NVENC Support
3  * Copyright (C) 2015 Luca Barbato
4  * Copyright (C) 2015 Philip Langdale <philipl@overt.org>
5  * Copyright (C) 2014 Timo Rothenpieler <timo@rothenpieler.org>
6  *
7  * This file is part of Libav.
8  *
9  * Libav is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * Libav is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with Libav; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22  */
23
24 #include "config.h"
25
26 #include <nvEncodeAPI.h>
27 #include <string.h>
28
29 #define CUDA_LIBNAME "libcuda.so"
30
31 #if HAVE_DLFCN_H
32 #include <dlfcn.h>
33
34 #define NVENC_LIBNAME "libnvidia-encode.so"
35
36 #elif HAVE_WINDOWS_H
37 #include <windows.h>
38
39 #if ARCH_X86_64
40 #define NVENC_LIBNAME "nvEncodeAPI64.dll"
41 #else
42 #define NVENC_LIBNAME "nvEncodeAPI.dll"
43 #endif
44
45 #define dlopen(filename, flags) LoadLibrary((filename))
46 #define dlsym(handle, symbol)   GetProcAddress(handle, symbol)
47 #define dlclose(handle)         FreeLibrary(handle)
48 #endif
49
50 #include "libavutil/common.h"
51 #include "libavutil/hwcontext.h"
52 #include "libavutil/imgutils.h"
53 #include "libavutil/mem.h"
54 #include "avcodec.h"
55 #include "internal.h"
56 #include "nvenc.h"
57
58 #if CONFIG_CUDA
59 #include "libavutil/hwcontext_cuda.h"
60 #endif
61
62 #define NVENC_CAP 0x30
63 #define BITSTREAM_BUFFER_SIZE 1024 * 1024
64 #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR ||               \
65                     rc == NV_ENC_PARAMS_RC_2_PASS_QUALITY ||    \
66                     rc == NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP)
67
68 #define LOAD_LIBRARY(l, path)                   \
69     do {                                        \
70         if (!((l) = dlopen(path, RTLD_LAZY))) { \
71             av_log(avctx, AV_LOG_ERROR,         \
72                    "Cannot load %s\n",          \
73                    path);                       \
74             return AVERROR_UNKNOWN;             \
75         }                                       \
76     } while (0)
77
78 #define LOAD_SYMBOL(fun, lib, symbol)        \
79     do {                                     \
80         if (!((fun) = dlsym(lib, symbol))) { \
81             av_log(avctx, AV_LOG_ERROR,      \
82                    "Cannot load %s\n",       \
83                    symbol);                  \
84             return AVERROR_UNKNOWN;          \
85         }                                    \
86     } while (0)
87
88 const enum AVPixelFormat ff_nvenc_pix_fmts[] = {
89     AV_PIX_FMT_NV12,
90     AV_PIX_FMT_YUV420P,
91     AV_PIX_FMT_YUV444P,
92 #if NVENCAPI_MAJOR_VERSION >= 7
93     AV_PIX_FMT_P010,
94     AV_PIX_FMT_YUV444P16,
95 #endif
96 #if CONFIG_CUDA
97     AV_PIX_FMT_CUDA,
98 #endif
99     AV_PIX_FMT_NONE
100 };
101
102 #define IS_10BIT(pix_fmt)  (pix_fmt == AV_PIX_FMT_P010    || \
103                             pix_fmt == AV_PIX_FMT_YUV444P16)
104
105 #define IS_YUV444(pix_fmt) (pix_fmt == AV_PIX_FMT_YUV444P || \
106                             pix_fmt == AV_PIX_FMT_YUV444P16)
107
108 static const struct {
109     NVENCSTATUS nverr;
110     int         averr;
111     const char *desc;
112 } nvenc_errors[] = {
113     { NV_ENC_SUCCESS,                      0,                "success"                  },
114     { NV_ENC_ERR_NO_ENCODE_DEVICE,         AVERROR(ENOENT),  "no encode device"         },
115     { NV_ENC_ERR_UNSUPPORTED_DEVICE,       AVERROR(ENOSYS),  "unsupported device"       },
116     { NV_ENC_ERR_INVALID_ENCODERDEVICE,    AVERROR(EINVAL),  "invalid encoder device"   },
117     { NV_ENC_ERR_INVALID_DEVICE,           AVERROR(EINVAL),  "invalid device"           },
118     { NV_ENC_ERR_DEVICE_NOT_EXIST,         AVERROR(EIO),     "device does not exist"    },
119     { NV_ENC_ERR_INVALID_PTR,              AVERROR(EFAULT),  "invalid ptr"              },
120     { NV_ENC_ERR_INVALID_EVENT,            AVERROR(EINVAL),  "invalid event"            },
121     { NV_ENC_ERR_INVALID_PARAM,            AVERROR(EINVAL),  "invalid param"            },
122     { NV_ENC_ERR_INVALID_CALL,             AVERROR(EINVAL),  "invalid call"             },
123     { NV_ENC_ERR_OUT_OF_MEMORY,            AVERROR(ENOMEM),  "out of memory"            },
124     { NV_ENC_ERR_ENCODER_NOT_INITIALIZED,  AVERROR(EINVAL),  "encoder not initialized"  },
125     { NV_ENC_ERR_UNSUPPORTED_PARAM,        AVERROR(ENOSYS),  "unsupported param"        },
126     { NV_ENC_ERR_LOCK_BUSY,                AVERROR(EBUSY),   "lock busy"                },
127     { NV_ENC_ERR_NOT_ENOUGH_BUFFER,        AVERROR(ENOBUFS), "not enough buffer"        },
128     { NV_ENC_ERR_INVALID_VERSION,          AVERROR(EINVAL),  "invalid version"          },
129     { NV_ENC_ERR_MAP_FAILED,               AVERROR(EIO),     "map failed"               },
130     /* this is error should always be treated specially, so this "mapping"
131      * is for completeness only */
132     { NV_ENC_ERR_NEED_MORE_INPUT,          AVERROR_UNKNOWN,  "need more input"          },
133     { NV_ENC_ERR_ENCODER_BUSY,             AVERROR(EBUSY),   "encoder busy"             },
134     { NV_ENC_ERR_EVENT_NOT_REGISTERD,      AVERROR(EBADF),   "event not registered"     },
135     { NV_ENC_ERR_GENERIC,                  AVERROR_UNKNOWN,  "generic error"            },
136     { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY,  AVERROR(EINVAL),  "incompatible client key"  },
137     { NV_ENC_ERR_UNIMPLEMENTED,            AVERROR(ENOSYS),  "unimplemented"            },
138     { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO),     "resource register failed" },
139     { NV_ENC_ERR_RESOURCE_NOT_REGISTERED,  AVERROR(EBADF),   "resource not registered"  },
140     { NV_ENC_ERR_RESOURCE_NOT_MAPPED,      AVERROR(EBADF),   "resource not mapped"      },
141 };
142
143 static int nvenc_map_error(NVENCSTATUS err, const char **desc)
144 {
145     int i;
146     for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
147         if (nvenc_errors[i].nverr == err) {
148             if (desc)
149                 *desc = nvenc_errors[i].desc;
150             return nvenc_errors[i].averr;
151         }
152     }
153     if (desc)
154         *desc = "unknown error";
155     return AVERROR_UNKNOWN;
156 }
157
158 static int nvenc_print_error(void *log_ctx, NVENCSTATUS err,
159                              const char *error_string)
160 {
161     const char *desc;
162     int ret;
163     ret = nvenc_map_error(err, &desc);
164     av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
165     return ret;
166 }
167
168 static av_cold int nvenc_load_libraries(AVCodecContext *avctx)
169 {
170     NVENCContext *ctx         = avctx->priv_data;
171     NVENCLibraryContext *nvel = &ctx->nvel;
172     PNVENCODEAPICREATEINSTANCE nvenc_create_instance;
173     NVENCSTATUS err;
174
175 #if CONFIG_CUDA
176     nvel->cu_init                      = cuInit;
177     nvel->cu_device_get_count          = cuDeviceGetCount;
178     nvel->cu_device_get                = cuDeviceGet;
179     nvel->cu_device_get_name           = cuDeviceGetName;
180     nvel->cu_device_compute_capability = cuDeviceComputeCapability;
181     nvel->cu_ctx_create                = cuCtxCreate_v2;
182     nvel->cu_ctx_pop_current           = cuCtxPopCurrent_v2;
183     nvel->cu_ctx_push_current          = cuCtxPushCurrent_v2;
184     nvel->cu_ctx_destroy               = cuCtxDestroy_v2;
185 #else
186     LOAD_LIBRARY(nvel->cuda, CUDA_LIBNAME);
187
188     LOAD_SYMBOL(nvel->cu_init, nvel->cuda, "cuInit");
189     LOAD_SYMBOL(nvel->cu_device_get_count, nvel->cuda, "cuDeviceGetCount");
190     LOAD_SYMBOL(nvel->cu_device_get, nvel->cuda, "cuDeviceGet");
191     LOAD_SYMBOL(nvel->cu_device_get_name, nvel->cuda, "cuDeviceGetName");
192     LOAD_SYMBOL(nvel->cu_device_compute_capability, nvel->cuda,
193                 "cuDeviceComputeCapability");
194     LOAD_SYMBOL(nvel->cu_ctx_create, nvel->cuda, "cuCtxCreate_v2");
195     LOAD_SYMBOL(nvel->cu_ctx_pop_current, nvel->cuda, "cuCtxPopCurrent_v2");
196     LOAD_SYMBOL(nvel->cu_ctx_push_current, nvel->cuda, "cuCtxPushCurrent_v2");
197     LOAD_SYMBOL(nvel->cu_ctx_destroy, nvel->cuda, "cuCtxDestroy_v2");
198 #endif
199
200     LOAD_LIBRARY(nvel->nvenc, NVENC_LIBNAME);
201
202     LOAD_SYMBOL(nvenc_create_instance, nvel->nvenc,
203                 "NvEncodeAPICreateInstance");
204
205     nvel->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
206
207     err = nvenc_create_instance(&nvel->nvenc_funcs);
208     if (err != NV_ENC_SUCCESS)
209         return nvenc_print_error(avctx, err, "Cannot create the NVENC instance");
210
211     return 0;
212 }
213
214 static int nvenc_open_session(AVCodecContext *avctx)
215 {
216     NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
217     NVENCContext *ctx                           = avctx->priv_data;
218     NV_ENCODE_API_FUNCTION_LIST *nv             = &ctx->nvel.nvenc_funcs;
219     int ret;
220
221     params.version    = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
222     params.apiVersion = NVENCAPI_VERSION;
223     params.device     = ctx->cu_context;
224     params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
225
226     ret = nv->nvEncOpenEncodeSessionEx(&params, &ctx->nvenc_ctx);
227     if (ret != NV_ENC_SUCCESS) {
228         ctx->nvenc_ctx = NULL;
229         return nvenc_print_error(avctx, ret, "Cannot open the NVENC Session");
230     }
231
232     return 0;
233 }
234
235 static int nvenc_check_codec_support(AVCodecContext *avctx)
236 {
237     NVENCContext *ctx               = avctx->priv_data;
238     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
239     int i, ret, count = 0;
240     GUID *guids = NULL;
241
242     ret = nv->nvEncGetEncodeGUIDCount(ctx->nvenc_ctx, &count);
243
244     if (ret != NV_ENC_SUCCESS || !count)
245         return AVERROR(ENOSYS);
246
247     guids = av_malloc(count * sizeof(GUID));
248     if (!guids)
249         return AVERROR(ENOMEM);
250
251     ret = nv->nvEncGetEncodeGUIDs(ctx->nvenc_ctx, guids, count, &count);
252     if (ret != NV_ENC_SUCCESS) {
253         ret = AVERROR(ENOSYS);
254         goto fail;
255     }
256
257     ret = AVERROR(ENOSYS);
258     for (i = 0; i < count; i++) {
259         if (!memcmp(&guids[i], &ctx->params.encodeGUID, sizeof(*guids))) {
260             ret = 0;
261             break;
262         }
263     }
264
265 fail:
266     av_free(guids);
267
268     return ret;
269 }
270
271 static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
272 {
273     NVENCContext *ctx               = avctx->priv_data;
274     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
275     NV_ENC_CAPS_PARAM params        = { 0 };
276     int ret, val = 0;
277
278     params.version     = NV_ENC_CAPS_PARAM_VER;
279     params.capsToQuery = cap;
280
281     ret = nv->nvEncGetEncodeCaps(ctx->nvenc_ctx, ctx->params.encodeGUID, &params, &val);
282
283     if (ret == NV_ENC_SUCCESS)
284         return val;
285     return 0;
286 }
287
288 static int nvenc_check_capabilities(AVCodecContext *avctx)
289 {
290     NVENCContext *ctx = avctx->priv_data;
291     int ret;
292
293     ret = nvenc_check_codec_support(avctx);
294     if (ret < 0) {
295         av_log(avctx, AV_LOG_VERBOSE, "Codec not supported\n");
296         return ret;
297     }
298
299     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
300     if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P && ret <= 0) {
301         av_log(avctx, AV_LOG_VERBOSE, "YUV444P not supported\n");
302         return AVERROR(ENOSYS);
303     }
304
305     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
306     if (ret < avctx->width) {
307         av_log(avctx, AV_LOG_VERBOSE, "Width %d exceeds %d\n",
308                avctx->width, ret);
309         return AVERROR(ENOSYS);
310     }
311
312     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
313     if (ret < avctx->height) {
314         av_log(avctx, AV_LOG_VERBOSE, "Height %d exceeds %d\n",
315                avctx->height, ret);
316         return AVERROR(ENOSYS);
317     }
318
319     ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
320     if (ret < avctx->max_b_frames) {
321         av_log(avctx, AV_LOG_VERBOSE, "Max B-frames %d exceed %d\n",
322                avctx->max_b_frames, ret);
323
324         return AVERROR(ENOSYS);
325     }
326
327     return 0;
328 }
329
330 static int nvenc_check_device(AVCodecContext *avctx, int idx)
331 {
332     NVENCContext *ctx               = avctx->priv_data;
333     NVENCLibraryContext *nvel       = &ctx->nvel;
334     char name[128]                  = { 0 };
335     int major, minor, ret;
336     CUdevice cu_device;
337     CUcontext dummy;
338     int loglevel = AV_LOG_VERBOSE;
339
340     if (ctx->device == LIST_DEVICES)
341         loglevel = AV_LOG_INFO;
342
343     ret = nvel->cu_device_get(&cu_device, idx);
344     if (ret != CUDA_SUCCESS) {
345         av_log(avctx, AV_LOG_ERROR,
346                "Cannot access the CUDA device %d\n",
347                idx);
348         return -1;
349     }
350
351     ret = nvel->cu_device_get_name(name, sizeof(name), cu_device);
352     if (ret != CUDA_SUCCESS)
353         return -1;
354
355     ret = nvel->cu_device_compute_capability(&major, &minor, cu_device);
356     if (ret != CUDA_SUCCESS)
357         return -1;
358
359     av_log(avctx, loglevel, "Device %d [%s] ", cu_device, name);
360
361     if (((major << 4) | minor) < NVENC_CAP)
362         goto fail;
363
364     if (ctx->device != idx && ctx->device != ANY_DEVICE)
365         return -1;
366
367     ret = nvel->cu_ctx_create(&ctx->cu_context_internal, 0, cu_device);
368     if (ret != CUDA_SUCCESS)
369         goto fail;
370
371     ctx->cu_context = ctx->cu_context_internal;
372
373     ret = nvel->cu_ctx_pop_current(&dummy);
374     if (ret != CUDA_SUCCESS)
375         goto fail2;
376
377     if ((ret = nvenc_open_session(avctx)) < 0)
378         goto fail2;
379
380     if ((ret = nvenc_check_capabilities(avctx)) < 0)
381         goto fail3;
382
383     av_log(avctx, loglevel, "supports NVENC\n");
384
385     if (ctx->device == idx || ctx->device == ANY_DEVICE)
386         return 0;
387
388 fail3:
389     nvel->nvenc_funcs.nvEncDestroyEncoder(ctx->nvenc_ctx);
390     ctx->nvenc_ctx = NULL;
391
392 fail2:
393     nvel->cu_ctx_destroy(ctx->cu_context_internal);
394     ctx->cu_context_internal = NULL;
395
396 fail:
397     if (ret != 0)
398         av_log(avctx, loglevel, "does not support NVENC (major %d minor %d)\n",
399                major, minor);
400
401     return AVERROR(ENOSYS);
402 }
403
404 static int nvenc_setup_device(AVCodecContext *avctx)
405 {
406     NVENCContext *ctx         = avctx->priv_data;
407     NVENCLibraryContext *nvel = &ctx->nvel;
408
409     switch (avctx->codec->id) {
410     case AV_CODEC_ID_H264:
411         ctx->params.encodeGUID = NV_ENC_CODEC_H264_GUID;
412         break;
413     case AV_CODEC_ID_HEVC:
414         ctx->params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
415         break;
416     default:
417         return AVERROR_BUG;
418     }
419
420     if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
421 #if CONFIG_CUDA
422         AVHWFramesContext   *frames_ctx;
423         AVCUDADeviceContext *device_hwctx;
424         int ret;
425
426         if (!avctx->hw_frames_ctx)
427             return AVERROR(EINVAL);
428
429         frames_ctx   = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
430         device_hwctx = frames_ctx->device_ctx->hwctx;
431
432         ctx->cu_context = device_hwctx->cuda_ctx;
433
434         ret = nvenc_open_session(avctx);
435         if (ret < 0)
436             return ret;
437
438         ret = nvenc_check_capabilities(avctx);
439         if (ret < 0)
440             return ret;
441 #else
442         return AVERROR_BUG;
443 #endif
444     } else {
445         int i, nb_devices = 0;
446
447         if ((nvel->cu_init(0)) != CUDA_SUCCESS) {
448             av_log(avctx, AV_LOG_ERROR,
449                    "Cannot init CUDA\n");
450             return AVERROR_UNKNOWN;
451         }
452
453         if ((nvel->cu_device_get_count(&nb_devices)) != CUDA_SUCCESS) {
454             av_log(avctx, AV_LOG_ERROR,
455                    "Cannot enumerate the CUDA devices\n");
456             return AVERROR_UNKNOWN;
457         }
458
459
460         for (i = 0; i < nb_devices; ++i) {
461             if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
462                 return 0;
463         }
464
465         if (ctx->device == LIST_DEVICES)
466             return AVERROR_EXIT;
467
468         return AVERROR(ENOSYS);
469     }
470
471     return 0;
472 }
473
474 typedef struct GUIDTuple {
475     const GUID guid;
476     int flags;
477 } GUIDTuple;
478
479 #define PRESET_ALIAS(alias, name, ...) \
480     [PRESET_ ## alias] = { NV_ENC_PRESET_ ## name ## _GUID, __VA_ARGS__ }
481
482 #define PRESET(name, ...) PRESET_ALIAS(name, name, __VA_ARGS__)
483
484 static int nvenc_map_preset(NVENCContext *ctx)
485 {
486     GUIDTuple presets[] = {
487         PRESET(DEFAULT),
488         PRESET(HP),
489         PRESET(HQ),
490         PRESET(BD),
491         PRESET(LOW_LATENCY_DEFAULT, NVENC_LOWLATENCY),
492         PRESET(LOW_LATENCY_HP,      NVENC_LOWLATENCY),
493         PRESET(LOW_LATENCY_HQ,      NVENC_LOWLATENCY),
494         PRESET(LOSSLESS_DEFAULT,    NVENC_LOSSLESS),
495         PRESET(LOSSLESS_HP,         NVENC_LOSSLESS),
496         PRESET_ALIAS(SLOW, HQ,      NVENC_TWO_PASSES),
497         PRESET_ALIAS(MEDIUM, HQ,    NVENC_ONE_PASS),
498         PRESET_ALIAS(FAST, HP,      NVENC_ONE_PASS)
499     };
500
501     GUIDTuple *t = &presets[ctx->preset];
502
503     ctx->params.presetGUID = t->guid;
504     ctx->flags             = t->flags;
505
506     return AVERROR(EINVAL);
507 }
508
509 #undef PRESET
510 #undef PRESET_ALIAS
511
512 static void set_constqp(AVCodecContext *avctx, NV_ENC_RC_PARAMS *rc)
513 {
514     NVENCContext *ctx = avctx->priv_data;
515     rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
516
517     if (ctx->init_qp_p >= 0) {
518         rc->constQP.qpInterP = ctx->init_qp_p;
519         if (ctx->init_qp_i >= 0 && ctx->init_qp_b >= 0) {
520             rc->constQP.qpIntra  = ctx->init_qp_i;
521             rc->constQP.qpInterB = ctx->init_qp_b;
522         } else if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
523             rc->constQP.qpIntra  = av_clip(rc->constQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
524             rc->constQP.qpInterB = av_clip(rc->constQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
525         } else {
526             rc->constQP.qpIntra  = rc->constQP.qpInterP;
527             rc->constQP.qpInterB = rc->constQP.qpInterP;
528         }
529     } else if (avctx->global_quality >= 0) {
530         rc->constQP.qpInterP = avctx->global_quality;
531         rc->constQP.qpInterB = avctx->global_quality;
532         rc->constQP.qpIntra  = avctx->global_quality;
533     }
534 }
535
536 static void set_vbr(AVCodecContext *avctx, NV_ENC_RC_PARAMS *rc)
537 {
538     NVENCContext *ctx    = avctx->priv_data;
539
540     if (avctx->qmin >= 0) {
541         rc->enableMinQP    = 1;
542         rc->minQP.qpInterB = avctx->qmin;
543         rc->minQP.qpInterP = avctx->qmin;
544         rc->minQP.qpIntra  = avctx->qmin;
545     }
546
547     if (avctx->qmax >= 0) {
548         rc->enableMaxQP = 1;
549         rc->maxQP.qpInterB = avctx->qmax;
550         rc->maxQP.qpInterP = avctx->qmax;
551         rc->maxQP.qpIntra  = avctx->qmax;
552     }
553
554     if (ctx->init_qp_p >= 0) {
555         rc->enableInitialRCQP = 1;
556         rc->initialRCQP.qpInterP = ctx->init_qp_p;
557         if (ctx->init_qp_i < 0) {
558             if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
559                 rc->initialRCQP.qpIntra = av_clip(rc->initialRCQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
560             } else {
561                 rc->initialRCQP.qpIntra = rc->initialRCQP.qpInterP;
562             }
563         } else {
564             rc->initialRCQP.qpIntra = ctx->init_qp_i;
565         }
566
567         if (ctx->init_qp_b < 0) {
568             if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
569                 rc->initialRCQP.qpInterB = av_clip(rc->initialRCQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
570             } else {
571                 rc->initialRCQP.qpInterB = rc->initialRCQP.qpInterP;
572             }
573         } else {
574             rc->initialRCQP.qpInterB = ctx->init_qp_b;
575         }
576     }
577 }
578
579 static void set_lossless(AVCodecContext *avctx, NV_ENC_RC_PARAMS *rc)
580 {
581     rc->rateControlMode  = NV_ENC_PARAMS_RC_CONSTQP;
582     rc->constQP.qpInterB = 0;
583     rc->constQP.qpInterP = 0;
584     rc->constQP.qpIntra  = 0;
585 }
586
587 static void nvenc_override_rate_control(AVCodecContext *avctx,
588                                         NV_ENC_RC_PARAMS *rc)
589 {
590     NVENCContext *ctx    = avctx->priv_data;
591
592     switch (ctx->rc) {
593     case NV_ENC_PARAMS_RC_CONSTQP:
594         set_constqp(avctx, rc);
595         return;
596     case NV_ENC_PARAMS_RC_2_PASS_VBR:
597     case NV_ENC_PARAMS_RC_VBR:
598         set_vbr(avctx, rc);
599         break;
600     case NV_ENC_PARAMS_RC_VBR_MINQP:
601         if (avctx->qmin < 0) {
602             av_log(avctx, AV_LOG_WARNING,
603                    "The variable bitrate rate-control requires "
604                    "the 'qmin' option set.\n");
605             return;
606         }
607         set_vbr(avctx, rc);
608         break;
609     case NV_ENC_PARAMS_RC_CBR:
610         break;
611     case NV_ENC_PARAMS_RC_2_PASS_QUALITY:
612     case NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP:
613         if (!(ctx->flags & NVENC_LOWLATENCY)) {
614             av_log(avctx, AV_LOG_WARNING,
615                    "The multipass rate-control requires "
616                    "a low-latency preset.\n");
617             return;
618         }
619     }
620
621     rc->rateControlMode = ctx->rc;
622 }
623
624 static void nvenc_setup_rate_control(AVCodecContext *avctx)
625 {
626     NVENCContext *ctx    = avctx->priv_data;
627     NV_ENC_RC_PARAMS *rc = &ctx->config.rcParams;
628
629     if (avctx->bit_rate > 0)
630         rc->averageBitRate = avctx->bit_rate;
631
632     if (avctx->rc_max_rate > 0)
633         rc->maxBitRate = avctx->rc_max_rate;
634
635     if (ctx->rc > 0) {
636         nvenc_override_rate_control(avctx, rc);
637     } else if (ctx->flags & NVENC_LOSSLESS) {
638         set_lossless(avctx, rc);
639     } else if (avctx->global_quality > 0) {
640         set_constqp(avctx, rc);
641     } else {
642         if (ctx->flags & NVENC_TWO_PASSES)
643             rc->rateControlMode = NV_ENC_PARAMS_RC_2_PASS_VBR;
644         else
645             rc->rateControlMode = NV_ENC_PARAMS_RC_VBR;
646         set_vbr(avctx, rc);
647     }
648
649     if (avctx->rc_buffer_size > 0)
650         rc->vbvBufferSize = avctx->rc_buffer_size;
651
652     if (rc->averageBitRate > 0)
653         avctx->bit_rate = rc->averageBitRate;
654
655 #if NVENCAPI_MAJOR_VERSION >= 7
656     if (ctx->aq) {
657         ctx->config.rcParams.enableAQ   = 1;
658         ctx->config.rcParams.aqStrength = ctx->aq_strength;
659         av_log(avctx, AV_LOG_VERBOSE, "AQ enabled.\n");
660     }
661
662     if (ctx->temporal_aq) {
663         ctx->config.rcParams.enableTemporalAQ = 1;
664         av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ enabled.\n");
665     }
666
667     if (ctx->rc_lookahead > 0) {
668         int lkd_bound = FFMIN(ctx->nb_surfaces, ctx->async_depth) -
669                         ctx->config.frameIntervalP - 4;
670
671         if (lkd_bound < 0) {
672             av_log(avctx, AV_LOG_WARNING,
673                    "Lookahead not enabled. Increase buffer delay (-delay).\n");
674         } else {
675             ctx->config.rcParams.enableLookahead = 1;
676             ctx->config.rcParams.lookaheadDepth  = av_clip(ctx->rc_lookahead, 0, lkd_bound);
677             ctx->config.rcParams.disableIadapt   = ctx->no_scenecut;
678             ctx->config.rcParams.disableBadapt   = !ctx->b_adapt;
679             av_log(avctx, AV_LOG_VERBOSE,
680                    "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",
681                    ctx->config.rcParams.lookaheadDepth,
682                    ctx->config.rcParams.disableIadapt ? "disabled" : "enabled",
683                    ctx->config.rcParams.disableBadapt ? "disabled" : "enabled");
684         }
685     }
686
687     if (ctx->strict_gop) {
688         ctx->config.rcParams.strictGOPTarget = 1;
689         av_log(avctx, AV_LOG_VERBOSE, "Strict GOP target enabled.\n");
690     }
691
692     if (ctx->nonref_p)
693         ctx->config.rcParams.enableNonRefP = 1;
694
695     if (ctx->zerolatency)
696         ctx->config.rcParams.zeroReorderDelay = 1;
697
698     if (ctx->quality)
699         ctx->config.rcParams.targetQuality = ctx->quality;
700 #endif /* NVENCAPI_MAJOR_VERSION >= 7 */
701 }
702
703 static int nvenc_setup_h264_config(AVCodecContext *avctx)
704 {
705     NVENCContext *ctx                      = avctx->priv_data;
706     NV_ENC_CONFIG *cc                      = &ctx->config;
707     NV_ENC_CONFIG_H264 *h264               = &cc->encodeCodecConfig.h264Config;
708     NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
709
710     vui->colourDescriptionPresentFlag = avctx->colorspace      != AVCOL_SPC_UNSPECIFIED ||
711                                         avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
712                                         avctx->color_trc       != AVCOL_TRC_UNSPECIFIED;
713
714     vui->colourMatrix            = avctx->colorspace;
715     vui->colourPrimaries         = avctx->color_primaries;
716     vui->transferCharacteristics = avctx->color_trc;
717
718     vui->videoFullRangeFlag = avctx->color_range == AVCOL_RANGE_JPEG;
719
720     vui->videoSignalTypePresentFlag = vui->colourDescriptionPresentFlag ||
721                                       vui->videoFullRangeFlag;
722
723     h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
724     h264->repeatSPSPPS  = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
725     h264->outputAUD     = 1;
726
727     h264->maxNumRefFrames = avctx->refs;
728     h264->idrPeriod       = cc->gopLength;
729
730     h264->sliceMode     = 3;
731     h264->sliceModeData = FFMAX(avctx->slices, 1);
732
733     if (ctx->flags & NVENC_LOSSLESS)
734         h264->qpPrimeYZeroTransformBypassFlag = 1;
735
736     if (IS_CBR(cc->rcParams.rateControlMode)) {
737         h264->outputBufferingPeriodSEI = 1;
738         h264->outputPictureTimingSEI   = 1;
739     }
740
741     if (ctx->profile)
742         avctx->profile = ctx->profile;
743
744     if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P)
745         h264->chromaFormatIDC = 3;
746     else
747         h264->chromaFormatIDC = 1;
748
749     switch (ctx->profile) {
750     case NV_ENC_H264_PROFILE_BASELINE:
751         cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
752         break;
753     case NV_ENC_H264_PROFILE_MAIN:
754         cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
755         break;
756     case NV_ENC_H264_PROFILE_HIGH:
757         cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
758         break;
759     case NV_ENC_H264_PROFILE_HIGH_444:
760         cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
761         break;
762     case NV_ENC_H264_PROFILE_CONSTRAINED_HIGH:
763         cc->profileGUID = NV_ENC_H264_PROFILE_CONSTRAINED_HIGH_GUID;
764         break;
765     }
766
767     if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P) {
768         cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
769         avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
770     }
771
772     h264->level = ctx->level;
773
774     return 0;
775 }
776
777 static int nvenc_setup_hevc_config(AVCodecContext *avctx)
778 {
779     NVENCContext *ctx                      = avctx->priv_data;
780     NV_ENC_CONFIG *cc                      = &ctx->config;
781     NV_ENC_CONFIG_HEVC *hevc               = &cc->encodeCodecConfig.hevcConfig;
782     NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
783
784     vui->colourDescriptionPresentFlag = avctx->colorspace      != AVCOL_SPC_UNSPECIFIED ||
785                                         avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
786                                         avctx->color_trc       != AVCOL_TRC_UNSPECIFIED;
787
788     vui->colourMatrix            = avctx->colorspace;
789     vui->colourPrimaries         = avctx->color_primaries;
790     vui->transferCharacteristics = avctx->color_trc;
791
792     vui->videoFullRangeFlag = avctx->color_range == AVCOL_RANGE_JPEG;
793
794     vui->videoSignalTypePresentFlag = vui->colourDescriptionPresentFlag ||
795                                       vui->videoFullRangeFlag;
796
797     hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
798     hevc->repeatSPSPPS  = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
799     hevc->outputAUD     = 1;
800
801     hevc->maxNumRefFramesInDPB = avctx->refs;
802     hevc->idrPeriod            = cc->gopLength;
803
804     if (IS_CBR(cc->rcParams.rateControlMode)) {
805         hevc->outputBufferingPeriodSEI = 1;
806         hevc->outputPictureTimingSEI   = 1;
807     }
808
809     switch (ctx->profile) {
810     case NV_ENC_HEVC_PROFILE_MAIN:
811         cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
812         avctx->profile  = FF_PROFILE_HEVC_MAIN;
813         break;
814 #if NVENCAPI_MAJOR_VERSION >= 7
815     case NV_ENC_HEVC_PROFILE_MAIN_10:
816         cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
817         avctx->profile  = FF_PROFILE_HEVC_MAIN_10;
818         break;
819     case NV_ENC_HEVC_PROFILE_REXT:
820         cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
821         avctx->profile  = FF_PROFILE_HEVC_REXT;
822         break;
823 #endif /* NVENCAPI_MAJOR_VERSION >= 7 */
824     }
825
826     // force setting profile for various input formats
827     switch (ctx->data_pix_fmt) {
828     case AV_PIX_FMT_YUV420P:
829     case AV_PIX_FMT_NV12:
830         cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
831         avctx->profile  = FF_PROFILE_HEVC_MAIN;
832         break;
833 #if NVENCAPI_MAJOR_VERSION >= 7
834     case AV_PIX_FMT_P010:
835         cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
836         avctx->profile  = FF_PROFILE_HEVC_MAIN_10;
837         break;
838     case AV_PIX_FMT_YUV444P:
839     case AV_PIX_FMT_YUV444P16:
840         cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
841         avctx->profile  = FF_PROFILE_HEVC_REXT;
842         break;
843 #endif /* NVENCAPI_MAJOR_VERSION >= 7 */
844     }
845
846 #if NVENCAPI_MAJOR_VERSION >= 7
847     hevc->chromaFormatIDC     = IS_YUV444(ctx->data_pix_fmt) ? 3 : 1;
848     hevc->pixelBitDepthMinus8 = IS_10BIT(ctx->data_pix_fmt)  ? 2 : 0;
849 #endif /* NVENCAPI_MAJOR_VERSION >= 7 */
850
851     hevc->sliceMode     = 3;
852     hevc->sliceModeData = FFMAX(avctx->slices, 1);
853
854     if (ctx->level) {
855         hevc->level = ctx->level;
856     } else {
857         hevc->level = NV_ENC_LEVEL_AUTOSELECT;
858     }
859
860     if (ctx->tier) {
861         hevc->tier = ctx->tier;
862     }
863
864     return 0;
865 }
866 static int nvenc_setup_codec_config(AVCodecContext *avctx)
867 {
868     switch (avctx->codec->id) {
869     case AV_CODEC_ID_H264:
870         return nvenc_setup_h264_config(avctx);
871     case AV_CODEC_ID_HEVC:
872         return nvenc_setup_hevc_config(avctx);
873     }
874     return 0;
875 }
876
877 static int nvenc_setup_encoder(AVCodecContext *avctx)
878 {
879     NVENCContext *ctx               = avctx->priv_data;
880     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
881     NV_ENC_PRESET_CONFIG preset_cfg = { 0 };
882     AVCPBProperties *cpb_props;
883     int ret;
884
885     ctx->params.version = NV_ENC_INITIALIZE_PARAMS_VER;
886
887     ctx->params.encodeHeight = avctx->height;
888     ctx->params.encodeWidth  = avctx->width;
889
890     if (avctx->sample_aspect_ratio.num &&
891         avctx->sample_aspect_ratio.den &&
892         (avctx->sample_aspect_ratio.num != 1 ||
893          avctx->sample_aspect_ratio.den != 1)) {
894         av_reduce(&ctx->params.darWidth,
895                   &ctx->params.darHeight,
896                   avctx->width * avctx->sample_aspect_ratio.num,
897                   avctx->height * avctx->sample_aspect_ratio.den,
898                   INT_MAX / 8);
899     } else {
900         ctx->params.darHeight = avctx->height;
901         ctx->params.darWidth  = avctx->width;
902     }
903
904     // De-compensate for hardware, dubiously, trying to compensate for
905     // playback at 704 pixel width.
906     if (avctx->width == 720 && (avctx->height == 480 || avctx->height == 576)) {
907         av_reduce(&ctx->params.darWidth, &ctx->params.darHeight,
908                   ctx->params.darWidth * 44,
909                   ctx->params.darHeight * 45,
910                   1024 * 1024);
911     }
912
913     ctx->params.frameRateNum = avctx->time_base.den;
914     ctx->params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
915
916     ctx->params.enableEncodeAsync = 0;
917     ctx->params.enablePTD         = 1;
918
919     ctx->params.encodeConfig = &ctx->config;
920
921     nvenc_map_preset(ctx);
922
923     preset_cfg.version           = NV_ENC_PRESET_CONFIG_VER;
924     preset_cfg.presetCfg.version = NV_ENC_CONFIG_VER;
925
926     ret = nv->nvEncGetEncodePresetConfig(ctx->nvenc_ctx,
927                                          ctx->params.encodeGUID,
928                                          ctx->params.presetGUID,
929                                          &preset_cfg);
930     if (ret != NV_ENC_SUCCESS)
931         return nvenc_print_error(avctx, ret, "Cannot get the preset configuration");
932
933     memcpy(&ctx->config, &preset_cfg.presetCfg, sizeof(ctx->config));
934
935     ctx->config.version = NV_ENC_CONFIG_VER;
936
937     if (avctx->gop_size > 0) {
938         if (avctx->max_b_frames > 0) {
939             /* 0 is intra-only,
940              * 1 is I/P only,
941              * 2 is one B-Frame,
942              * 3 two B-frames, and so on. */
943             ctx->config.frameIntervalP = avctx->max_b_frames + 1;
944         } else if (avctx->max_b_frames == 0) {
945             ctx->config.frameIntervalP = 1;
946         }
947         ctx->config.gopLength = avctx->gop_size;
948     } else if (avctx->gop_size == 0) {
949         ctx->config.frameIntervalP = 0;
950         ctx->config.gopLength      = 1;
951     }
952
953     if (ctx->config.frameIntervalP > 1)
954         avctx->max_b_frames = ctx->config.frameIntervalP - 1;
955
956     ctx->initial_pts[0] = AV_NOPTS_VALUE;
957     ctx->initial_pts[1] = AV_NOPTS_VALUE;
958
959     nvenc_setup_rate_control(avctx);
960
961     if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
962         ctx->config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
963     } else {
964         ctx->config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
965     }
966
967     if ((ret = nvenc_setup_codec_config(avctx)) < 0)
968         return ret;
969
970     ret = nv->nvEncInitializeEncoder(ctx->nvenc_ctx, &ctx->params);
971     if (ret != NV_ENC_SUCCESS)
972         return nvenc_print_error(avctx, ret, "InitializeEncoder failed");
973
974     cpb_props = ff_add_cpb_side_data(avctx);
975     if (!cpb_props)
976         return AVERROR(ENOMEM);
977     cpb_props->max_bitrate = avctx->rc_max_rate;
978     cpb_props->min_bitrate = avctx->rc_min_rate;
979     cpb_props->avg_bitrate = avctx->bit_rate;
980     cpb_props->buffer_size = avctx->rc_buffer_size;
981
982     return 0;
983 }
984
985 static int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
986 {
987     NVENCContext *ctx               = avctx->priv_data;
988     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
989     int ret;
990     NV_ENC_CREATE_BITSTREAM_BUFFER out_buffer = { 0 };
991
992     switch (ctx->data_pix_fmt) {
993     case AV_PIX_FMT_YUV420P:
994         ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YV12_PL;
995         break;
996     case AV_PIX_FMT_NV12:
997         ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_NV12_PL;
998         break;
999     case AV_PIX_FMT_YUV444P:
1000         ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YUV444_PL;
1001         break;
1002 #if NVENCAPI_MAJOR_VERSION >= 7
1003     case AV_PIX_FMT_P010:
1004         ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1005         break;
1006     case AV_PIX_FMT_YUV444P16:
1007         ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1008         break;
1009 #endif /* NVENCAPI_MAJOR_VERSION >= 7 */
1010     default:
1011         return AVERROR_BUG;
1012     }
1013
1014     if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1015         ctx->frames[idx].in_ref = av_frame_alloc();
1016         if (!ctx->frames[idx].in_ref)
1017             return AVERROR(ENOMEM);
1018     } else {
1019         NV_ENC_CREATE_INPUT_BUFFER in_buffer      = { 0 };
1020
1021         in_buffer.version  = NV_ENC_CREATE_INPUT_BUFFER_VER;
1022
1023         in_buffer.width  = avctx->width;
1024         in_buffer.height = avctx->height;
1025
1026         in_buffer.bufferFmt  = ctx->frames[idx].format;
1027         in_buffer.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED;
1028
1029         ret = nv->nvEncCreateInputBuffer(ctx->nvenc_ctx, &in_buffer);
1030         if (ret != NV_ENC_SUCCESS)
1031             return nvenc_print_error(avctx, ret, "CreateInputBuffer failed");
1032
1033         ctx->frames[idx].in     = in_buffer.inputBuffer;
1034     }
1035
1036     out_buffer.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1037     /* 1MB is large enough to hold most output frames.
1038      * NVENC increases this automatically if it is not enough. */
1039     out_buffer.size = BITSTREAM_BUFFER_SIZE;
1040
1041     out_buffer.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED;
1042
1043     ret = nv->nvEncCreateBitstreamBuffer(ctx->nvenc_ctx, &out_buffer);
1044     if (ret != NV_ENC_SUCCESS)
1045         return nvenc_print_error(avctx, ret, "CreateBitstreamBuffer failed");
1046
1047     ctx->frames[idx].out  = out_buffer.bitstreamBuffer;
1048
1049     return 0;
1050 }
1051
1052 static int nvenc_setup_surfaces(AVCodecContext *avctx)
1053 {
1054     NVENCContext *ctx = avctx->priv_data;
1055     int i, ret;
1056
1057     ctx->nb_surfaces = FFMAX(4 + avctx->max_b_frames,
1058                              ctx->nb_surfaces);
1059     ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
1060
1061
1062     ctx->frames = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->frames));
1063     if (!ctx->frames)
1064         return AVERROR(ENOMEM);
1065
1066     ctx->timestamps = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
1067     if (!ctx->timestamps)
1068         return AVERROR(ENOMEM);
1069     ctx->pending = av_fifo_alloc(ctx->nb_surfaces * sizeof(*ctx->frames));
1070     if (!ctx->pending)
1071         return AVERROR(ENOMEM);
1072     ctx->ready = av_fifo_alloc(ctx->nb_surfaces * sizeof(*ctx->frames));
1073     if (!ctx->ready)
1074         return AVERROR(ENOMEM);
1075
1076     for (i = 0; i < ctx->nb_surfaces; i++) {
1077         if ((ret = nvenc_alloc_surface(avctx, i)) < 0)
1078             return ret;
1079     }
1080
1081     return 0;
1082 }
1083
1084 #define EXTRADATA_SIZE 512
1085
1086 static int nvenc_setup_extradata(AVCodecContext *avctx)
1087 {
1088     NVENCContext *ctx                     = avctx->priv_data;
1089     NV_ENCODE_API_FUNCTION_LIST *nv       = &ctx->nvel.nvenc_funcs;
1090     NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1091     int ret;
1092
1093     avctx->extradata = av_mallocz(EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
1094     if (!avctx->extradata)
1095         return AVERROR(ENOMEM);
1096
1097     payload.version              = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1098     payload.spsppsBuffer         = avctx->extradata;
1099     payload.inBufferSize         = EXTRADATA_SIZE;
1100     payload.outSPSPPSPayloadSize = &avctx->extradata_size;
1101
1102     ret = nv->nvEncGetSequenceParams(ctx->nvenc_ctx, &payload);
1103     if (ret != NV_ENC_SUCCESS)
1104         return nvenc_print_error(avctx, ret, "Cannot get the extradata");
1105
1106     return 0;
1107 }
1108
1109 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
1110 {
1111     NVENCContext *ctx               = avctx->priv_data;
1112     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1113     int i;
1114
1115     /* the encoder has to be flushed before it can be closed */
1116     if (ctx->nvenc_ctx) {
1117         NV_ENC_PIC_PARAMS params        = { .version        = NV_ENC_PIC_PARAMS_VER,
1118                                             .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
1119
1120         nv->nvEncEncodePicture(ctx->nvenc_ctx, &params);
1121     }
1122
1123     av_fifo_free(ctx->timestamps);
1124     av_fifo_free(ctx->pending);
1125     av_fifo_free(ctx->ready);
1126
1127     if (ctx->frames) {
1128         for (i = 0; i < ctx->nb_surfaces; ++i) {
1129             if (avctx->pix_fmt != AV_PIX_FMT_CUDA) {
1130                 nv->nvEncDestroyInputBuffer(ctx->nvenc_ctx, ctx->frames[i].in);
1131             } else if (ctx->frames[i].in) {
1132                 nv->nvEncUnmapInputResource(ctx->nvenc_ctx, ctx->frames[i].in_map.mappedResource);
1133             }
1134
1135             av_frame_free(&ctx->frames[i].in_ref);
1136             nv->nvEncDestroyBitstreamBuffer(ctx->nvenc_ctx, ctx->frames[i].out);
1137         }
1138     }
1139     for (i = 0; i < ctx->nb_registered_frames; i++) {
1140         if (ctx->registered_frames[i].regptr)
1141             nv->nvEncUnregisterResource(ctx->nvenc_ctx, ctx->registered_frames[i].regptr);
1142     }
1143     ctx->nb_registered_frames = 0;
1144
1145     av_freep(&ctx->frames);
1146
1147     if (ctx->nvenc_ctx)
1148         nv->nvEncDestroyEncoder(ctx->nvenc_ctx);
1149
1150     if (ctx->cu_context_internal)
1151         ctx->nvel.cu_ctx_destroy(ctx->cu_context_internal);
1152
1153     if (ctx->nvel.nvenc)
1154         dlclose(ctx->nvel.nvenc);
1155
1156 #if !CONFIG_CUDA
1157     if (ctx->nvel.cuda)
1158         dlclose(ctx->nvel.cuda);
1159 #endif
1160
1161     return 0;
1162 }
1163
1164 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
1165 {
1166     NVENCContext *ctx = avctx->priv_data;
1167     int ret;
1168
1169     if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1170         AVHWFramesContext *frames_ctx;
1171         if (!avctx->hw_frames_ctx) {
1172             av_log(avctx, AV_LOG_ERROR,
1173                    "hw_frames_ctx must be set when using GPU frames as input\n");
1174             return AVERROR(EINVAL);
1175         }
1176         frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1177         ctx->data_pix_fmt = frames_ctx->sw_format;
1178     } else {
1179         ctx->data_pix_fmt = avctx->pix_fmt;
1180     }
1181
1182     if ((ret = nvenc_load_libraries(avctx)) < 0)
1183         return ret;
1184
1185     if ((ret = nvenc_setup_device(avctx)) < 0)
1186         return ret;
1187
1188     if ((ret = nvenc_setup_encoder(avctx)) < 0)
1189         return ret;
1190
1191     if ((ret = nvenc_setup_surfaces(avctx)) < 0)
1192         return ret;
1193
1194     if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1195         if ((ret = nvenc_setup_extradata(avctx)) < 0)
1196             return ret;
1197     }
1198
1199     return 0;
1200 }
1201
1202 static NVENCFrame *get_free_frame(NVENCContext *ctx)
1203 {
1204     int i;
1205
1206     for (i = 0; i < ctx->nb_surfaces; i++) {
1207         if (!ctx->frames[i].locked) {
1208             ctx->frames[i].locked = 1;
1209             return &ctx->frames[i];
1210         }
1211     }
1212
1213     return NULL;
1214 }
1215
1216 static int nvenc_copy_frame(NV_ENC_LOCK_INPUT_BUFFER *in, const AVFrame *frame)
1217 {
1218     uint8_t *buf = in->bufferDataPtr;
1219     int off      = frame->height * in->pitch;
1220
1221     switch (frame->format) {
1222     case AV_PIX_FMT_YUV420P:
1223         av_image_copy_plane(buf, in->pitch,
1224                             frame->data[0], frame->linesize[0],
1225                             frame->width, frame->height);
1226         buf += off;
1227
1228         av_image_copy_plane(buf, in->pitch >> 1,
1229                             frame->data[2], frame->linesize[2],
1230                             frame->width >> 1, frame->height >> 1);
1231
1232         buf += off >> 2;
1233
1234         av_image_copy_plane(buf, in->pitch >> 1,
1235                             frame->data[1], frame->linesize[1],
1236                             frame->width >> 1, frame->height >> 1);
1237         break;
1238     case AV_PIX_FMT_NV12:
1239         av_image_copy_plane(buf, in->pitch,
1240                             frame->data[0], frame->linesize[0],
1241                             frame->width, frame->height);
1242         buf += off;
1243
1244         av_image_copy_plane(buf, in->pitch,
1245                             frame->data[1], frame->linesize[1],
1246                             frame->width, frame->height >> 1);
1247         break;
1248     case AV_PIX_FMT_P010:
1249         av_image_copy_plane(buf, in->pitch,
1250                             frame->data[0], frame->linesize[0],
1251                             frame->width << 1, frame->height);
1252         buf += off;
1253
1254         av_image_copy_plane(buf, in->pitch,
1255                             frame->data[1], frame->linesize[1],
1256                             frame->width << 1, frame->height >> 1);
1257         break;
1258     case AV_PIX_FMT_YUV444P:
1259         av_image_copy_plane(buf, in->pitch,
1260                             frame->data[0], frame->linesize[0],
1261                             frame->width, frame->height);
1262         buf += off;
1263
1264         av_image_copy_plane(buf, in->pitch,
1265                             frame->data[1], frame->linesize[1],
1266                             frame->width, frame->height);
1267         buf += off;
1268
1269         av_image_copy_plane(buf, in->pitch,
1270                             frame->data[2], frame->linesize[2],
1271                             frame->width, frame->height);
1272         break;
1273     case AV_PIX_FMT_YUV444P16:
1274         av_image_copy_plane(buf, in->pitch,
1275                             frame->data[0], frame->linesize[0],
1276                             frame->width << 1, frame->height);
1277         buf += off;
1278
1279         av_image_copy_plane(buf, in->pitch,
1280                             frame->data[1], frame->linesize[1],
1281                             frame->width << 1, frame->height);
1282         buf += off;
1283
1284         av_image_copy_plane(buf, in->pitch,
1285                             frame->data[2], frame->linesize[2],
1286                             frame->width << 1, frame->height);
1287         break;
1288     default:
1289         return AVERROR_BUG;
1290     }
1291
1292     return 0;
1293 }
1294
1295 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1296 {
1297     NVENCContext               *ctx = avctx->priv_data;
1298     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1299     int i;
1300
1301     if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1302         for (i = 0; i < ctx->nb_registered_frames; i++) {
1303             if (!ctx->registered_frames[i].mapped) {
1304                 if (ctx->registered_frames[i].regptr) {
1305                     nv->nvEncUnregisterResource(ctx->nvenc_ctx,
1306                                                 ctx->registered_frames[i].regptr);
1307                     ctx->registered_frames[i].regptr = NULL;
1308                 }
1309                 return i;
1310             }
1311         }
1312     } else {
1313         return ctx->nb_registered_frames++;
1314     }
1315
1316     av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1317     return AVERROR(ENOMEM);
1318 }
1319
1320 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1321 {
1322     NVENCContext               *ctx = avctx->priv_data;
1323     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1324     AVHWFramesContext   *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1325     NV_ENC_REGISTER_RESOURCE reg;
1326     int i, idx, ret;
1327
1328     for (i = 0; i < ctx->nb_registered_frames; i++) {
1329         if (ctx->registered_frames[i].ptr == (CUdeviceptr)frame->data[0])
1330             return i;
1331     }
1332
1333     idx = nvenc_find_free_reg_resource(avctx);
1334     if (idx < 0)
1335         return idx;
1336
1337     reg.version            = NV_ENC_REGISTER_RESOURCE_VER;
1338     reg.resourceType       = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1339     reg.width              = frames_ctx->width;
1340     reg.height             = frames_ctx->height;
1341     reg.bufferFormat       = ctx->frames[0].format;
1342     reg.pitch              = frame->linesize[0];
1343     reg.resourceToRegister = frame->data[0];
1344
1345     ret = nv->nvEncRegisterResource(ctx->nvenc_ctx, &reg);
1346     if (ret != NV_ENC_SUCCESS) {
1347         nvenc_print_error(avctx, ret, "Error registering an input resource");
1348         return AVERROR_UNKNOWN;
1349     }
1350
1351     ctx->registered_frames[idx].ptr    = (CUdeviceptr)frame->data[0];
1352     ctx->registered_frames[idx].regptr = reg.registeredResource;
1353     return idx;
1354 }
1355
1356 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1357                               NVENCFrame *nvenc_frame)
1358 {
1359     NVENCContext *ctx               = avctx->priv_data;
1360     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1361     int ret;
1362
1363     if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1364         int reg_idx;
1365
1366         ret = nvenc_register_frame(avctx, frame);
1367         if (ret < 0) {
1368             av_log(avctx, AV_LOG_ERROR, "Could not register an input CUDA frame\n");
1369             return ret;
1370         }
1371         reg_idx = ret;
1372
1373         ret = av_frame_ref(nvenc_frame->in_ref, frame);
1374         if (ret < 0)
1375             return ret;
1376
1377         nvenc_frame->in_map.version            = NV_ENC_MAP_INPUT_RESOURCE_VER;
1378         nvenc_frame->in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1379
1380         ret = nv->nvEncMapInputResource(ctx->nvenc_ctx, &nvenc_frame->in_map);
1381         if (ret != NV_ENC_SUCCESS) {
1382             av_frame_unref(nvenc_frame->in_ref);
1383             return nvenc_print_error(avctx, ret, "Error mapping an input resource");
1384         }
1385
1386         ctx->registered_frames[reg_idx].mapped = 1;
1387         nvenc_frame->reg_idx                   = reg_idx;
1388         nvenc_frame->in                        = nvenc_frame->in_map.mappedResource;
1389     } else {
1390         NV_ENC_LOCK_INPUT_BUFFER params = { 0 };
1391
1392         params.version     = NV_ENC_LOCK_INPUT_BUFFER_VER;
1393         params.inputBuffer = nvenc_frame->in;
1394
1395         ret = nv->nvEncLockInputBuffer(ctx->nvenc_ctx, &params);
1396         if (ret != NV_ENC_SUCCESS)
1397             return nvenc_print_error(avctx, ret, "Cannot lock the buffer");
1398
1399         ret = nvenc_copy_frame(&params, frame);
1400         if (ret < 0) {
1401             nv->nvEncUnlockInputBuffer(ctx->nvenc_ctx, nvenc_frame->in);
1402             return ret;
1403         }
1404
1405         ret = nv->nvEncUnlockInputBuffer(ctx->nvenc_ctx, nvenc_frame->in);
1406         if (ret != NV_ENC_SUCCESS)
1407             return nvenc_print_error(avctx, ret, "Cannot unlock the buffer");
1408     }
1409
1410     return 0;
1411 }
1412
1413 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1414                                             NV_ENC_PIC_PARAMS *params)
1415 {
1416     NVENCContext *ctx = avctx->priv_data;
1417
1418     switch (avctx->codec->id) {
1419     case AV_CODEC_ID_H264:
1420         params->codecPicParams.h264PicParams.sliceMode =
1421             ctx->config.encodeCodecConfig.h264Config.sliceMode;
1422         params->codecPicParams.h264PicParams.sliceModeData =
1423             ctx->config.encodeCodecConfig.h264Config.sliceModeData;
1424         break;
1425     case AV_CODEC_ID_HEVC:
1426         params->codecPicParams.hevcPicParams.sliceMode =
1427             ctx->config.encodeCodecConfig.hevcConfig.sliceMode;
1428         params->codecPicParams.hevcPicParams.sliceModeData =
1429             ctx->config.encodeCodecConfig.hevcConfig.sliceModeData;
1430         break;
1431     }
1432 }
1433
1434 static inline int nvenc_enqueue_timestamp(AVFifoBuffer *f, int64_t pts)
1435 {
1436     return av_fifo_generic_write(f, &pts, sizeof(pts), NULL);
1437 }
1438
1439 static inline int nvenc_dequeue_timestamp(AVFifoBuffer *f, int64_t *pts)
1440 {
1441     return av_fifo_generic_read(f, pts, sizeof(*pts), NULL);
1442 }
1443
1444 static int nvenc_set_timestamp(AVCodecContext *avctx,
1445                                NV_ENC_LOCK_BITSTREAM *params,
1446                                AVPacket *pkt)
1447 {
1448     NVENCContext *ctx = avctx->priv_data;
1449
1450     pkt->pts      = params->outputTimeStamp;
1451     pkt->duration = params->outputDuration;
1452
1453     /* generate the first dts by linearly extrapolating the
1454      * first two pts values to the past */
1455     if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
1456         ctx->initial_pts[1] != AV_NOPTS_VALUE) {
1457         int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
1458         int64_t delta;
1459
1460         if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
1461             (ts0 > 0 && ts1 < INT64_MIN + ts0))
1462             return AVERROR(ERANGE);
1463         delta = ts1 - ts0;
1464
1465         if ((delta < 0 && ts0 > INT64_MAX + delta) ||
1466             (delta > 0 && ts0 < INT64_MIN + delta))
1467             return AVERROR(ERANGE);
1468         pkt->dts = ts0 - delta;
1469
1470         ctx->first_packet_output = 1;
1471         return 0;
1472     }
1473     return nvenc_dequeue_timestamp(ctx->timestamps, &pkt->dts);
1474 }
1475
1476 static int nvenc_get_output(AVCodecContext *avctx, AVPacket *pkt)
1477 {
1478     NVENCContext *ctx               = avctx->priv_data;
1479     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1480     NV_ENC_LOCK_BITSTREAM params    = { 0 };
1481     NVENCFrame *frame;
1482     int ret;
1483
1484     ret = av_fifo_generic_read(ctx->ready, &frame, sizeof(frame), NULL);
1485     if (ret)
1486         return ret;
1487
1488     params.version         = NV_ENC_LOCK_BITSTREAM_VER;
1489     params.outputBitstream = frame->out;
1490
1491     ret = nv->nvEncLockBitstream(ctx->nvenc_ctx, &params);
1492     if (ret < 0)
1493         return nvenc_print_error(avctx, ret, "Cannot lock the bitstream");
1494
1495     ret = ff_alloc_packet(pkt, params.bitstreamSizeInBytes);
1496     if (ret < 0)
1497         return ret;
1498
1499     memcpy(pkt->data, params.bitstreamBufferPtr, pkt->size);
1500
1501     ret = nv->nvEncUnlockBitstream(ctx->nvenc_ctx, frame->out);
1502     if (ret < 0)
1503         return nvenc_print_error(avctx, ret, "Cannot unlock the bitstream");
1504
1505     if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1506         nv->nvEncUnmapInputResource(ctx->nvenc_ctx, frame->in_map.mappedResource);
1507         av_frame_unref(frame->in_ref);
1508         ctx->registered_frames[frame->reg_idx].mapped = 0;
1509
1510         frame->in = NULL;
1511     }
1512
1513     frame->locked = 0;
1514
1515     ret = nvenc_set_timestamp(avctx, &params, pkt);
1516     if (ret < 0)
1517         return ret;
1518
1519     switch (params.pictureType) {
1520     case NV_ENC_PIC_TYPE_IDR:
1521         pkt->flags |= AV_PKT_FLAG_KEY;
1522 #if FF_API_CODED_FRAME
1523 FF_DISABLE_DEPRECATION_WARNINGS
1524     case NV_ENC_PIC_TYPE_INTRA_REFRESH:
1525     case NV_ENC_PIC_TYPE_I:
1526         avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
1527         break;
1528     case NV_ENC_PIC_TYPE_P:
1529         avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
1530         break;
1531     case NV_ENC_PIC_TYPE_B:
1532         avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;
1533         break;
1534     case NV_ENC_PIC_TYPE_BI:
1535         avctx->coded_frame->pict_type = AV_PICTURE_TYPE_BI;
1536         break;
1537 FF_ENABLE_DEPRECATION_WARNINGS
1538 #endif
1539     }
1540
1541     return 0;
1542 }
1543
1544 static int output_ready(AVCodecContext *avctx, int flush)
1545 {
1546     NVENCContext *ctx = avctx->priv_data;
1547     int nb_ready, nb_pending;
1548
1549     /* when B-frames are enabled, we wait for two initial timestamps to
1550      * calculate the first dts */
1551     if (!flush && avctx->max_b_frames > 0 &&
1552         (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
1553         return 0;
1554
1555     nb_ready   = av_fifo_size(ctx->ready)   / sizeof(NVENCFrame*);
1556     nb_pending = av_fifo_size(ctx->pending) / sizeof(NVENCFrame*);
1557     if (flush)
1558         return nb_ready > 0;
1559     return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
1560 }
1561
1562 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1563                           const AVFrame *frame, int *got_packet)
1564 {
1565     NVENCContext *ctx               = avctx->priv_data;
1566     NVENCLibraryContext *nvel       = &ctx->nvel;
1567     NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1568     NV_ENC_PIC_PARAMS params        = { 0 };
1569     NVENCFrame         *nvenc_frame = NULL;
1570     CUcontext dummy;
1571     int enc_ret, ret;
1572
1573     params.version = NV_ENC_PIC_PARAMS_VER;
1574
1575     if (frame) {
1576         nvenc_frame = get_free_frame(ctx);
1577         if (!nvenc_frame) {
1578             av_log(avctx, AV_LOG_ERROR, "No free surfaces\n");
1579             return AVERROR_BUG;
1580         }
1581
1582         ret = nvenc_upload_frame(avctx, frame, nvenc_frame);
1583         if (ret < 0)
1584             return ret;
1585
1586         params.inputBuffer     = nvenc_frame->in;
1587         params.bufferFmt       = nvenc_frame->format;
1588         params.inputWidth      = frame->width;
1589         params.inputHeight     = frame->height;
1590         params.outputBitstream = nvenc_frame->out;
1591         params.inputTimeStamp  = frame->pts;
1592
1593         if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1594             if (frame->top_field_first)
1595                 params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
1596             else
1597                 params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
1598         } else {
1599             params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1600         }
1601
1602         nvenc_codec_specific_pic_params(avctx, &params);
1603
1604         ret = nvenc_enqueue_timestamp(ctx->timestamps, frame->pts);
1605         if (ret < 0)
1606             return ret;
1607
1608         if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
1609             ctx->initial_pts[0] = frame->pts;
1610         else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
1611             ctx->initial_pts[1] = frame->pts;
1612     } else {
1613         params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1614     }
1615
1616     nvel->cu_ctx_push_current(ctx->cu_context);
1617     enc_ret = nv->nvEncEncodePicture(ctx->nvenc_ctx, &params);
1618     nvel->cu_ctx_pop_current(&dummy);
1619
1620     if (enc_ret != NV_ENC_SUCCESS &&
1621         enc_ret != NV_ENC_ERR_NEED_MORE_INPUT)
1622         return nvenc_print_error(avctx, enc_ret, "Error encoding the frame");
1623
1624     if (nvenc_frame) {
1625         ret = av_fifo_generic_write(ctx->pending, &nvenc_frame, sizeof(nvenc_frame), NULL);
1626         if (ret < 0)
1627             return ret;
1628     }
1629
1630     /* all the pending buffers are now ready for output */
1631     if (enc_ret == NV_ENC_SUCCESS) {
1632         while (av_fifo_size(ctx->pending) > 0) {
1633             av_fifo_generic_read(ctx->pending, &nvenc_frame, sizeof(nvenc_frame), NULL);
1634             av_fifo_generic_write(ctx->ready,  &nvenc_frame, sizeof(nvenc_frame), NULL);
1635         }
1636     }
1637
1638     if (output_ready(avctx, !frame)) {
1639         ret = nvenc_get_output(avctx, pkt);
1640         if (ret < 0)
1641             return ret;
1642         *got_packet = 1;
1643     } else {
1644         *got_packet = 0;
1645     }
1646
1647     return 0;
1648 }