You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1599 lines
52KB

  1. /*
  2. * H.264 hardware encoding using nvidia nvenc
  3. * Copyright (c) 2014 Timo Rothenpieler <timo@rothenpieler.org>
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg 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. * FFmpeg 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 FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "config.h"
  22. #if defined(_WIN32)
  23. #include <windows.h>
  24. #else
  25. #include <dlfcn.h>
  26. #endif
  27. #include "libavutil/imgutils.h"
  28. #include "libavutil/avassert.h"
  29. #include "libavutil/mem.h"
  30. #include "libavutil/hwcontext.h"
  31. #include "internal.h"
  32. #include "thread.h"
  33. #include "nvenc.h"
  34. #if CONFIG_CUDA
  35. #include "libavutil/hwcontext_cuda.h"
  36. #endif
  37. #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR || \
  38. rc == NV_ENC_PARAMS_RC_2_PASS_QUALITY || \
  39. rc == NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP)
  40. #if defined(_WIN32)
  41. #define LOAD_FUNC(l, s) GetProcAddress(l, s)
  42. #define DL_CLOSE_FUNC(l) FreeLibrary(l)
  43. #else
  44. #define LOAD_FUNC(l, s) dlsym(l, s)
  45. #define DL_CLOSE_FUNC(l) dlclose(l)
  46. #endif
  47. const enum AVPixelFormat ff_nvenc_pix_fmts[] = {
  48. AV_PIX_FMT_YUV420P,
  49. AV_PIX_FMT_NV12,
  50. AV_PIX_FMT_YUV444P,
  51. #if CONFIG_CUDA
  52. AV_PIX_FMT_CUDA,
  53. #endif
  54. AV_PIX_FMT_NONE
  55. };
  56. typedef struct NvencData
  57. {
  58. union {
  59. int64_t timestamp;
  60. NvencSurface *surface;
  61. } u;
  62. } NvencData;
  63. static const struct {
  64. NVENCSTATUS nverr;
  65. int averr;
  66. const char *desc;
  67. } nvenc_errors[] = {
  68. { NV_ENC_SUCCESS, 0, "success" },
  69. { NV_ENC_ERR_NO_ENCODE_DEVICE, AVERROR(ENOENT), "no encode device" },
  70. { NV_ENC_ERR_UNSUPPORTED_DEVICE, AVERROR(ENOSYS), "unsupported device" },
  71. { NV_ENC_ERR_INVALID_ENCODERDEVICE, AVERROR(EINVAL), "invalid encoder device" },
  72. { NV_ENC_ERR_INVALID_DEVICE, AVERROR(EINVAL), "invalid device" },
  73. { NV_ENC_ERR_DEVICE_NOT_EXIST, AVERROR(EIO), "device does not exist" },
  74. { NV_ENC_ERR_INVALID_PTR, AVERROR(EFAULT), "invalid ptr" },
  75. { NV_ENC_ERR_INVALID_EVENT, AVERROR(EINVAL), "invalid event" },
  76. { NV_ENC_ERR_INVALID_PARAM, AVERROR(EINVAL), "invalid param" },
  77. { NV_ENC_ERR_INVALID_CALL, AVERROR(EINVAL), "invalid call" },
  78. { NV_ENC_ERR_OUT_OF_MEMORY, AVERROR(ENOMEM), "out of memory" },
  79. { NV_ENC_ERR_ENCODER_NOT_INITIALIZED, AVERROR(EINVAL), "encoder not initialized" },
  80. { NV_ENC_ERR_UNSUPPORTED_PARAM, AVERROR(ENOSYS), "unsupported param" },
  81. { NV_ENC_ERR_LOCK_BUSY, AVERROR(EAGAIN), "lock busy" },
  82. { NV_ENC_ERR_NOT_ENOUGH_BUFFER, AVERROR(ENOBUFS), "not enough buffer" },
  83. { NV_ENC_ERR_INVALID_VERSION, AVERROR(EINVAL), "invalid version" },
  84. { NV_ENC_ERR_MAP_FAILED, AVERROR(EIO), "map failed" },
  85. { NV_ENC_ERR_NEED_MORE_INPUT, AVERROR(EAGAIN), "need more input" },
  86. { NV_ENC_ERR_ENCODER_BUSY, AVERROR(EAGAIN), "encoder busy" },
  87. { NV_ENC_ERR_EVENT_NOT_REGISTERD, AVERROR(EBADF), "event not registered" },
  88. { NV_ENC_ERR_GENERIC, AVERROR_UNKNOWN, "generic error" },
  89. { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY, AVERROR(EINVAL), "incompatible client key" },
  90. { NV_ENC_ERR_UNIMPLEMENTED, AVERROR(ENOSYS), "unimplemented" },
  91. { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO), "resource register failed" },
  92. { NV_ENC_ERR_RESOURCE_NOT_REGISTERED, AVERROR(EBADF), "resource not registered" },
  93. { NV_ENC_ERR_RESOURCE_NOT_MAPPED, AVERROR(EBADF), "resource not mapped" },
  94. };
  95. static int nvenc_map_error(NVENCSTATUS err, const char **desc)
  96. {
  97. int i;
  98. for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
  99. if (nvenc_errors[i].nverr == err) {
  100. if (desc)
  101. *desc = nvenc_errors[i].desc;
  102. return nvenc_errors[i].averr;
  103. }
  104. }
  105. if (desc)
  106. *desc = "unknown error";
  107. return AVERROR_UNKNOWN;
  108. }
  109. static int nvenc_print_error(void *log_ctx, NVENCSTATUS err,
  110. const char *error_string)
  111. {
  112. const char *desc;
  113. int ret;
  114. ret = nvenc_map_error(err, &desc);
  115. av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
  116. return ret;
  117. }
  118. static void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
  119. {
  120. av_fifo_generic_write(queue, &timestamp, sizeof(timestamp), NULL);
  121. }
  122. static int64_t timestamp_queue_dequeue(AVFifoBuffer* queue)
  123. {
  124. int64_t timestamp = AV_NOPTS_VALUE;
  125. if (av_fifo_size(queue) > 0)
  126. av_fifo_generic_read(queue, &timestamp, sizeof(timestamp), NULL);
  127. return timestamp;
  128. }
  129. #define CHECK_LOAD_FUNC(t, f, s) \
  130. do { \
  131. (f) = (t)LOAD_FUNC(dl_fn->cuda_lib, s); \
  132. if (!(f)) { \
  133. av_log(avctx, AV_LOG_FATAL, "Failed loading %s from CUDA library\n", s); \
  134. goto error; \
  135. } \
  136. } while (0)
  137. static av_cold int nvenc_dyload_cuda(AVCodecContext *avctx)
  138. {
  139. NvencContext *ctx = avctx->priv_data;
  140. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  141. #if CONFIG_CUDA
  142. dl_fn->cu_init = cuInit;
  143. dl_fn->cu_device_get_count = cuDeviceGetCount;
  144. dl_fn->cu_device_get = cuDeviceGet;
  145. dl_fn->cu_device_get_name = cuDeviceGetName;
  146. dl_fn->cu_device_compute_capability = cuDeviceComputeCapability;
  147. dl_fn->cu_ctx_create = cuCtxCreate_v2;
  148. dl_fn->cu_ctx_pop_current = cuCtxPopCurrent_v2;
  149. dl_fn->cu_ctx_destroy = cuCtxDestroy_v2;
  150. return 1;
  151. #else
  152. if (dl_fn->cuda_lib)
  153. return 1;
  154. #if defined(_WIN32)
  155. dl_fn->cuda_lib = LoadLibrary(TEXT("nvcuda.dll"));
  156. #else
  157. dl_fn->cuda_lib = dlopen("libcuda.so", RTLD_LAZY);
  158. #endif
  159. if (!dl_fn->cuda_lib) {
  160. av_log(avctx, AV_LOG_FATAL, "Failed loading CUDA library\n");
  161. goto error;
  162. }
  163. CHECK_LOAD_FUNC(PCUINIT, dl_fn->cu_init, "cuInit");
  164. CHECK_LOAD_FUNC(PCUDEVICEGETCOUNT, dl_fn->cu_device_get_count, "cuDeviceGetCount");
  165. CHECK_LOAD_FUNC(PCUDEVICEGET, dl_fn->cu_device_get, "cuDeviceGet");
  166. CHECK_LOAD_FUNC(PCUDEVICEGETNAME, dl_fn->cu_device_get_name, "cuDeviceGetName");
  167. CHECK_LOAD_FUNC(PCUDEVICECOMPUTECAPABILITY, dl_fn->cu_device_compute_capability, "cuDeviceComputeCapability");
  168. CHECK_LOAD_FUNC(PCUCTXCREATE, dl_fn->cu_ctx_create, "cuCtxCreate_v2");
  169. CHECK_LOAD_FUNC(PCUCTXPOPCURRENT, dl_fn->cu_ctx_pop_current, "cuCtxPopCurrent_v2");
  170. CHECK_LOAD_FUNC(PCUCTXDESTROY, dl_fn->cu_ctx_destroy, "cuCtxDestroy_v2");
  171. return 1;
  172. error:
  173. if (dl_fn->cuda_lib)
  174. DL_CLOSE_FUNC(dl_fn->cuda_lib);
  175. dl_fn->cuda_lib = NULL;
  176. return 0;
  177. #endif
  178. }
  179. static av_cold int check_cuda_errors(AVCodecContext *avctx, CUresult err, const char *func)
  180. {
  181. if (err != CUDA_SUCCESS) {
  182. av_log(avctx, AV_LOG_FATAL, ">> %s - failed with error code 0x%x\n", func, err);
  183. return 0;
  184. }
  185. return 1;
  186. }
  187. #define check_cuda_errors(f) if (!check_cuda_errors(avctx, f, #f)) goto error
  188. static av_cold int nvenc_check_cuda(AVCodecContext *avctx)
  189. {
  190. int device_count = 0;
  191. CUdevice cu_device = 0;
  192. char gpu_name[128];
  193. int smminor = 0, smmajor = 0;
  194. int i, smver, target_smver;
  195. NvencContext *ctx = avctx->priv_data;
  196. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  197. switch (avctx->codec->id) {
  198. case AV_CODEC_ID_H264:
  199. target_smver = ctx->data_pix_fmt == AV_PIX_FMT_YUV444P ? 0x52 : 0x30;
  200. break;
  201. case AV_CODEC_ID_H265:
  202. target_smver = 0x52;
  203. break;
  204. default:
  205. av_log(avctx, AV_LOG_FATAL, "Unknown codec name\n");
  206. goto error;
  207. }
  208. if (ctx->preset >= PRESET_LOSSLESS_DEFAULT)
  209. target_smver = 0x52;
  210. if (!nvenc_dyload_cuda(avctx))
  211. return 0;
  212. if (dl_fn->nvenc_device_count > 0)
  213. return 1;
  214. check_cuda_errors(dl_fn->cu_init(0));
  215. check_cuda_errors(dl_fn->cu_device_get_count(&device_count));
  216. if (!device_count) {
  217. av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
  218. goto error;
  219. }
  220. av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", device_count);
  221. dl_fn->nvenc_device_count = 0;
  222. for (i = 0; i < device_count; ++i) {
  223. check_cuda_errors(dl_fn->cu_device_get(&cu_device, i));
  224. check_cuda_errors(dl_fn->cu_device_get_name(gpu_name, sizeof(gpu_name), cu_device));
  225. check_cuda_errors(dl_fn->cu_device_compute_capability(&smmajor, &smminor, cu_device));
  226. smver = (smmajor << 4) | smminor;
  227. av_log(avctx, AV_LOG_VERBOSE, "[ GPU #%d - < %s > has Compute SM %d.%d, NVENC %s ]\n", i, gpu_name, smmajor, smminor, (smver >= target_smver) ? "Available" : "Not Available");
  228. if (smver >= target_smver)
  229. dl_fn->nvenc_devices[dl_fn->nvenc_device_count++] = cu_device;
  230. }
  231. if (!dl_fn->nvenc_device_count) {
  232. av_log(avctx, AV_LOG_FATAL, "No NVENC capable devices found\n");
  233. goto error;
  234. }
  235. return 1;
  236. error:
  237. dl_fn->nvenc_device_count = 0;
  238. return 0;
  239. }
  240. static av_cold int nvenc_dyload_nvenc(AVCodecContext *avctx)
  241. {
  242. PNVENCODEAPICREATEINSTANCE nvEncodeAPICreateInstance = 0;
  243. NVENCSTATUS nvstatus;
  244. NvencContext *ctx = avctx->priv_data;
  245. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  246. if (!nvenc_check_cuda(avctx))
  247. return 0;
  248. if (dl_fn->nvenc_lib)
  249. return 1;
  250. #if defined(_WIN32)
  251. if (sizeof(void*) == 8) {
  252. dl_fn->nvenc_lib = LoadLibrary(TEXT("nvEncodeAPI64.dll"));
  253. } else {
  254. dl_fn->nvenc_lib = LoadLibrary(TEXT("nvEncodeAPI.dll"));
  255. }
  256. #else
  257. dl_fn->nvenc_lib = dlopen("libnvidia-encode.so.1", RTLD_LAZY);
  258. #endif
  259. if (!dl_fn->nvenc_lib) {
  260. av_log(avctx, AV_LOG_FATAL, "Failed loading the nvenc library\n");
  261. goto error;
  262. }
  263. nvEncodeAPICreateInstance = (PNVENCODEAPICREATEINSTANCE)LOAD_FUNC(dl_fn->nvenc_lib, "NvEncodeAPICreateInstance");
  264. if (!nvEncodeAPICreateInstance) {
  265. av_log(avctx, AV_LOG_FATAL, "Failed to load nvenc entrypoint\n");
  266. goto error;
  267. }
  268. dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
  269. nvstatus = nvEncodeAPICreateInstance(&dl_fn->nvenc_funcs);
  270. if (nvstatus != NV_ENC_SUCCESS) {
  271. nvenc_print_error(avctx, nvstatus, "Failed to create nvenc instance");
  272. goto error;
  273. }
  274. av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
  275. return 1;
  276. error:
  277. if (dl_fn->nvenc_lib)
  278. DL_CLOSE_FUNC(dl_fn->nvenc_lib);
  279. dl_fn->nvenc_lib = NULL;
  280. return 0;
  281. }
  282. static av_cold void nvenc_unload_nvenc(AVCodecContext *avctx)
  283. {
  284. NvencContext *ctx = avctx->priv_data;
  285. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  286. DL_CLOSE_FUNC(dl_fn->nvenc_lib);
  287. dl_fn->nvenc_lib = NULL;
  288. dl_fn->nvenc_device_count = 0;
  289. #if !CONFIG_CUDA
  290. DL_CLOSE_FUNC(dl_fn->cuda_lib);
  291. dl_fn->cuda_lib = NULL;
  292. #endif
  293. dl_fn->cu_init = NULL;
  294. dl_fn->cu_device_get_count = NULL;
  295. dl_fn->cu_device_get = NULL;
  296. dl_fn->cu_device_get_name = NULL;
  297. dl_fn->cu_device_compute_capability = NULL;
  298. dl_fn->cu_ctx_create = NULL;
  299. dl_fn->cu_ctx_pop_current = NULL;
  300. dl_fn->cu_ctx_destroy = NULL;
  301. av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
  302. }
  303. static av_cold int nvenc_setup_device(AVCodecContext *avctx)
  304. {
  305. NvencContext *ctx = avctx->priv_data;
  306. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  307. CUresult cu_res;
  308. CUcontext cu_context_curr;
  309. switch (avctx->codec->id) {
  310. case AV_CODEC_ID_H264:
  311. ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
  312. break;
  313. case AV_CODEC_ID_HEVC:
  314. ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
  315. break;
  316. default:
  317. return AVERROR_BUG;
  318. }
  319. ctx->data_pix_fmt = avctx->pix_fmt;
  320. #if CONFIG_CUDA
  321. if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
  322. AVHWFramesContext *frames_ctx;
  323. AVCUDADeviceContext *device_hwctx;
  324. if (!avctx->hw_frames_ctx) {
  325. av_log(avctx, AV_LOG_ERROR, "hw_frames_ctx must be set when using GPU frames as input\n");
  326. return AVERROR(EINVAL);
  327. }
  328. frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  329. device_hwctx = frames_ctx->device_ctx->hwctx;
  330. ctx->cu_context = device_hwctx->cuda_ctx;
  331. ctx->data_pix_fmt = frames_ctx->sw_format;
  332. return 0;
  333. }
  334. #endif
  335. if (ctx->gpu >= dl_fn->nvenc_device_count) {
  336. av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->gpu, dl_fn->nvenc_device_count);
  337. return AVERROR(EINVAL);
  338. }
  339. ctx->cu_context = NULL;
  340. cu_res = dl_fn->cu_ctx_create(&ctx->cu_context_internal, 4, dl_fn->nvenc_devices[ctx->gpu]); // CU_CTX_SCHED_BLOCKING_SYNC=4, avoid CPU spins
  341. if (cu_res != CUDA_SUCCESS) {
  342. av_log(avctx, AV_LOG_FATAL, "Failed creating CUDA context for NVENC: 0x%x\n", (int)cu_res);
  343. return AVERROR_EXTERNAL;
  344. }
  345. cu_res = dl_fn->cu_ctx_pop_current(&cu_context_curr);
  346. if (cu_res != CUDA_SUCCESS) {
  347. av_log(avctx, AV_LOG_FATAL, "Failed popping CUDA context: 0x%x\n", (int)cu_res);
  348. return AVERROR_EXTERNAL;
  349. }
  350. ctx->cu_context = ctx->cu_context_internal;
  351. return 0;
  352. }
  353. static av_cold int nvenc_open_session(AVCodecContext *avctx)
  354. {
  355. NvencContext *ctx = avctx->priv_data;
  356. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  357. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  358. NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS encode_session_params = { 0 };
  359. NVENCSTATUS nv_status;
  360. encode_session_params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
  361. encode_session_params.apiVersion = NVENCAPI_VERSION;
  362. encode_session_params.device = ctx->cu_context;
  363. encode_session_params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
  364. nv_status = p_nvenc->nvEncOpenEncodeSessionEx(&encode_session_params, &ctx->nvencoder);
  365. if (nv_status != NV_ENC_SUCCESS) {
  366. ctx->nvencoder = NULL;
  367. return nvenc_print_error(avctx, nv_status, "OpenEncodeSessionEx failed");
  368. }
  369. return 0;
  370. }
  371. typedef struct GUIDTuple {
  372. const GUID guid;
  373. int flags;
  374. } GUIDTuple;
  375. static void nvenc_map_preset(NvencContext *ctx)
  376. {
  377. GUIDTuple presets[] = {
  378. { NV_ENC_PRESET_DEFAULT_GUID },
  379. { NV_ENC_PRESET_HQ_GUID, NVENC_TWO_PASSES }, /* slow */
  380. { NV_ENC_PRESET_HQ_GUID, NVENC_ONE_PASS }, /* medium */
  381. { NV_ENC_PRESET_HP_GUID, NVENC_ONE_PASS }, /* fast */
  382. { NV_ENC_PRESET_HP_GUID },
  383. { NV_ENC_PRESET_HQ_GUID },
  384. { NV_ENC_PRESET_BD_GUID },
  385. { NV_ENC_PRESET_LOW_LATENCY_DEFAULT_GUID, NVENC_LOWLATENCY },
  386. { NV_ENC_PRESET_LOW_LATENCY_HQ_GUID, NVENC_LOWLATENCY },
  387. { NV_ENC_PRESET_LOW_LATENCY_HP_GUID, NVENC_LOWLATENCY },
  388. { NV_ENC_PRESET_LOSSLESS_DEFAULT_GUID, NVENC_LOSSLESS },
  389. { NV_ENC_PRESET_LOSSLESS_HP_GUID, NVENC_LOSSLESS },
  390. };
  391. GUIDTuple *t = &presets[ctx->preset];
  392. ctx->init_encode_params.presetGUID = t->guid;
  393. ctx->flags = t->flags;
  394. }
  395. static av_cold void set_constqp(AVCodecContext *avctx)
  396. {
  397. NvencContext *ctx = avctx->priv_data;
  398. NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
  399. rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
  400. rc->constQP.qpInterB = avctx->global_quality;
  401. rc->constQP.qpInterP = avctx->global_quality;
  402. rc->constQP.qpIntra = avctx->global_quality;
  403. avctx->qmin = -1;
  404. avctx->qmax = -1;
  405. }
  406. static av_cold void set_vbr(AVCodecContext *avctx)
  407. {
  408. NvencContext *ctx = avctx->priv_data;
  409. NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
  410. int qp_inter_p;
  411. if (avctx->qmin >= 0 && avctx->qmax >= 0) {
  412. rc->enableMinQP = 1;
  413. rc->enableMaxQP = 1;
  414. rc->minQP.qpInterB = avctx->qmin;
  415. rc->minQP.qpInterP = avctx->qmin;
  416. rc->minQP.qpIntra = avctx->qmin;
  417. rc->maxQP.qpInterB = avctx->qmax;
  418. rc->maxQP.qpInterP = avctx->qmax;
  419. rc->maxQP.qpIntra = avctx->qmax;
  420. qp_inter_p = (avctx->qmax + 3 * avctx->qmin) / 4; // biased towards Qmin
  421. } else {
  422. qp_inter_p = 26; // default to 26
  423. }
  424. rc->enableInitialRCQP = 1;
  425. rc->initialRCQP.qpInterP = qp_inter_p;
  426. if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
  427. rc->initialRCQP.qpIntra = av_clip(
  428. qp_inter_p * fabs(avctx->i_quant_factor) + avctx->i_quant_offset, 0, 51);
  429. rc->initialRCQP.qpInterB = av_clip(
  430. qp_inter_p * fabs(avctx->b_quant_factor) + avctx->b_quant_offset, 0, 51);
  431. } else {
  432. rc->initialRCQP.qpIntra = qp_inter_p;
  433. rc->initialRCQP.qpInterB = qp_inter_p;
  434. }
  435. }
  436. static av_cold void set_lossless(AVCodecContext *avctx)
  437. {
  438. NvencContext *ctx = avctx->priv_data;
  439. NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
  440. rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
  441. rc->constQP.qpInterB = 0;
  442. rc->constQP.qpInterP = 0;
  443. rc->constQP.qpIntra = 0;
  444. avctx->qmin = -1;
  445. avctx->qmax = -1;
  446. }
  447. static void nvenc_override_rate_control(AVCodecContext *avctx)
  448. {
  449. NvencContext *ctx = avctx->priv_data;
  450. NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
  451. switch (ctx->rc) {
  452. case NV_ENC_PARAMS_RC_CONSTQP:
  453. if (avctx->global_quality <= 0) {
  454. av_log(avctx, AV_LOG_WARNING,
  455. "The constant quality rate-control requires "
  456. "the 'global_quality' option set.\n");
  457. return;
  458. }
  459. set_constqp(avctx);
  460. return;
  461. case NV_ENC_PARAMS_RC_2_PASS_VBR:
  462. case NV_ENC_PARAMS_RC_VBR:
  463. if (avctx->qmin < 0 && avctx->qmax < 0) {
  464. av_log(avctx, AV_LOG_WARNING,
  465. "The variable bitrate rate-control requires "
  466. "the 'qmin' and/or 'qmax' option set.\n");
  467. set_vbr(avctx);
  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. set_vbr(avctx);
  476. return;
  477. }
  478. set_vbr(avctx);
  479. break;
  480. case NV_ENC_PARAMS_RC_CBR:
  481. break;
  482. case NV_ENC_PARAMS_RC_2_PASS_QUALITY:
  483. case NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP:
  484. if (!(ctx->flags & NVENC_LOWLATENCY)) {
  485. av_log(avctx, AV_LOG_WARNING,
  486. "The multipass rate-control requires "
  487. "a low-latency preset.\n");
  488. return;
  489. }
  490. }
  491. rc->rateControlMode = ctx->rc;
  492. }
  493. static av_cold void nvenc_setup_rate_control(AVCodecContext *avctx)
  494. {
  495. NvencContext *ctx = avctx->priv_data;
  496. if (avctx->bit_rate > 0) {
  497. ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
  498. } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
  499. ctx->encode_config.rcParams.maxBitRate = ctx->encode_config.rcParams.averageBitRate;
  500. }
  501. if (avctx->rc_max_rate > 0)
  502. ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
  503. if (ctx->rc < 0) {
  504. if (ctx->flags & NVENC_ONE_PASS)
  505. ctx->twopass = 0;
  506. if (ctx->flags & NVENC_TWO_PASSES)
  507. ctx->twopass = 1;
  508. if (ctx->twopass < 0)
  509. ctx->twopass = (ctx->flags & NVENC_LOWLATENCY) != 0;
  510. if (ctx->cbr) {
  511. if (ctx->twopass) {
  512. ctx->rc = NV_ENC_PARAMS_RC_2_PASS_QUALITY;
  513. } else {
  514. ctx->rc = NV_ENC_PARAMS_RC_CBR;
  515. }
  516. } else if (avctx->global_quality > 0) {
  517. ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
  518. } else if (ctx->twopass) {
  519. ctx->rc = NV_ENC_PARAMS_RC_2_PASS_VBR;
  520. } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
  521. ctx->rc = NV_ENC_PARAMS_RC_VBR_MINQP;
  522. }
  523. }
  524. if (ctx->flags & NVENC_LOSSLESS) {
  525. set_lossless(avctx);
  526. } else if (ctx->rc > 0) {
  527. nvenc_override_rate_control(avctx);
  528. } else {
  529. ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
  530. set_vbr(avctx);
  531. }
  532. if (avctx->rc_buffer_size > 0) {
  533. ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
  534. } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
  535. ctx->encode_config.rcParams.vbvBufferSize = 2 * ctx->encode_config.rcParams.averageBitRate;
  536. }
  537. }
  538. static av_cold int nvenc_setup_h264_config(AVCodecContext *avctx)
  539. {
  540. NvencContext *ctx = avctx->priv_data;
  541. NV_ENC_CONFIG *cc = &ctx->encode_config;
  542. NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
  543. NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
  544. vui->colourMatrix = avctx->colorspace;
  545. vui->colourPrimaries = avctx->color_primaries;
  546. vui->transferCharacteristics = avctx->color_trc;
  547. vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
  548. || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
  549. vui->colourDescriptionPresentFlag =
  550. (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
  551. vui->videoSignalTypePresentFlag =
  552. (vui->colourDescriptionPresentFlag
  553. || vui->videoFormat != 5
  554. || vui->videoFullRangeFlag != 0);
  555. h264->sliceMode = 3;
  556. h264->sliceModeData = 1;
  557. h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
  558. h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
  559. h264->outputAUD = 1;
  560. if (avctx->refs >= 0) {
  561. /* 0 means "let the hardware decide" */
  562. h264->maxNumRefFrames = avctx->refs;
  563. }
  564. if (avctx->gop_size >= 0) {
  565. h264->idrPeriod = cc->gopLength;
  566. }
  567. if (IS_CBR(cc->rcParams.rateControlMode)) {
  568. h264->outputBufferingPeriodSEI = 1;
  569. h264->outputPictureTimingSEI = 1;
  570. }
  571. if (cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_2_PASS_QUALITY ||
  572. cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP ||
  573. cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_2_PASS_VBR) {
  574. h264->adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
  575. h264->fmoMode = NV_ENC_H264_FMO_DISABLE;
  576. }
  577. if (ctx->flags & NVENC_LOSSLESS) {
  578. h264->qpPrimeYZeroTransformBypassFlag = 1;
  579. } else {
  580. switch(ctx->profile) {
  581. case NV_ENC_H264_PROFILE_BASELINE:
  582. cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
  583. avctx->profile = FF_PROFILE_H264_BASELINE;
  584. break;
  585. case NV_ENC_H264_PROFILE_MAIN:
  586. cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
  587. avctx->profile = FF_PROFILE_H264_MAIN;
  588. break;
  589. case NV_ENC_H264_PROFILE_HIGH:
  590. cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
  591. avctx->profile = FF_PROFILE_H264_HIGH;
  592. break;
  593. case NV_ENC_H264_PROFILE_HIGH_444P:
  594. cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
  595. avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
  596. break;
  597. }
  598. }
  599. // force setting profile as high444p if input is AV_PIX_FMT_YUV444P
  600. if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P) {
  601. cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
  602. avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
  603. }
  604. h264->chromaFormatIDC = avctx->profile == FF_PROFILE_H264_HIGH_444_PREDICTIVE ? 3 : 1;
  605. h264->level = ctx->level;
  606. return 0;
  607. }
  608. static av_cold int nvenc_setup_hevc_config(AVCodecContext *avctx)
  609. {
  610. NvencContext *ctx = avctx->priv_data;
  611. NV_ENC_CONFIG *cc = &ctx->encode_config;
  612. NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
  613. NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
  614. vui->colourMatrix = avctx->colorspace;
  615. vui->colourPrimaries = avctx->color_primaries;
  616. vui->transferCharacteristics = avctx->color_trc;
  617. vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
  618. || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
  619. vui->colourDescriptionPresentFlag =
  620. (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
  621. vui->videoSignalTypePresentFlag =
  622. (vui->colourDescriptionPresentFlag
  623. || vui->videoFormat != 5
  624. || vui->videoFullRangeFlag != 0);
  625. hevc->sliceMode = 3;
  626. hevc->sliceModeData = 1;
  627. hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
  628. hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
  629. hevc->outputAUD = 1;
  630. if (avctx->refs >= 0) {
  631. /* 0 means "let the hardware decide" */
  632. hevc->maxNumRefFramesInDPB = avctx->refs;
  633. }
  634. if (avctx->gop_size >= 0) {
  635. hevc->idrPeriod = cc->gopLength;
  636. }
  637. if (IS_CBR(cc->rcParams.rateControlMode)) {
  638. hevc->outputBufferingPeriodSEI = 1;
  639. hevc->outputPictureTimingSEI = 1;
  640. }
  641. /* No other profile is supported in the current SDK version 5 */
  642. cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
  643. avctx->profile = FF_PROFILE_HEVC_MAIN;
  644. hevc->level = ctx->level;
  645. hevc->tier = ctx->tier;
  646. return 0;
  647. }
  648. static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx)
  649. {
  650. switch (avctx->codec->id) {
  651. case AV_CODEC_ID_H264:
  652. return nvenc_setup_h264_config(avctx);
  653. case AV_CODEC_ID_HEVC:
  654. return nvenc_setup_hevc_config(avctx);
  655. /* Earlier switch/case will return if unknown codec is passed. */
  656. }
  657. return 0;
  658. }
  659. static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
  660. {
  661. NvencContext *ctx = avctx->priv_data;
  662. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  663. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  664. NV_ENC_PRESET_CONFIG preset_config = { 0 };
  665. NVENCSTATUS nv_status = NV_ENC_SUCCESS;
  666. AVCPBProperties *cpb_props;
  667. int num_mbs;
  668. int res = 0;
  669. int dw, dh;
  670. ctx->last_dts = AV_NOPTS_VALUE;
  671. ctx->encode_config.version = NV_ENC_CONFIG_VER;
  672. ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
  673. ctx->init_encode_params.encodeHeight = avctx->height;
  674. ctx->init_encode_params.encodeWidth = avctx->width;
  675. ctx->init_encode_params.encodeConfig = &ctx->encode_config;
  676. nvenc_map_preset(ctx);
  677. preset_config.version = NV_ENC_PRESET_CONFIG_VER;
  678. preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
  679. nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder,
  680. ctx->init_encode_params.encodeGUID,
  681. ctx->init_encode_params.presetGUID,
  682. &preset_config);
  683. if (nv_status != NV_ENC_SUCCESS)
  684. return nvenc_print_error(avctx, nv_status, "Cannot get the preset configuration");
  685. memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
  686. ctx->encode_config.version = NV_ENC_CONFIG_VER;
  687. if (avctx->sample_aspect_ratio.num && avctx->sample_aspect_ratio.den &&
  688. (avctx->sample_aspect_ratio.num != 1 || avctx->sample_aspect_ratio.num != 1)) {
  689. av_reduce(&dw, &dh,
  690. avctx->width * avctx->sample_aspect_ratio.num,
  691. avctx->height * avctx->sample_aspect_ratio.den,
  692. 1024 * 1024);
  693. ctx->init_encode_params.darHeight = dh;
  694. ctx->init_encode_params.darWidth = dw;
  695. } else {
  696. ctx->init_encode_params.darHeight = avctx->height;
  697. ctx->init_encode_params.darWidth = avctx->width;
  698. }
  699. // De-compensate for hardware, dubiously, trying to compensate for
  700. // playback at 704 pixel width.
  701. if (avctx->width == 720 &&
  702. (avctx->height == 480 || avctx->height == 576)) {
  703. av_reduce(&dw, &dh,
  704. ctx->init_encode_params.darWidth * 44,
  705. ctx->init_encode_params.darHeight * 45,
  706. 1024 * 1024);
  707. ctx->init_encode_params.darHeight = dh;
  708. ctx->init_encode_params.darWidth = dw;
  709. }
  710. ctx->init_encode_params.frameRateNum = avctx->time_base.den;
  711. ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
  712. num_mbs = ((avctx->width + 15) >> 4) * ((avctx->height + 15) >> 4);
  713. ctx->max_surface_count = (num_mbs >= 8160) ? 32 : 48;
  714. if (ctx->buffer_delay >= ctx->max_surface_count)
  715. ctx->buffer_delay = ctx->max_surface_count - 1;
  716. ctx->init_encode_params.enableEncodeAsync = 0;
  717. ctx->init_encode_params.enablePTD = 1;
  718. if (avctx->gop_size > 0) {
  719. if (avctx->max_b_frames >= 0) {
  720. /* 0 is intra-only, 1 is I/P only, 2 is one B Frame, 3 two B frames, and so on. */
  721. ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
  722. }
  723. ctx->encode_config.gopLength = avctx->gop_size;
  724. } else if (avctx->gop_size == 0) {
  725. ctx->encode_config.frameIntervalP = 0;
  726. ctx->encode_config.gopLength = 1;
  727. }
  728. /* when there're b frames, set dts offset */
  729. if (ctx->encode_config.frameIntervalP >= 2)
  730. ctx->last_dts = -2;
  731. nvenc_setup_rate_control(avctx);
  732. if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
  733. ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
  734. } else {
  735. ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
  736. }
  737. res = nvenc_setup_codec_config(avctx);
  738. if (res)
  739. return res;
  740. nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
  741. if (nv_status != NV_ENC_SUCCESS) {
  742. return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
  743. }
  744. if (ctx->encode_config.frameIntervalP > 1)
  745. avctx->has_b_frames = 2;
  746. if (ctx->encode_config.rcParams.averageBitRate > 0)
  747. avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
  748. cpb_props = ff_add_cpb_side_data(avctx);
  749. if (!cpb_props)
  750. return AVERROR(ENOMEM);
  751. cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
  752. cpb_props->avg_bitrate = avctx->bit_rate;
  753. cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
  754. return 0;
  755. }
  756. static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
  757. {
  758. NvencContext *ctx = avctx->priv_data;
  759. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  760. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  761. NVENCSTATUS nv_status;
  762. NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
  763. allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
  764. switch (ctx->data_pix_fmt) {
  765. case AV_PIX_FMT_YUV420P:
  766. ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_YV12_PL;
  767. break;
  768. case AV_PIX_FMT_NV12:
  769. ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_NV12_PL;
  770. break;
  771. case AV_PIX_FMT_YUV444P:
  772. ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_YUV444_PL;
  773. break;
  774. default:
  775. av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format\n");
  776. return AVERROR(EINVAL);
  777. }
  778. if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
  779. ctx->surfaces[idx].in_ref = av_frame_alloc();
  780. if (!ctx->surfaces[idx].in_ref)
  781. return AVERROR(ENOMEM);
  782. } else {
  783. NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
  784. allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
  785. allocSurf.width = (avctx->width + 31) & ~31;
  786. allocSurf.height = (avctx->height + 31) & ~31;
  787. allocSurf.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
  788. allocSurf.bufferFmt = ctx->surfaces[idx].format;
  789. nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
  790. if (nv_status != NV_ENC_SUCCESS) {
  791. return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
  792. }
  793. ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
  794. ctx->surfaces[idx].width = allocSurf.width;
  795. ctx->surfaces[idx].height = allocSurf.height;
  796. }
  797. ctx->surfaces[idx].lockCount = 0;
  798. /* 1MB is large enough to hold most output frames. NVENC increases this automaticaly if it's not enough. */
  799. allocOut.size = 1024 * 1024;
  800. allocOut.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
  801. nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
  802. if (nv_status != NV_ENC_SUCCESS) {
  803. int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
  804. if (avctx->pix_fmt != AV_PIX_FMT_CUDA)
  805. p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
  806. av_frame_free(&ctx->surfaces[idx].in_ref);
  807. return err;
  808. }
  809. ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
  810. ctx->surfaces[idx].size = allocOut.size;
  811. return 0;
  812. }
  813. static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx, int* surfaceCount)
  814. {
  815. int res;
  816. NvencContext *ctx = avctx->priv_data;
  817. ctx->surfaces = av_malloc(ctx->max_surface_count * sizeof(*ctx->surfaces));
  818. if (!ctx->surfaces) {
  819. return AVERROR(ENOMEM);
  820. }
  821. ctx->timestamp_list = av_fifo_alloc(ctx->max_surface_count * sizeof(int64_t));
  822. if (!ctx->timestamp_list)
  823. return AVERROR(ENOMEM);
  824. ctx->output_surface_queue = av_fifo_alloc(ctx->max_surface_count * sizeof(NvencSurface*));
  825. if (!ctx->output_surface_queue)
  826. return AVERROR(ENOMEM);
  827. ctx->output_surface_ready_queue = av_fifo_alloc(ctx->max_surface_count * sizeof(NvencSurface*));
  828. if (!ctx->output_surface_ready_queue)
  829. return AVERROR(ENOMEM);
  830. for (*surfaceCount = 0; *surfaceCount < ctx->max_surface_count; ++*surfaceCount) {
  831. res = nvenc_alloc_surface(avctx, *surfaceCount);
  832. if (res)
  833. return res;
  834. }
  835. return 0;
  836. }
  837. static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
  838. {
  839. NvencContext *ctx = avctx->priv_data;
  840. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  841. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  842. NVENCSTATUS nv_status;
  843. uint32_t outSize = 0;
  844. char tmpHeader[256];
  845. NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
  846. payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
  847. payload.spsppsBuffer = tmpHeader;
  848. payload.inBufferSize = sizeof(tmpHeader);
  849. payload.outSPSPPSPayloadSize = &outSize;
  850. nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
  851. if (nv_status != NV_ENC_SUCCESS) {
  852. return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
  853. }
  854. avctx->extradata_size = outSize;
  855. avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
  856. if (!avctx->extradata) {
  857. return AVERROR(ENOMEM);
  858. }
  859. memcpy(avctx->extradata, tmpHeader, outSize);
  860. return 0;
  861. }
  862. av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
  863. {
  864. NvencContext *ctx = avctx->priv_data;
  865. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  866. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  867. int res;
  868. int i;
  869. int surfaceCount = 0;
  870. if (!nvenc_dyload_nvenc(avctx))
  871. return AVERROR_EXTERNAL;
  872. res = nvenc_setup_device(avctx);
  873. if (res)
  874. goto error;
  875. res = nvenc_open_session(avctx);
  876. if (res)
  877. goto error;
  878. res = nvenc_setup_encoder(avctx);
  879. if (res)
  880. goto error;
  881. res = nvenc_setup_surfaces(avctx, &surfaceCount);
  882. if (res)
  883. goto error;
  884. if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
  885. res = nvenc_setup_extradata(avctx);
  886. if (res)
  887. goto error;
  888. }
  889. return 0;
  890. error:
  891. av_fifo_freep(&ctx->timestamp_list);
  892. av_fifo_freep(&ctx->output_surface_ready_queue);
  893. av_fifo_freep(&ctx->output_surface_queue);
  894. for (i = 0; i < surfaceCount; ++i) {
  895. if (avctx->pix_fmt != AV_PIX_FMT_CUDA)
  896. p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
  897. av_frame_free(&ctx->surfaces[i].in_ref);
  898. p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
  899. }
  900. av_freep(&ctx->surfaces);
  901. if (ctx->nvencoder)
  902. p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
  903. ctx->nvencoder = NULL;
  904. if (ctx->cu_context_internal)
  905. dl_fn->cu_ctx_destroy(ctx->cu_context_internal);
  906. ctx->cu_context = ctx->cu_context_internal = NULL;
  907. nvenc_unload_nvenc(avctx);
  908. return res;
  909. }
  910. av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
  911. {
  912. NvencContext *ctx = avctx->priv_data;
  913. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  914. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  915. int i;
  916. av_fifo_freep(&ctx->timestamp_list);
  917. av_fifo_freep(&ctx->output_surface_ready_queue);
  918. av_fifo_freep(&ctx->output_surface_queue);
  919. if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
  920. for (i = 0; i < ctx->max_surface_count; ++i) {
  921. if (ctx->surfaces[i].input_surface) {
  922. p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->surfaces[i].in_map.mappedResource);
  923. }
  924. }
  925. for (i = 0; i < ctx->nb_registered_frames; i++) {
  926. if (ctx->registered_frames[i].regptr)
  927. p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
  928. }
  929. ctx->nb_registered_frames = 0;
  930. }
  931. for (i = 0; i < ctx->max_surface_count; ++i) {
  932. if (avctx->pix_fmt != AV_PIX_FMT_CUDA)
  933. p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
  934. av_frame_free(&ctx->surfaces[i].in_ref);
  935. p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
  936. }
  937. av_freep(&ctx->surfaces);
  938. ctx->max_surface_count = 0;
  939. p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
  940. ctx->nvencoder = NULL;
  941. if (ctx->cu_context_internal)
  942. dl_fn->cu_ctx_destroy(ctx->cu_context_internal);
  943. ctx->cu_context = ctx->cu_context_internal = NULL;
  944. nvenc_unload_nvenc(avctx);
  945. return 0;
  946. }
  947. static NvencSurface *get_free_frame(NvencContext *ctx)
  948. {
  949. int i;
  950. for (i = 0; i < ctx->max_surface_count; ++i) {
  951. if (!ctx->surfaces[i].lockCount) {
  952. ctx->surfaces[i].lockCount = 1;
  953. return &ctx->surfaces[i];
  954. }
  955. }
  956. return NULL;
  957. }
  958. static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *inSurf,
  959. NV_ENC_LOCK_INPUT_BUFFER *lockBufferParams, const AVFrame *frame)
  960. {
  961. uint8_t *buf = lockBufferParams->bufferDataPtr;
  962. int off = inSurf->height * lockBufferParams->pitch;
  963. if (frame->format == AV_PIX_FMT_YUV420P) {
  964. av_image_copy_plane(buf, lockBufferParams->pitch,
  965. frame->data[0], frame->linesize[0],
  966. avctx->width, avctx->height);
  967. buf += off;
  968. av_image_copy_plane(buf, lockBufferParams->pitch >> 1,
  969. frame->data[2], frame->linesize[2],
  970. avctx->width >> 1, avctx->height >> 1);
  971. buf += off >> 2;
  972. av_image_copy_plane(buf, lockBufferParams->pitch >> 1,
  973. frame->data[1], frame->linesize[1],
  974. avctx->width >> 1, avctx->height >> 1);
  975. } else if (frame->format == AV_PIX_FMT_NV12) {
  976. av_image_copy_plane(buf, lockBufferParams->pitch,
  977. frame->data[0], frame->linesize[0],
  978. avctx->width, avctx->height);
  979. buf += off;
  980. av_image_copy_plane(buf, lockBufferParams->pitch,
  981. frame->data[1], frame->linesize[1],
  982. avctx->width, avctx->height >> 1);
  983. } else if (frame->format == AV_PIX_FMT_YUV444P) {
  984. av_image_copy_plane(buf, lockBufferParams->pitch,
  985. frame->data[0], frame->linesize[0],
  986. avctx->width, avctx->height);
  987. buf += off;
  988. av_image_copy_plane(buf, lockBufferParams->pitch,
  989. frame->data[1], frame->linesize[1],
  990. avctx->width, avctx->height);
  991. buf += off;
  992. av_image_copy_plane(buf, lockBufferParams->pitch,
  993. frame->data[2], frame->linesize[2],
  994. avctx->width, avctx->height);
  995. } else {
  996. av_log(avctx, AV_LOG_FATAL, "Invalid pixel format!\n");
  997. return AVERROR(EINVAL);
  998. }
  999. return 0;
  1000. }
  1001. static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
  1002. {
  1003. NvencContext *ctx = avctx->priv_data;
  1004. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  1005. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  1006. int i;
  1007. if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
  1008. for (i = 0; i < ctx->nb_registered_frames; i++) {
  1009. if (!ctx->registered_frames[i].mapped) {
  1010. if (ctx->registered_frames[i].regptr) {
  1011. p_nvenc->nvEncUnregisterResource(ctx->nvencoder,
  1012. ctx->registered_frames[i].regptr);
  1013. ctx->registered_frames[i].regptr = NULL;
  1014. }
  1015. return i;
  1016. }
  1017. }
  1018. } else {
  1019. return ctx->nb_registered_frames++;
  1020. }
  1021. av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
  1022. return AVERROR(ENOMEM);
  1023. }
  1024. static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
  1025. {
  1026. NvencContext *ctx = avctx->priv_data;
  1027. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  1028. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  1029. AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  1030. NV_ENC_REGISTER_RESOURCE reg;
  1031. int i, idx, ret;
  1032. for (i = 0; i < ctx->nb_registered_frames; i++) {
  1033. if (ctx->registered_frames[i].ptr == (CUdeviceptr)frame->data[0])
  1034. return i;
  1035. }
  1036. idx = nvenc_find_free_reg_resource(avctx);
  1037. if (idx < 0)
  1038. return idx;
  1039. reg.version = NV_ENC_REGISTER_RESOURCE_VER;
  1040. reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
  1041. reg.width = frames_ctx->width;
  1042. reg.height = frames_ctx->height;
  1043. reg.bufferFormat = ctx->surfaces[0].format;
  1044. reg.pitch = frame->linesize[0];
  1045. reg.resourceToRegister = frame->data[0];
  1046. ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, &reg);
  1047. if (ret != NV_ENC_SUCCESS) {
  1048. nvenc_print_error(avctx, ret, "Error registering an input resource");
  1049. return AVERROR_UNKNOWN;
  1050. }
  1051. ctx->registered_frames[idx].ptr = (CUdeviceptr)frame->data[0];
  1052. ctx->registered_frames[idx].regptr = reg.registeredResource;
  1053. return idx;
  1054. }
  1055. static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
  1056. NvencSurface *nvenc_frame)
  1057. {
  1058. NvencContext *ctx = avctx->priv_data;
  1059. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  1060. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  1061. int res;
  1062. NVENCSTATUS nv_status;
  1063. if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
  1064. int reg_idx = nvenc_register_frame(avctx, frame);
  1065. if (reg_idx < 0) {
  1066. av_log(avctx, AV_LOG_ERROR, "Could not register an input CUDA frame\n");
  1067. return reg_idx;
  1068. }
  1069. res = av_frame_ref(nvenc_frame->in_ref, frame);
  1070. if (res < 0)
  1071. return res;
  1072. nvenc_frame->in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
  1073. nvenc_frame->in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
  1074. nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &nvenc_frame->in_map);
  1075. if (nv_status != NV_ENC_SUCCESS) {
  1076. av_frame_unref(nvenc_frame->in_ref);
  1077. return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
  1078. }
  1079. ctx->registered_frames[reg_idx].mapped = 1;
  1080. nvenc_frame->reg_idx = reg_idx;
  1081. nvenc_frame->input_surface = nvenc_frame->in_map.mappedResource;
  1082. return 0;
  1083. } else {
  1084. NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
  1085. lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
  1086. lockBufferParams.inputBuffer = nvenc_frame->input_surface;
  1087. nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
  1088. if (nv_status != NV_ENC_SUCCESS) {
  1089. return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
  1090. }
  1091. res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
  1092. nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
  1093. if (nv_status != NV_ENC_SUCCESS) {
  1094. return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
  1095. }
  1096. return res;
  1097. }
  1098. }
  1099. static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
  1100. NV_ENC_PIC_PARAMS *params)
  1101. {
  1102. NvencContext *ctx = avctx->priv_data;
  1103. switch (avctx->codec->id) {
  1104. case AV_CODEC_ID_H264:
  1105. params->codecPicParams.h264PicParams.sliceMode = ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
  1106. params->codecPicParams.h264PicParams.sliceModeData = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
  1107. break;
  1108. case AV_CODEC_ID_H265:
  1109. params->codecPicParams.hevcPicParams.sliceMode = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
  1110. params->codecPicParams.hevcPicParams.sliceModeData = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
  1111. break;
  1112. }
  1113. }
  1114. static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
  1115. {
  1116. NvencContext *ctx = avctx->priv_data;
  1117. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  1118. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  1119. uint32_t slice_mode_data;
  1120. uint32_t *slice_offsets;
  1121. NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
  1122. NVENCSTATUS nv_status;
  1123. int res = 0;
  1124. enum AVPictureType pict_type;
  1125. switch (avctx->codec->id) {
  1126. case AV_CODEC_ID_H264:
  1127. slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
  1128. break;
  1129. case AV_CODEC_ID_H265:
  1130. slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
  1131. break;
  1132. default:
  1133. av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
  1134. res = AVERROR(EINVAL);
  1135. goto error;
  1136. }
  1137. slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
  1138. if (!slice_offsets)
  1139. return AVERROR(ENOMEM);
  1140. lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
  1141. lock_params.doNotWait = 0;
  1142. lock_params.outputBitstream = tmpoutsurf->output_surface;
  1143. lock_params.sliceOffsets = slice_offsets;
  1144. nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
  1145. if (nv_status != NV_ENC_SUCCESS) {
  1146. res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
  1147. goto error;
  1148. }
  1149. if (res = ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes,0)) {
  1150. p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
  1151. goto error;
  1152. }
  1153. memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
  1154. nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
  1155. if (nv_status != NV_ENC_SUCCESS)
  1156. nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
  1157. if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
  1158. p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, tmpoutsurf->in_map.mappedResource);
  1159. av_frame_unref(tmpoutsurf->in_ref);
  1160. ctx->registered_frames[tmpoutsurf->reg_idx].mapped = 0;
  1161. tmpoutsurf->input_surface = NULL;
  1162. }
  1163. switch (lock_params.pictureType) {
  1164. case NV_ENC_PIC_TYPE_IDR:
  1165. pkt->flags |= AV_PKT_FLAG_KEY;
  1166. case NV_ENC_PIC_TYPE_I:
  1167. pict_type = AV_PICTURE_TYPE_I;
  1168. break;
  1169. case NV_ENC_PIC_TYPE_P:
  1170. pict_type = AV_PICTURE_TYPE_P;
  1171. break;
  1172. case NV_ENC_PIC_TYPE_B:
  1173. pict_type = AV_PICTURE_TYPE_B;
  1174. break;
  1175. case NV_ENC_PIC_TYPE_BI:
  1176. pict_type = AV_PICTURE_TYPE_BI;
  1177. break;
  1178. default:
  1179. av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
  1180. av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
  1181. res = AVERROR_EXTERNAL;
  1182. goto error;
  1183. }
  1184. #if FF_API_CODED_FRAME
  1185. FF_DISABLE_DEPRECATION_WARNINGS
  1186. avctx->coded_frame->pict_type = pict_type;
  1187. FF_ENABLE_DEPRECATION_WARNINGS
  1188. #endif
  1189. ff_side_data_set_encoder_stats(pkt,
  1190. (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
  1191. pkt->pts = lock_params.outputTimeStamp;
  1192. pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
  1193. /* when there're b frame(s), set dts offset */
  1194. if (ctx->encode_config.frameIntervalP >= 2)
  1195. pkt->dts -= 1;
  1196. if (pkt->dts > pkt->pts)
  1197. pkt->dts = pkt->pts;
  1198. if (ctx->last_dts != AV_NOPTS_VALUE && pkt->dts <= ctx->last_dts)
  1199. pkt->dts = ctx->last_dts + 1;
  1200. ctx->last_dts = pkt->dts;
  1201. av_free(slice_offsets);
  1202. return 0;
  1203. error:
  1204. av_free(slice_offsets);
  1205. timestamp_queue_dequeue(ctx->timestamp_list);
  1206. return res;
  1207. }
  1208. static int output_ready(NvencContext *ctx, int flush)
  1209. {
  1210. int nb_ready, nb_pending;
  1211. nb_ready = av_fifo_size(ctx->output_surface_ready_queue) / sizeof(NvencSurface*);
  1212. nb_pending = av_fifo_size(ctx->output_surface_queue) / sizeof(NvencSurface*);
  1213. return nb_ready > 0 && (flush || nb_ready + nb_pending >= ctx->buffer_delay);
  1214. }
  1215. int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
  1216. const AVFrame *frame, int *got_packet)
  1217. {
  1218. NVENCSTATUS nv_status;
  1219. NvencSurface *tmpoutsurf, *inSurf;
  1220. int res;
  1221. NvencContext *ctx = avctx->priv_data;
  1222. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  1223. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  1224. NV_ENC_PIC_PARAMS pic_params = { 0 };
  1225. pic_params.version = NV_ENC_PIC_PARAMS_VER;
  1226. if (frame) {
  1227. inSurf = get_free_frame(ctx);
  1228. av_assert0(inSurf);
  1229. res = nvenc_upload_frame(avctx, frame, inSurf);
  1230. if (res) {
  1231. inSurf->lockCount = 0;
  1232. return res;
  1233. }
  1234. pic_params.inputBuffer = inSurf->input_surface;
  1235. pic_params.bufferFmt = inSurf->format;
  1236. pic_params.inputWidth = avctx->width;
  1237. pic_params.inputHeight = avctx->height;
  1238. pic_params.outputBitstream = inSurf->output_surface;
  1239. pic_params.completionEvent = 0;
  1240. if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
  1241. if (frame->top_field_first) {
  1242. pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
  1243. } else {
  1244. pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
  1245. }
  1246. } else {
  1247. pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
  1248. }
  1249. pic_params.encodePicFlags = 0;
  1250. pic_params.inputTimeStamp = frame->pts;
  1251. pic_params.inputDuration = 0;
  1252. nvenc_codec_specific_pic_params(avctx, &pic_params);
  1253. timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
  1254. } else {
  1255. pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
  1256. }
  1257. nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
  1258. if (frame && nv_status == NV_ENC_ERR_NEED_MORE_INPUT)
  1259. av_fifo_generic_write(ctx->output_surface_queue, &inSurf, sizeof(inSurf), NULL);
  1260. if (nv_status != NV_ENC_SUCCESS && nv_status != NV_ENC_ERR_NEED_MORE_INPUT) {
  1261. return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
  1262. }
  1263. if (nv_status != NV_ENC_ERR_NEED_MORE_INPUT) {
  1264. while (av_fifo_size(ctx->output_surface_queue) > 0) {
  1265. av_fifo_generic_read(ctx->output_surface_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
  1266. av_fifo_generic_write(ctx->output_surface_ready_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
  1267. }
  1268. if (frame)
  1269. av_fifo_generic_write(ctx->output_surface_ready_queue, &inSurf, sizeof(inSurf), NULL);
  1270. }
  1271. if (output_ready(ctx, !frame)) {
  1272. av_fifo_generic_read(ctx->output_surface_ready_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
  1273. res = process_output_surface(avctx, pkt, tmpoutsurf);
  1274. if (res)
  1275. return res;
  1276. av_assert0(tmpoutsurf->lockCount);
  1277. tmpoutsurf->lockCount--;
  1278. *got_packet = 1;
  1279. } else {
  1280. *got_packet = 0;
  1281. }
  1282. return 0;
  1283. }