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.

1649 lines
54KB

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