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.

2092 lines
70KB

  1. /*
  2. * H.264/HEVC hardware encoding using nvidia nvenc
  3. * Copyright (c) 2016 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. #include "nvenc.h"
  23. #include "libavutil/hwcontext_cuda.h"
  24. #include "libavutil/hwcontext.h"
  25. #include "libavutil/imgutils.h"
  26. #include "libavutil/avassert.h"
  27. #include "libavutil/mem.h"
  28. #include "libavutil/pixdesc.h"
  29. #include "internal.h"
  30. #define NVENC_CAP 0x30
  31. #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR || \
  32. rc == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ || \
  33. rc == NV_ENC_PARAMS_RC_CBR_HQ)
  34. const enum AVPixelFormat ff_nvenc_pix_fmts[] = {
  35. AV_PIX_FMT_YUV420P,
  36. AV_PIX_FMT_NV12,
  37. AV_PIX_FMT_P010,
  38. AV_PIX_FMT_YUV444P,
  39. AV_PIX_FMT_P016, // Truncated to 10bits
  40. AV_PIX_FMT_YUV444P16, // Truncated to 10bits
  41. AV_PIX_FMT_0RGB32,
  42. AV_PIX_FMT_0BGR32,
  43. AV_PIX_FMT_CUDA,
  44. #if CONFIG_D3D11VA
  45. AV_PIX_FMT_D3D11,
  46. #endif
  47. AV_PIX_FMT_NONE
  48. };
  49. #define IS_10BIT(pix_fmt) (pix_fmt == AV_PIX_FMT_P010 || \
  50. pix_fmt == AV_PIX_FMT_P016 || \
  51. pix_fmt == AV_PIX_FMT_YUV444P16)
  52. #define IS_YUV444(pix_fmt) (pix_fmt == AV_PIX_FMT_YUV444P || \
  53. pix_fmt == AV_PIX_FMT_YUV444P16)
  54. static const struct {
  55. NVENCSTATUS nverr;
  56. int averr;
  57. const char *desc;
  58. } nvenc_errors[] = {
  59. { NV_ENC_SUCCESS, 0, "success" },
  60. { NV_ENC_ERR_NO_ENCODE_DEVICE, AVERROR(ENOENT), "no encode device" },
  61. { NV_ENC_ERR_UNSUPPORTED_DEVICE, AVERROR(ENOSYS), "unsupported device" },
  62. { NV_ENC_ERR_INVALID_ENCODERDEVICE, AVERROR(EINVAL), "invalid encoder device" },
  63. { NV_ENC_ERR_INVALID_DEVICE, AVERROR(EINVAL), "invalid device" },
  64. { NV_ENC_ERR_DEVICE_NOT_EXIST, AVERROR(EIO), "device does not exist" },
  65. { NV_ENC_ERR_INVALID_PTR, AVERROR(EFAULT), "invalid ptr" },
  66. { NV_ENC_ERR_INVALID_EVENT, AVERROR(EINVAL), "invalid event" },
  67. { NV_ENC_ERR_INVALID_PARAM, AVERROR(EINVAL), "invalid param" },
  68. { NV_ENC_ERR_INVALID_CALL, AVERROR(EINVAL), "invalid call" },
  69. { NV_ENC_ERR_OUT_OF_MEMORY, AVERROR(ENOMEM), "out of memory" },
  70. { NV_ENC_ERR_ENCODER_NOT_INITIALIZED, AVERROR(EINVAL), "encoder not initialized" },
  71. { NV_ENC_ERR_UNSUPPORTED_PARAM, AVERROR(ENOSYS), "unsupported param" },
  72. { NV_ENC_ERR_LOCK_BUSY, AVERROR(EAGAIN), "lock busy" },
  73. { NV_ENC_ERR_NOT_ENOUGH_BUFFER, AVERROR_BUFFER_TOO_SMALL, "not enough buffer"},
  74. { NV_ENC_ERR_INVALID_VERSION, AVERROR(EINVAL), "invalid version" },
  75. { NV_ENC_ERR_MAP_FAILED, AVERROR(EIO), "map failed" },
  76. { NV_ENC_ERR_NEED_MORE_INPUT, AVERROR(EAGAIN), "need more input" },
  77. { NV_ENC_ERR_ENCODER_BUSY, AVERROR(EAGAIN), "encoder busy" },
  78. { NV_ENC_ERR_EVENT_NOT_REGISTERD, AVERROR(EBADF), "event not registered" },
  79. { NV_ENC_ERR_GENERIC, AVERROR_UNKNOWN, "generic error" },
  80. { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY, AVERROR(EINVAL), "incompatible client key" },
  81. { NV_ENC_ERR_UNIMPLEMENTED, AVERROR(ENOSYS), "unimplemented" },
  82. { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO), "resource register failed" },
  83. { NV_ENC_ERR_RESOURCE_NOT_REGISTERED, AVERROR(EBADF), "resource not registered" },
  84. { NV_ENC_ERR_RESOURCE_NOT_MAPPED, AVERROR(EBADF), "resource not mapped" },
  85. };
  86. static int nvenc_map_error(NVENCSTATUS err, const char **desc)
  87. {
  88. int i;
  89. for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
  90. if (nvenc_errors[i].nverr == err) {
  91. if (desc)
  92. *desc = nvenc_errors[i].desc;
  93. return nvenc_errors[i].averr;
  94. }
  95. }
  96. if (desc)
  97. *desc = "unknown error";
  98. return AVERROR_UNKNOWN;
  99. }
  100. static int nvenc_print_error(void *log_ctx, NVENCSTATUS err,
  101. const char *error_string)
  102. {
  103. const char *desc;
  104. int ret;
  105. ret = nvenc_map_error(err, &desc);
  106. av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
  107. return ret;
  108. }
  109. static void nvenc_print_driver_requirement(AVCodecContext *avctx, int level)
  110. {
  111. #if NVENCAPI_CHECK_VERSION(8, 1)
  112. # if defined(_WIN32) || defined(__CYGWIN__)
  113. const char *minver = "390.77";
  114. # else
  115. const char *minver = "390.25";
  116. # endif
  117. #else
  118. # if defined(_WIN32) || defined(__CYGWIN__)
  119. const char *minver = "378.66";
  120. # else
  121. const char *minver = "378.13";
  122. # endif
  123. #endif
  124. av_log(avctx, level, "The minimum required Nvidia driver for nvenc is %s or newer\n", minver);
  125. }
  126. static av_cold int nvenc_load_libraries(AVCodecContext *avctx)
  127. {
  128. NvencContext *ctx = avctx->priv_data;
  129. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  130. NVENCSTATUS err;
  131. uint32_t nvenc_max_ver;
  132. int ret;
  133. ret = cuda_load_functions(&dl_fn->cuda_dl, avctx);
  134. if (ret < 0)
  135. return ret;
  136. ret = nvenc_load_functions(&dl_fn->nvenc_dl, avctx);
  137. if (ret < 0) {
  138. nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
  139. return ret;
  140. }
  141. err = dl_fn->nvenc_dl->NvEncodeAPIGetMaxSupportedVersion(&nvenc_max_ver);
  142. if (err != NV_ENC_SUCCESS)
  143. return nvenc_print_error(avctx, err, "Failed to query nvenc max version");
  144. av_log(avctx, AV_LOG_VERBOSE, "Loaded Nvenc version %d.%d\n", nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
  145. if ((NVENCAPI_MAJOR_VERSION << 4 | NVENCAPI_MINOR_VERSION) > nvenc_max_ver) {
  146. av_log(avctx, AV_LOG_ERROR, "Driver does not support the required nvenc API version. "
  147. "Required: %d.%d Found: %d.%d\n",
  148. NVENCAPI_MAJOR_VERSION, NVENCAPI_MINOR_VERSION,
  149. nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
  150. nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
  151. return AVERROR(ENOSYS);
  152. }
  153. dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
  154. err = dl_fn->nvenc_dl->NvEncodeAPICreateInstance(&dl_fn->nvenc_funcs);
  155. if (err != NV_ENC_SUCCESS)
  156. return nvenc_print_error(avctx, err, "Failed to create nvenc instance");
  157. av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
  158. return 0;
  159. }
  160. static int nvenc_push_context(AVCodecContext *avctx)
  161. {
  162. NvencContext *ctx = avctx->priv_data;
  163. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  164. CUresult cu_res;
  165. if (ctx->d3d11_device)
  166. return 0;
  167. cu_res = dl_fn->cuda_dl->cuCtxPushCurrent(ctx->cu_context);
  168. if (cu_res != CUDA_SUCCESS) {
  169. av_log(avctx, AV_LOG_ERROR, "cuCtxPushCurrent failed\n");
  170. return AVERROR_EXTERNAL;
  171. }
  172. return 0;
  173. }
  174. static int nvenc_pop_context(AVCodecContext *avctx)
  175. {
  176. NvencContext *ctx = avctx->priv_data;
  177. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  178. CUresult cu_res;
  179. CUcontext dummy;
  180. if (ctx->d3d11_device)
  181. return 0;
  182. cu_res = dl_fn->cuda_dl->cuCtxPopCurrent(&dummy);
  183. if (cu_res != CUDA_SUCCESS) {
  184. av_log(avctx, AV_LOG_ERROR, "cuCtxPopCurrent failed\n");
  185. return AVERROR_EXTERNAL;
  186. }
  187. return 0;
  188. }
  189. static av_cold int nvenc_open_session(AVCodecContext *avctx)
  190. {
  191. NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
  192. NvencContext *ctx = avctx->priv_data;
  193. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
  194. NVENCSTATUS ret;
  195. params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
  196. params.apiVersion = NVENCAPI_VERSION;
  197. if (ctx->d3d11_device) {
  198. params.device = ctx->d3d11_device;
  199. params.deviceType = NV_ENC_DEVICE_TYPE_DIRECTX;
  200. } else {
  201. params.device = ctx->cu_context;
  202. params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
  203. }
  204. ret = p_nvenc->nvEncOpenEncodeSessionEx(&params, &ctx->nvencoder);
  205. if (ret != NV_ENC_SUCCESS) {
  206. ctx->nvencoder = NULL;
  207. return nvenc_print_error(avctx, ret, "OpenEncodeSessionEx failed");
  208. }
  209. return 0;
  210. }
  211. static int nvenc_check_codec_support(AVCodecContext *avctx)
  212. {
  213. NvencContext *ctx = avctx->priv_data;
  214. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
  215. int i, ret, count = 0;
  216. GUID *guids = NULL;
  217. ret = p_nvenc->nvEncGetEncodeGUIDCount(ctx->nvencoder, &count);
  218. if (ret != NV_ENC_SUCCESS || !count)
  219. return AVERROR(ENOSYS);
  220. guids = av_malloc(count * sizeof(GUID));
  221. if (!guids)
  222. return AVERROR(ENOMEM);
  223. ret = p_nvenc->nvEncGetEncodeGUIDs(ctx->nvencoder, guids, count, &count);
  224. if (ret != NV_ENC_SUCCESS) {
  225. ret = AVERROR(ENOSYS);
  226. goto fail;
  227. }
  228. ret = AVERROR(ENOSYS);
  229. for (i = 0; i < count; i++) {
  230. if (!memcmp(&guids[i], &ctx->init_encode_params.encodeGUID, sizeof(*guids))) {
  231. ret = 0;
  232. break;
  233. }
  234. }
  235. fail:
  236. av_free(guids);
  237. return ret;
  238. }
  239. static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
  240. {
  241. NvencContext *ctx = avctx->priv_data;
  242. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
  243. NV_ENC_CAPS_PARAM params = { 0 };
  244. int ret, val = 0;
  245. params.version = NV_ENC_CAPS_PARAM_VER;
  246. params.capsToQuery = cap;
  247. ret = p_nvenc->nvEncGetEncodeCaps(ctx->nvencoder, ctx->init_encode_params.encodeGUID, &params, &val);
  248. if (ret == NV_ENC_SUCCESS)
  249. return val;
  250. return 0;
  251. }
  252. static int nvenc_check_capabilities(AVCodecContext *avctx)
  253. {
  254. NvencContext *ctx = avctx->priv_data;
  255. int ret;
  256. ret = nvenc_check_codec_support(avctx);
  257. if (ret < 0) {
  258. av_log(avctx, AV_LOG_VERBOSE, "Codec not supported\n");
  259. return ret;
  260. }
  261. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
  262. if (IS_YUV444(ctx->data_pix_fmt) && ret <= 0) {
  263. av_log(avctx, AV_LOG_VERBOSE, "YUV444P not supported\n");
  264. return AVERROR(ENOSYS);
  265. }
  266. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOSSLESS_ENCODE);
  267. if (ctx->preset >= PRESET_LOSSLESS_DEFAULT && ret <= 0) {
  268. av_log(avctx, AV_LOG_VERBOSE, "Lossless encoding not supported\n");
  269. return AVERROR(ENOSYS);
  270. }
  271. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
  272. if (ret < avctx->width) {
  273. av_log(avctx, AV_LOG_VERBOSE, "Width %d exceeds %d\n",
  274. avctx->width, ret);
  275. return AVERROR(ENOSYS);
  276. }
  277. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
  278. if (ret < avctx->height) {
  279. av_log(avctx, AV_LOG_VERBOSE, "Height %d exceeds %d\n",
  280. avctx->height, ret);
  281. return AVERROR(ENOSYS);
  282. }
  283. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
  284. if (ret < avctx->max_b_frames) {
  285. av_log(avctx, AV_LOG_VERBOSE, "Max B-frames %d exceed %d\n",
  286. avctx->max_b_frames, ret);
  287. return AVERROR(ENOSYS);
  288. }
  289. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_FIELD_ENCODING);
  290. if (ret < 1 && avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
  291. av_log(avctx, AV_LOG_VERBOSE,
  292. "Interlaced encoding is not supported. Supported level: %d\n",
  293. ret);
  294. return AVERROR(ENOSYS);
  295. }
  296. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_10BIT_ENCODE);
  297. if (IS_10BIT(ctx->data_pix_fmt) && ret <= 0) {
  298. av_log(avctx, AV_LOG_VERBOSE, "10 bit encode not supported\n");
  299. return AVERROR(ENOSYS);
  300. }
  301. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOOKAHEAD);
  302. if (ctx->rc_lookahead > 0 && ret <= 0) {
  303. av_log(avctx, AV_LOG_VERBOSE, "RC lookahead not supported\n");
  304. return AVERROR(ENOSYS);
  305. }
  306. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_TEMPORAL_AQ);
  307. if (ctx->temporal_aq > 0 && ret <= 0) {
  308. av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ not supported\n");
  309. return AVERROR(ENOSYS);
  310. }
  311. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_WEIGHTED_PREDICTION);
  312. if (ctx->weighted_pred > 0 && ret <= 0) {
  313. av_log (avctx, AV_LOG_VERBOSE, "Weighted Prediction not supported\n");
  314. return AVERROR(ENOSYS);
  315. }
  316. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_CABAC);
  317. if (ctx->coder == NV_ENC_H264_ENTROPY_CODING_MODE_CABAC && ret <= 0) {
  318. av_log(avctx, AV_LOG_VERBOSE, "CABAC entropy coding not supported\n");
  319. return AVERROR(ENOSYS);
  320. }
  321. #ifdef NVENC_HAVE_BFRAME_REF_MODE
  322. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_BFRAME_REF_MODE);
  323. if (ctx->b_ref_mode == NV_ENC_BFRAME_REF_MODE_EACH && ret != 1) {
  324. av_log(avctx, AV_LOG_VERBOSE, "Each B frame as reference is not supported\n");
  325. return AVERROR(ENOSYS);
  326. } else if (ctx->b_ref_mode != NV_ENC_BFRAME_REF_MODE_DISABLED && ret == 0) {
  327. av_log(avctx, AV_LOG_VERBOSE, "B frames as references are not supported\n");
  328. return AVERROR(ENOSYS);
  329. }
  330. #else
  331. if (ctx->b_ref_mode != 0) {
  332. av_log(avctx, AV_LOG_VERBOSE, "B frames as references need SDK 8.1 at build time\n");
  333. return AVERROR(ENOSYS);
  334. }
  335. #endif
  336. return 0;
  337. }
  338. static av_cold int nvenc_check_device(AVCodecContext *avctx, int idx)
  339. {
  340. NvencContext *ctx = avctx->priv_data;
  341. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  342. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  343. char name[128] = { 0};
  344. int major, minor, ret;
  345. CUresult cu_res;
  346. CUdevice cu_device;
  347. int loglevel = AV_LOG_VERBOSE;
  348. if (ctx->device == LIST_DEVICES)
  349. loglevel = AV_LOG_INFO;
  350. cu_res = dl_fn->cuda_dl->cuDeviceGet(&cu_device, idx);
  351. if (cu_res != CUDA_SUCCESS) {
  352. av_log(avctx, AV_LOG_ERROR,
  353. "Cannot access the CUDA device %d\n",
  354. idx);
  355. return -1;
  356. }
  357. cu_res = dl_fn->cuda_dl->cuDeviceGetName(name, sizeof(name), cu_device);
  358. if (cu_res != CUDA_SUCCESS) {
  359. av_log(avctx, AV_LOG_ERROR, "cuDeviceGetName failed on device %d\n", idx);
  360. return -1;
  361. }
  362. cu_res = dl_fn->cuda_dl->cuDeviceComputeCapability(&major, &minor, cu_device);
  363. if (cu_res != CUDA_SUCCESS) {
  364. av_log(avctx, AV_LOG_ERROR, "cuDeviceComputeCapability failed on device %d\n", idx);
  365. return -1;
  366. }
  367. av_log(avctx, loglevel, "[ GPU #%d - < %s > has Compute SM %d.%d ]\n", idx, name, major, minor);
  368. if (((major << 4) | minor) < NVENC_CAP) {
  369. av_log(avctx, loglevel, "does not support NVENC\n");
  370. goto fail;
  371. }
  372. if (ctx->device != idx && ctx->device != ANY_DEVICE)
  373. return -1;
  374. cu_res = dl_fn->cuda_dl->cuCtxCreate(&ctx->cu_context_internal, 0, cu_device);
  375. if (cu_res != CUDA_SUCCESS) {
  376. av_log(avctx, AV_LOG_FATAL, "Failed creating CUDA context for NVENC: 0x%x\n", (int)cu_res);
  377. goto fail;
  378. }
  379. ctx->cu_context = ctx->cu_context_internal;
  380. if ((ret = nvenc_pop_context(avctx)) < 0)
  381. goto fail2;
  382. if ((ret = nvenc_open_session(avctx)) < 0)
  383. goto fail2;
  384. if ((ret = nvenc_check_capabilities(avctx)) < 0)
  385. goto fail3;
  386. av_log(avctx, loglevel, "supports NVENC\n");
  387. dl_fn->nvenc_device_count++;
  388. if (ctx->device == idx || ctx->device == ANY_DEVICE)
  389. return 0;
  390. fail3:
  391. if ((ret = nvenc_push_context(avctx)) < 0)
  392. return ret;
  393. p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
  394. ctx->nvencoder = NULL;
  395. if ((ret = nvenc_pop_context(avctx)) < 0)
  396. return ret;
  397. fail2:
  398. dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal);
  399. ctx->cu_context_internal = NULL;
  400. fail:
  401. return AVERROR(ENOSYS);
  402. }
  403. static av_cold int nvenc_setup_device(AVCodecContext *avctx)
  404. {
  405. NvencContext *ctx = avctx->priv_data;
  406. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  407. switch (avctx->codec->id) {
  408. case AV_CODEC_ID_H264:
  409. ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
  410. break;
  411. case AV_CODEC_ID_HEVC:
  412. ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
  413. break;
  414. default:
  415. return AVERROR_BUG;
  416. }
  417. if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11 || avctx->hw_frames_ctx || avctx->hw_device_ctx) {
  418. AVHWFramesContext *frames_ctx;
  419. AVHWDeviceContext *hwdev_ctx;
  420. AVCUDADeviceContext *cuda_device_hwctx = NULL;
  421. #if CONFIG_D3D11VA
  422. AVD3D11VADeviceContext *d3d11_device_hwctx = NULL;
  423. #endif
  424. int ret;
  425. if (avctx->hw_frames_ctx) {
  426. frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  427. if (frames_ctx->format == AV_PIX_FMT_CUDA)
  428. cuda_device_hwctx = frames_ctx->device_ctx->hwctx;
  429. #if CONFIG_D3D11VA
  430. else if (frames_ctx->format == AV_PIX_FMT_D3D11)
  431. d3d11_device_hwctx = frames_ctx->device_ctx->hwctx;
  432. #endif
  433. else
  434. return AVERROR(EINVAL);
  435. } else if (avctx->hw_device_ctx) {
  436. hwdev_ctx = (AVHWDeviceContext*)avctx->hw_device_ctx->data;
  437. if (hwdev_ctx->type == AV_HWDEVICE_TYPE_CUDA)
  438. cuda_device_hwctx = hwdev_ctx->hwctx;
  439. #if CONFIG_D3D11VA
  440. else if (hwdev_ctx->type == AV_HWDEVICE_TYPE_D3D11VA)
  441. d3d11_device_hwctx = hwdev_ctx->hwctx;
  442. #endif
  443. else
  444. return AVERROR(EINVAL);
  445. } else {
  446. return AVERROR(EINVAL);
  447. }
  448. if (cuda_device_hwctx) {
  449. ctx->cu_context = cuda_device_hwctx->cuda_ctx;
  450. }
  451. #if CONFIG_D3D11VA
  452. else if (d3d11_device_hwctx) {
  453. ctx->d3d11_device = d3d11_device_hwctx->device;
  454. ID3D11Device_AddRef(ctx->d3d11_device);
  455. }
  456. #endif
  457. ret = nvenc_open_session(avctx);
  458. if (ret < 0)
  459. return ret;
  460. ret = nvenc_check_capabilities(avctx);
  461. if (ret < 0) {
  462. av_log(avctx, AV_LOG_FATAL, "Provided device doesn't support required NVENC features\n");
  463. return ret;
  464. }
  465. } else {
  466. int i, nb_devices = 0;
  467. if ((dl_fn->cuda_dl->cuInit(0)) != CUDA_SUCCESS) {
  468. av_log(avctx, AV_LOG_ERROR,
  469. "Cannot init CUDA\n");
  470. return AVERROR_UNKNOWN;
  471. }
  472. if ((dl_fn->cuda_dl->cuDeviceGetCount(&nb_devices)) != CUDA_SUCCESS) {
  473. av_log(avctx, AV_LOG_ERROR,
  474. "Cannot enumerate the CUDA devices\n");
  475. return AVERROR_UNKNOWN;
  476. }
  477. if (!nb_devices) {
  478. av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
  479. return AVERROR_EXTERNAL;
  480. }
  481. av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", nb_devices);
  482. dl_fn->nvenc_device_count = 0;
  483. for (i = 0; i < nb_devices; ++i) {
  484. if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
  485. return 0;
  486. }
  487. if (ctx->device == LIST_DEVICES)
  488. return AVERROR_EXIT;
  489. if (!dl_fn->nvenc_device_count) {
  490. av_log(avctx, AV_LOG_FATAL, "No NVENC capable devices found\n");
  491. return AVERROR_EXTERNAL;
  492. }
  493. av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->device, nb_devices);
  494. return AVERROR(EINVAL);
  495. }
  496. return 0;
  497. }
  498. typedef struct GUIDTuple {
  499. const GUID guid;
  500. int flags;
  501. } GUIDTuple;
  502. #define PRESET_ALIAS(alias, name, ...) \
  503. [PRESET_ ## alias] = { NV_ENC_PRESET_ ## name ## _GUID, __VA_ARGS__ }
  504. #define PRESET(name, ...) PRESET_ALIAS(name, name, __VA_ARGS__)
  505. static void nvenc_map_preset(NvencContext *ctx)
  506. {
  507. GUIDTuple presets[] = {
  508. PRESET(DEFAULT),
  509. PRESET(HP),
  510. PRESET(HQ),
  511. PRESET(BD),
  512. PRESET_ALIAS(SLOW, HQ, NVENC_TWO_PASSES),
  513. PRESET_ALIAS(MEDIUM, HQ, NVENC_ONE_PASS),
  514. PRESET_ALIAS(FAST, HP, NVENC_ONE_PASS),
  515. PRESET(LOW_LATENCY_DEFAULT, NVENC_LOWLATENCY),
  516. PRESET(LOW_LATENCY_HP, NVENC_LOWLATENCY),
  517. PRESET(LOW_LATENCY_HQ, NVENC_LOWLATENCY),
  518. PRESET(LOSSLESS_DEFAULT, NVENC_LOSSLESS),
  519. PRESET(LOSSLESS_HP, NVENC_LOSSLESS),
  520. };
  521. GUIDTuple *t = &presets[ctx->preset];
  522. ctx->init_encode_params.presetGUID = t->guid;
  523. ctx->flags = t->flags;
  524. }
  525. #undef PRESET
  526. #undef PRESET_ALIAS
  527. static av_cold void set_constqp(AVCodecContext *avctx)
  528. {
  529. NvencContext *ctx = avctx->priv_data;
  530. NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
  531. rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
  532. if (ctx->init_qp_p >= 0) {
  533. rc->constQP.qpInterP = ctx->init_qp_p;
  534. if (ctx->init_qp_i >= 0 && ctx->init_qp_b >= 0) {
  535. rc->constQP.qpIntra = ctx->init_qp_i;
  536. rc->constQP.qpInterB = ctx->init_qp_b;
  537. } else if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
  538. rc->constQP.qpIntra = av_clip(
  539. rc->constQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
  540. rc->constQP.qpInterB = av_clip(
  541. rc->constQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
  542. } else {
  543. rc->constQP.qpIntra = rc->constQP.qpInterP;
  544. rc->constQP.qpInterB = rc->constQP.qpInterP;
  545. }
  546. } else if (ctx->cqp >= 0) {
  547. rc->constQP.qpInterP = rc->constQP.qpInterB = rc->constQP.qpIntra = ctx->cqp;
  548. if (avctx->b_quant_factor != 0.0)
  549. rc->constQP.qpInterB = av_clip(ctx->cqp * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
  550. if (avctx->i_quant_factor != 0.0)
  551. rc->constQP.qpIntra = av_clip(ctx->cqp * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
  552. }
  553. avctx->qmin = -1;
  554. avctx->qmax = -1;
  555. }
  556. static av_cold void set_vbr(AVCodecContext *avctx)
  557. {
  558. NvencContext *ctx = avctx->priv_data;
  559. NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
  560. int qp_inter_p;
  561. if (avctx->qmin >= 0 && avctx->qmax >= 0) {
  562. rc->enableMinQP = 1;
  563. rc->enableMaxQP = 1;
  564. rc->minQP.qpInterB = avctx->qmin;
  565. rc->minQP.qpInterP = avctx->qmin;
  566. rc->minQP.qpIntra = avctx->qmin;
  567. rc->maxQP.qpInterB = avctx->qmax;
  568. rc->maxQP.qpInterP = avctx->qmax;
  569. rc->maxQP.qpIntra = avctx->qmax;
  570. qp_inter_p = (avctx->qmax + 3 * avctx->qmin) / 4; // biased towards Qmin
  571. } else if (avctx->qmin >= 0) {
  572. rc->enableMinQP = 1;
  573. rc->minQP.qpInterB = avctx->qmin;
  574. rc->minQP.qpInterP = avctx->qmin;
  575. rc->minQP.qpIntra = avctx->qmin;
  576. qp_inter_p = avctx->qmin;
  577. } else {
  578. qp_inter_p = 26; // default to 26
  579. }
  580. rc->enableInitialRCQP = 1;
  581. if (ctx->init_qp_p < 0) {
  582. rc->initialRCQP.qpInterP = qp_inter_p;
  583. } else {
  584. rc->initialRCQP.qpInterP = ctx->init_qp_p;
  585. }
  586. if (ctx->init_qp_i < 0) {
  587. if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
  588. rc->initialRCQP.qpIntra = av_clip(
  589. rc->initialRCQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
  590. } else {
  591. rc->initialRCQP.qpIntra = rc->initialRCQP.qpInterP;
  592. }
  593. } else {
  594. rc->initialRCQP.qpIntra = ctx->init_qp_i;
  595. }
  596. if (ctx->init_qp_b < 0) {
  597. if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
  598. rc->initialRCQP.qpInterB = av_clip(
  599. rc->initialRCQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
  600. } else {
  601. rc->initialRCQP.qpInterB = rc->initialRCQP.qpInterP;
  602. }
  603. } else {
  604. rc->initialRCQP.qpInterB = ctx->init_qp_b;
  605. }
  606. }
  607. static av_cold void set_lossless(AVCodecContext *avctx)
  608. {
  609. NvencContext *ctx = avctx->priv_data;
  610. NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
  611. rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
  612. rc->constQP.qpInterB = 0;
  613. rc->constQP.qpInterP = 0;
  614. rc->constQP.qpIntra = 0;
  615. avctx->qmin = -1;
  616. avctx->qmax = -1;
  617. }
  618. static void nvenc_override_rate_control(AVCodecContext *avctx)
  619. {
  620. NvencContext *ctx = avctx->priv_data;
  621. NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
  622. switch (ctx->rc) {
  623. case NV_ENC_PARAMS_RC_CONSTQP:
  624. set_constqp(avctx);
  625. return;
  626. case NV_ENC_PARAMS_RC_VBR_MINQP:
  627. if (avctx->qmin < 0) {
  628. av_log(avctx, AV_LOG_WARNING,
  629. "The variable bitrate rate-control requires "
  630. "the 'qmin' option set.\n");
  631. set_vbr(avctx);
  632. return;
  633. }
  634. /* fall through */
  635. case NV_ENC_PARAMS_RC_VBR_HQ:
  636. case NV_ENC_PARAMS_RC_VBR:
  637. set_vbr(avctx);
  638. break;
  639. case NV_ENC_PARAMS_RC_CBR:
  640. case NV_ENC_PARAMS_RC_CBR_HQ:
  641. case NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ:
  642. break;
  643. }
  644. rc->rateControlMode = ctx->rc;
  645. }
  646. static av_cold int nvenc_recalc_surfaces(AVCodecContext *avctx)
  647. {
  648. NvencContext *ctx = avctx->priv_data;
  649. // default minimum of 4 surfaces
  650. // multiply by 2 for number of NVENCs on gpu (hardcode to 2)
  651. // another multiply by 2 to avoid blocking next PBB group
  652. int nb_surfaces = FFMAX(4, ctx->encode_config.frameIntervalP * 2 * 2);
  653. // lookahead enabled
  654. if (ctx->rc_lookahead > 0) {
  655. // +1 is to account for lkd_bound calculation later
  656. // +4 is to allow sufficient pipelining with lookahead
  657. nb_surfaces = FFMAX(1, FFMAX(nb_surfaces, ctx->rc_lookahead + ctx->encode_config.frameIntervalP + 1 + 4));
  658. if (nb_surfaces > ctx->nb_surfaces && ctx->nb_surfaces > 0)
  659. {
  660. av_log(avctx, AV_LOG_WARNING,
  661. "Defined rc_lookahead requires more surfaces, "
  662. "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
  663. }
  664. ctx->nb_surfaces = FFMAX(nb_surfaces, ctx->nb_surfaces);
  665. } else {
  666. if (ctx->encode_config.frameIntervalP > 1 && ctx->nb_surfaces < nb_surfaces && ctx->nb_surfaces > 0)
  667. {
  668. av_log(avctx, AV_LOG_WARNING,
  669. "Defined b-frame requires more surfaces, "
  670. "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
  671. ctx->nb_surfaces = FFMAX(ctx->nb_surfaces, nb_surfaces);
  672. }
  673. else if (ctx->nb_surfaces <= 0)
  674. ctx->nb_surfaces = nb_surfaces;
  675. // otherwise use user specified value
  676. }
  677. ctx->nb_surfaces = FFMAX(1, FFMIN(MAX_REGISTERED_FRAMES, ctx->nb_surfaces));
  678. ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
  679. return 0;
  680. }
  681. static av_cold void nvenc_setup_rate_control(AVCodecContext *avctx)
  682. {
  683. NvencContext *ctx = avctx->priv_data;
  684. if (avctx->global_quality > 0)
  685. av_log(avctx, AV_LOG_WARNING, "Using global_quality with nvenc is deprecated. Use qp instead.\n");
  686. if (ctx->cqp < 0 && avctx->global_quality > 0)
  687. ctx->cqp = avctx->global_quality;
  688. if (avctx->bit_rate > 0) {
  689. ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
  690. } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
  691. ctx->encode_config.rcParams.maxBitRate = ctx->encode_config.rcParams.averageBitRate;
  692. }
  693. if (avctx->rc_max_rate > 0)
  694. ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
  695. if (ctx->rc < 0) {
  696. if (ctx->flags & NVENC_ONE_PASS)
  697. ctx->twopass = 0;
  698. if (ctx->flags & NVENC_TWO_PASSES)
  699. ctx->twopass = 1;
  700. if (ctx->twopass < 0)
  701. ctx->twopass = (ctx->flags & NVENC_LOWLATENCY) != 0;
  702. if (ctx->cbr) {
  703. if (ctx->twopass) {
  704. ctx->rc = NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ;
  705. } else {
  706. ctx->rc = NV_ENC_PARAMS_RC_CBR;
  707. }
  708. } else if (ctx->cqp >= 0) {
  709. ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
  710. } else if (ctx->twopass) {
  711. ctx->rc = NV_ENC_PARAMS_RC_VBR_HQ;
  712. } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
  713. ctx->rc = NV_ENC_PARAMS_RC_VBR_MINQP;
  714. }
  715. }
  716. if (ctx->rc >= 0 && ctx->rc & RC_MODE_DEPRECATED) {
  717. av_log(avctx, AV_LOG_WARNING, "Specified rc mode is deprecated.\n");
  718. av_log(avctx, AV_LOG_WARNING, "\tll_2pass_quality -> cbr_ld_hq\n");
  719. av_log(avctx, AV_LOG_WARNING, "\tll_2pass_size -> cbr_hq\n");
  720. av_log(avctx, AV_LOG_WARNING, "\tvbr_2pass -> vbr_hq\n");
  721. av_log(avctx, AV_LOG_WARNING, "\tvbr_minqp -> (no replacement)\n");
  722. ctx->rc &= ~RC_MODE_DEPRECATED;
  723. }
  724. if (ctx->flags & NVENC_LOSSLESS) {
  725. set_lossless(avctx);
  726. } else if (ctx->rc >= 0) {
  727. nvenc_override_rate_control(avctx);
  728. } else {
  729. ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
  730. set_vbr(avctx);
  731. }
  732. if (avctx->rc_buffer_size > 0) {
  733. ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
  734. } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
  735. ctx->encode_config.rcParams.vbvBufferSize = 2 * ctx->encode_config.rcParams.averageBitRate;
  736. }
  737. if (ctx->aq) {
  738. ctx->encode_config.rcParams.enableAQ = 1;
  739. ctx->encode_config.rcParams.aqStrength = ctx->aq_strength;
  740. av_log(avctx, AV_LOG_VERBOSE, "AQ enabled.\n");
  741. }
  742. if (ctx->temporal_aq) {
  743. ctx->encode_config.rcParams.enableTemporalAQ = 1;
  744. av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ enabled.\n");
  745. }
  746. if (ctx->rc_lookahead > 0) {
  747. int lkd_bound = FFMIN(ctx->nb_surfaces, ctx->async_depth) -
  748. ctx->encode_config.frameIntervalP - 4;
  749. if (lkd_bound < 0) {
  750. av_log(avctx, AV_LOG_WARNING,
  751. "Lookahead not enabled. Increase buffer delay (-delay).\n");
  752. } else {
  753. ctx->encode_config.rcParams.enableLookahead = 1;
  754. ctx->encode_config.rcParams.lookaheadDepth = av_clip(ctx->rc_lookahead, 0, lkd_bound);
  755. ctx->encode_config.rcParams.disableIadapt = ctx->no_scenecut;
  756. ctx->encode_config.rcParams.disableBadapt = !ctx->b_adapt;
  757. av_log(avctx, AV_LOG_VERBOSE,
  758. "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",
  759. ctx->encode_config.rcParams.lookaheadDepth,
  760. ctx->encode_config.rcParams.disableIadapt ? "disabled" : "enabled",
  761. ctx->encode_config.rcParams.disableBadapt ? "disabled" : "enabled");
  762. }
  763. }
  764. if (ctx->strict_gop) {
  765. ctx->encode_config.rcParams.strictGOPTarget = 1;
  766. av_log(avctx, AV_LOG_VERBOSE, "Strict GOP target enabled.\n");
  767. }
  768. if (ctx->nonref_p)
  769. ctx->encode_config.rcParams.enableNonRefP = 1;
  770. if (ctx->zerolatency)
  771. ctx->encode_config.rcParams.zeroReorderDelay = 1;
  772. if (ctx->quality)
  773. {
  774. //convert from float to fixed point 8.8
  775. int tmp_quality = (int)(ctx->quality * 256.0f);
  776. ctx->encode_config.rcParams.targetQuality = (uint8_t)(tmp_quality >> 8);
  777. ctx->encode_config.rcParams.targetQualityLSB = (uint8_t)(tmp_quality & 0xff);
  778. }
  779. }
  780. static av_cold int nvenc_setup_h264_config(AVCodecContext *avctx)
  781. {
  782. NvencContext *ctx = avctx->priv_data;
  783. NV_ENC_CONFIG *cc = &ctx->encode_config;
  784. NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
  785. NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
  786. vui->colourMatrix = avctx->colorspace;
  787. vui->colourPrimaries = avctx->color_primaries;
  788. vui->transferCharacteristics = avctx->color_trc;
  789. vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
  790. || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
  791. vui->colourDescriptionPresentFlag =
  792. (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
  793. vui->videoSignalTypePresentFlag =
  794. (vui->colourDescriptionPresentFlag
  795. || vui->videoFormat != 5
  796. || vui->videoFullRangeFlag != 0);
  797. h264->sliceMode = 3;
  798. h264->sliceModeData = 1;
  799. h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
  800. h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
  801. h264->outputAUD = ctx->aud;
  802. if (avctx->refs >= 0) {
  803. /* 0 means "let the hardware decide" */
  804. h264->maxNumRefFrames = avctx->refs;
  805. }
  806. if (avctx->gop_size >= 0) {
  807. h264->idrPeriod = cc->gopLength;
  808. }
  809. if (IS_CBR(cc->rcParams.rateControlMode)) {
  810. h264->outputBufferingPeriodSEI = 1;
  811. }
  812. h264->outputPictureTimingSEI = 1;
  813. if (cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ ||
  814. cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_HQ ||
  815. cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_VBR_HQ) {
  816. h264->adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
  817. h264->fmoMode = NV_ENC_H264_FMO_DISABLE;
  818. }
  819. if (ctx->flags & NVENC_LOSSLESS) {
  820. h264->qpPrimeYZeroTransformBypassFlag = 1;
  821. } else {
  822. switch(ctx->profile) {
  823. case NV_ENC_H264_PROFILE_BASELINE:
  824. cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
  825. avctx->profile = FF_PROFILE_H264_BASELINE;
  826. break;
  827. case NV_ENC_H264_PROFILE_MAIN:
  828. cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
  829. avctx->profile = FF_PROFILE_H264_MAIN;
  830. break;
  831. case NV_ENC_H264_PROFILE_HIGH:
  832. cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
  833. avctx->profile = FF_PROFILE_H264_HIGH;
  834. break;
  835. case NV_ENC_H264_PROFILE_HIGH_444P:
  836. cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
  837. avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
  838. break;
  839. }
  840. }
  841. // force setting profile as high444p if input is AV_PIX_FMT_YUV444P
  842. if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P) {
  843. cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
  844. avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
  845. }
  846. h264->chromaFormatIDC = avctx->profile == FF_PROFILE_H264_HIGH_444_PREDICTIVE ? 3 : 1;
  847. h264->level = ctx->level;
  848. if (ctx->coder >= 0)
  849. h264->entropyCodingMode = ctx->coder;
  850. #ifdef NVENC_HAVE_BFRAME_REF_MODE
  851. h264->useBFramesAsRef = ctx->b_ref_mode;
  852. #endif
  853. return 0;
  854. }
  855. static av_cold int nvenc_setup_hevc_config(AVCodecContext *avctx)
  856. {
  857. NvencContext *ctx = avctx->priv_data;
  858. NV_ENC_CONFIG *cc = &ctx->encode_config;
  859. NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
  860. NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
  861. vui->colourMatrix = avctx->colorspace;
  862. vui->colourPrimaries = avctx->color_primaries;
  863. vui->transferCharacteristics = avctx->color_trc;
  864. vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
  865. || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
  866. vui->colourDescriptionPresentFlag =
  867. (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
  868. vui->videoSignalTypePresentFlag =
  869. (vui->colourDescriptionPresentFlag
  870. || vui->videoFormat != 5
  871. || vui->videoFullRangeFlag != 0);
  872. hevc->sliceMode = 3;
  873. hevc->sliceModeData = 1;
  874. hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
  875. hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
  876. hevc->outputAUD = ctx->aud;
  877. if (avctx->refs >= 0) {
  878. /* 0 means "let the hardware decide" */
  879. hevc->maxNumRefFramesInDPB = avctx->refs;
  880. }
  881. if (avctx->gop_size >= 0) {
  882. hevc->idrPeriod = cc->gopLength;
  883. }
  884. if (IS_CBR(cc->rcParams.rateControlMode)) {
  885. hevc->outputBufferingPeriodSEI = 1;
  886. }
  887. hevc->outputPictureTimingSEI = 1;
  888. switch (ctx->profile) {
  889. case NV_ENC_HEVC_PROFILE_MAIN:
  890. cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
  891. avctx->profile = FF_PROFILE_HEVC_MAIN;
  892. break;
  893. case NV_ENC_HEVC_PROFILE_MAIN_10:
  894. cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
  895. avctx->profile = FF_PROFILE_HEVC_MAIN_10;
  896. break;
  897. case NV_ENC_HEVC_PROFILE_REXT:
  898. cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
  899. avctx->profile = FF_PROFILE_HEVC_REXT;
  900. break;
  901. }
  902. // force setting profile as main10 if input is 10 bit
  903. if (IS_10BIT(ctx->data_pix_fmt)) {
  904. cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
  905. avctx->profile = FF_PROFILE_HEVC_MAIN_10;
  906. }
  907. // force setting profile as rext if input is yuv444
  908. if (IS_YUV444(ctx->data_pix_fmt)) {
  909. cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
  910. avctx->profile = FF_PROFILE_HEVC_REXT;
  911. }
  912. hevc->chromaFormatIDC = IS_YUV444(ctx->data_pix_fmt) ? 3 : 1;
  913. hevc->pixelBitDepthMinus8 = IS_10BIT(ctx->data_pix_fmt) ? 2 : 0;
  914. hevc->level = ctx->level;
  915. hevc->tier = ctx->tier;
  916. return 0;
  917. }
  918. static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx)
  919. {
  920. switch (avctx->codec->id) {
  921. case AV_CODEC_ID_H264:
  922. return nvenc_setup_h264_config(avctx);
  923. case AV_CODEC_ID_HEVC:
  924. return nvenc_setup_hevc_config(avctx);
  925. /* Earlier switch/case will return if unknown codec is passed. */
  926. }
  927. return 0;
  928. }
  929. static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
  930. {
  931. NvencContext *ctx = avctx->priv_data;
  932. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  933. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  934. NV_ENC_PRESET_CONFIG preset_config = { 0 };
  935. NVENCSTATUS nv_status = NV_ENC_SUCCESS;
  936. AVCPBProperties *cpb_props;
  937. int res = 0;
  938. int dw, dh;
  939. ctx->encode_config.version = NV_ENC_CONFIG_VER;
  940. ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
  941. ctx->init_encode_params.encodeHeight = avctx->height;
  942. ctx->init_encode_params.encodeWidth = avctx->width;
  943. ctx->init_encode_params.encodeConfig = &ctx->encode_config;
  944. nvenc_map_preset(ctx);
  945. preset_config.version = NV_ENC_PRESET_CONFIG_VER;
  946. preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
  947. nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder,
  948. ctx->init_encode_params.encodeGUID,
  949. ctx->init_encode_params.presetGUID,
  950. &preset_config);
  951. if (nv_status != NV_ENC_SUCCESS)
  952. return nvenc_print_error(avctx, nv_status, "Cannot get the preset configuration");
  953. memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
  954. ctx->encode_config.version = NV_ENC_CONFIG_VER;
  955. dw = avctx->width;
  956. dh = avctx->height;
  957. if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0) {
  958. dw*= avctx->sample_aspect_ratio.num;
  959. dh*= avctx->sample_aspect_ratio.den;
  960. }
  961. av_reduce(&dw, &dh, dw, dh, 1024 * 1024);
  962. ctx->init_encode_params.darHeight = dh;
  963. ctx->init_encode_params.darWidth = dw;
  964. ctx->init_encode_params.frameRateNum = avctx->time_base.den;
  965. ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
  966. ctx->init_encode_params.enableEncodeAsync = 0;
  967. ctx->init_encode_params.enablePTD = 1;
  968. if (ctx->weighted_pred == 1)
  969. ctx->init_encode_params.enableWeightedPrediction = 1;
  970. if (ctx->bluray_compat) {
  971. ctx->aud = 1;
  972. avctx->refs = FFMIN(FFMAX(avctx->refs, 0), 6);
  973. avctx->max_b_frames = FFMIN(avctx->max_b_frames, 3);
  974. switch (avctx->codec->id) {
  975. case AV_CODEC_ID_H264:
  976. /* maximum level depends on used resolution */
  977. break;
  978. case AV_CODEC_ID_HEVC:
  979. ctx->level = NV_ENC_LEVEL_HEVC_51;
  980. ctx->tier = NV_ENC_TIER_HEVC_HIGH;
  981. break;
  982. }
  983. }
  984. if (avctx->gop_size > 0) {
  985. if (avctx->max_b_frames >= 0) {
  986. /* 0 is intra-only, 1 is I/P only, 2 is one B-Frame, 3 two B-frames, and so on. */
  987. ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
  988. }
  989. ctx->encode_config.gopLength = avctx->gop_size;
  990. } else if (avctx->gop_size == 0) {
  991. ctx->encode_config.frameIntervalP = 0;
  992. ctx->encode_config.gopLength = 1;
  993. }
  994. ctx->initial_pts[0] = AV_NOPTS_VALUE;
  995. ctx->initial_pts[1] = AV_NOPTS_VALUE;
  996. nvenc_recalc_surfaces(avctx);
  997. nvenc_setup_rate_control(avctx);
  998. if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
  999. ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
  1000. } else {
  1001. ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
  1002. }
  1003. res = nvenc_setup_codec_config(avctx);
  1004. if (res)
  1005. return res;
  1006. res = nvenc_push_context(avctx);
  1007. if (res < 0)
  1008. return res;
  1009. nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
  1010. res = nvenc_pop_context(avctx);
  1011. if (res < 0)
  1012. return res;
  1013. if (nv_status != NV_ENC_SUCCESS) {
  1014. return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
  1015. }
  1016. if (ctx->encode_config.frameIntervalP > 1)
  1017. avctx->has_b_frames = 2;
  1018. if (ctx->encode_config.rcParams.averageBitRate > 0)
  1019. avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
  1020. cpb_props = ff_add_cpb_side_data(avctx);
  1021. if (!cpb_props)
  1022. return AVERROR(ENOMEM);
  1023. cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
  1024. cpb_props->avg_bitrate = avctx->bit_rate;
  1025. cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
  1026. return 0;
  1027. }
  1028. static NV_ENC_BUFFER_FORMAT nvenc_map_buffer_format(enum AVPixelFormat pix_fmt)
  1029. {
  1030. switch (pix_fmt) {
  1031. case AV_PIX_FMT_YUV420P:
  1032. return NV_ENC_BUFFER_FORMAT_YV12_PL;
  1033. case AV_PIX_FMT_NV12:
  1034. return NV_ENC_BUFFER_FORMAT_NV12_PL;
  1035. case AV_PIX_FMT_P010:
  1036. case AV_PIX_FMT_P016:
  1037. return NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
  1038. case AV_PIX_FMT_YUV444P:
  1039. return NV_ENC_BUFFER_FORMAT_YUV444_PL;
  1040. case AV_PIX_FMT_YUV444P16:
  1041. return NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
  1042. case AV_PIX_FMT_0RGB32:
  1043. return NV_ENC_BUFFER_FORMAT_ARGB;
  1044. case AV_PIX_FMT_0BGR32:
  1045. return NV_ENC_BUFFER_FORMAT_ABGR;
  1046. default:
  1047. return NV_ENC_BUFFER_FORMAT_UNDEFINED;
  1048. }
  1049. }
  1050. static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
  1051. {
  1052. NvencContext *ctx = avctx->priv_data;
  1053. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  1054. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  1055. NvencSurface* tmp_surface = &ctx->surfaces[idx];
  1056. NVENCSTATUS nv_status;
  1057. NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
  1058. allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
  1059. if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
  1060. ctx->surfaces[idx].in_ref = av_frame_alloc();
  1061. if (!ctx->surfaces[idx].in_ref)
  1062. return AVERROR(ENOMEM);
  1063. } else {
  1064. NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
  1065. ctx->surfaces[idx].format = nvenc_map_buffer_format(ctx->data_pix_fmt);
  1066. if (ctx->surfaces[idx].format == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
  1067. av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
  1068. av_get_pix_fmt_name(ctx->data_pix_fmt));
  1069. return AVERROR(EINVAL);
  1070. }
  1071. allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
  1072. allocSurf.width = avctx->width;
  1073. allocSurf.height = avctx->height;
  1074. allocSurf.bufferFmt = ctx->surfaces[idx].format;
  1075. nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
  1076. if (nv_status != NV_ENC_SUCCESS) {
  1077. return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
  1078. }
  1079. ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
  1080. ctx->surfaces[idx].width = allocSurf.width;
  1081. ctx->surfaces[idx].height = allocSurf.height;
  1082. }
  1083. nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
  1084. if (nv_status != NV_ENC_SUCCESS) {
  1085. int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
  1086. if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
  1087. p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
  1088. av_frame_free(&ctx->surfaces[idx].in_ref);
  1089. return err;
  1090. }
  1091. ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
  1092. ctx->surfaces[idx].size = allocOut.size;
  1093. av_fifo_generic_write(ctx->unused_surface_queue, &tmp_surface, sizeof(tmp_surface), NULL);
  1094. return 0;
  1095. }
  1096. static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx)
  1097. {
  1098. NvencContext *ctx = avctx->priv_data;
  1099. int i, res = 0, res2;
  1100. ctx->surfaces = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->surfaces));
  1101. if (!ctx->surfaces)
  1102. return AVERROR(ENOMEM);
  1103. ctx->timestamp_list = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
  1104. if (!ctx->timestamp_list)
  1105. return AVERROR(ENOMEM);
  1106. ctx->unused_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
  1107. if (!ctx->unused_surface_queue)
  1108. return AVERROR(ENOMEM);
  1109. ctx->output_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
  1110. if (!ctx->output_surface_queue)
  1111. return AVERROR(ENOMEM);
  1112. ctx->output_surface_ready_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
  1113. if (!ctx->output_surface_ready_queue)
  1114. return AVERROR(ENOMEM);
  1115. res = nvenc_push_context(avctx);
  1116. if (res < 0)
  1117. return res;
  1118. for (i = 0; i < ctx->nb_surfaces; i++) {
  1119. if ((res = nvenc_alloc_surface(avctx, i)) < 0)
  1120. goto fail;
  1121. }
  1122. fail:
  1123. res2 = nvenc_pop_context(avctx);
  1124. if (res2 < 0)
  1125. return res2;
  1126. return res;
  1127. }
  1128. static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
  1129. {
  1130. NvencContext *ctx = avctx->priv_data;
  1131. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  1132. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  1133. NVENCSTATUS nv_status;
  1134. uint32_t outSize = 0;
  1135. char tmpHeader[256];
  1136. NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
  1137. payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
  1138. payload.spsppsBuffer = tmpHeader;
  1139. payload.inBufferSize = sizeof(tmpHeader);
  1140. payload.outSPSPPSPayloadSize = &outSize;
  1141. nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
  1142. if (nv_status != NV_ENC_SUCCESS) {
  1143. return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
  1144. }
  1145. avctx->extradata_size = outSize;
  1146. avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
  1147. if (!avctx->extradata) {
  1148. return AVERROR(ENOMEM);
  1149. }
  1150. memcpy(avctx->extradata, tmpHeader, outSize);
  1151. return 0;
  1152. }
  1153. av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
  1154. {
  1155. NvencContext *ctx = avctx->priv_data;
  1156. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  1157. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  1158. int i, res;
  1159. /* the encoder has to be flushed before it can be closed */
  1160. if (ctx->nvencoder) {
  1161. NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
  1162. .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
  1163. res = nvenc_push_context(avctx);
  1164. if (res < 0)
  1165. return res;
  1166. p_nvenc->nvEncEncodePicture(ctx->nvencoder, &params);
  1167. }
  1168. av_fifo_freep(&ctx->timestamp_list);
  1169. av_fifo_freep(&ctx->output_surface_ready_queue);
  1170. av_fifo_freep(&ctx->output_surface_queue);
  1171. av_fifo_freep(&ctx->unused_surface_queue);
  1172. if (ctx->surfaces && (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11)) {
  1173. for (i = 0; i < ctx->nb_registered_frames; i++) {
  1174. if (ctx->registered_frames[i].mapped)
  1175. p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[i].in_map.mappedResource);
  1176. if (ctx->registered_frames[i].regptr)
  1177. p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
  1178. }
  1179. ctx->nb_registered_frames = 0;
  1180. }
  1181. if (ctx->surfaces) {
  1182. for (i = 0; i < ctx->nb_surfaces; ++i) {
  1183. if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
  1184. p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
  1185. av_frame_free(&ctx->surfaces[i].in_ref);
  1186. p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
  1187. }
  1188. }
  1189. av_freep(&ctx->surfaces);
  1190. ctx->nb_surfaces = 0;
  1191. if (ctx->nvencoder) {
  1192. p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
  1193. res = nvenc_pop_context(avctx);
  1194. if (res < 0)
  1195. return res;
  1196. }
  1197. ctx->nvencoder = NULL;
  1198. if (ctx->cu_context_internal)
  1199. dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal);
  1200. ctx->cu_context = ctx->cu_context_internal = NULL;
  1201. #if CONFIG_D3D11VA
  1202. if (ctx->d3d11_device) {
  1203. ID3D11Device_Release(ctx->d3d11_device);
  1204. ctx->d3d11_device = NULL;
  1205. }
  1206. #endif
  1207. nvenc_free_functions(&dl_fn->nvenc_dl);
  1208. cuda_free_functions(&dl_fn->cuda_dl);
  1209. dl_fn->nvenc_device_count = 0;
  1210. av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
  1211. return 0;
  1212. }
  1213. av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
  1214. {
  1215. NvencContext *ctx = avctx->priv_data;
  1216. int ret;
  1217. if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
  1218. if (avctx->hw_frames_ctx) {
  1219. AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  1220. if (frames_ctx->format != avctx->pix_fmt) {
  1221. av_log(avctx, AV_LOG_ERROR,
  1222. "hw_frames_ctx must match the GPU frame type\n");
  1223. return AVERROR(EINVAL);
  1224. }
  1225. ctx->data_pix_fmt = frames_ctx->sw_format;
  1226. } else if (avctx->sw_pix_fmt && avctx->sw_pix_fmt != AV_PIX_FMT_NONE) {
  1227. ctx->data_pix_fmt = avctx->sw_pix_fmt;
  1228. } else {
  1229. av_log(avctx, AV_LOG_ERROR,
  1230. "either hw_frames_ctx or sw_pix_fmt is required for hw frame input\n");
  1231. return AVERROR(EINVAL);
  1232. }
  1233. } else {
  1234. ctx->data_pix_fmt = avctx->pix_fmt;
  1235. }
  1236. if ((ret = nvenc_load_libraries(avctx)) < 0)
  1237. return ret;
  1238. if ((ret = nvenc_setup_device(avctx)) < 0)
  1239. return ret;
  1240. if ((ret = nvenc_setup_encoder(avctx)) < 0)
  1241. return ret;
  1242. if ((ret = nvenc_setup_surfaces(avctx)) < 0)
  1243. return ret;
  1244. if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
  1245. if ((ret = nvenc_setup_extradata(avctx)) < 0)
  1246. return ret;
  1247. }
  1248. return 0;
  1249. }
  1250. static NvencSurface *get_free_frame(NvencContext *ctx)
  1251. {
  1252. NvencSurface *tmp_surf;
  1253. if (!(av_fifo_size(ctx->unused_surface_queue) > 0))
  1254. // queue empty
  1255. return NULL;
  1256. av_fifo_generic_read(ctx->unused_surface_queue, &tmp_surf, sizeof(tmp_surf), NULL);
  1257. return tmp_surf;
  1258. }
  1259. static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *nv_surface,
  1260. NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params, const AVFrame *frame)
  1261. {
  1262. int dst_linesize[4] = {
  1263. lock_buffer_params->pitch,
  1264. lock_buffer_params->pitch,
  1265. lock_buffer_params->pitch,
  1266. lock_buffer_params->pitch
  1267. };
  1268. uint8_t *dst_data[4];
  1269. int ret;
  1270. if (frame->format == AV_PIX_FMT_YUV420P)
  1271. dst_linesize[1] = dst_linesize[2] >>= 1;
  1272. ret = av_image_fill_pointers(dst_data, frame->format, nv_surface->height,
  1273. lock_buffer_params->bufferDataPtr, dst_linesize);
  1274. if (ret < 0)
  1275. return ret;
  1276. if (frame->format == AV_PIX_FMT_YUV420P)
  1277. FFSWAP(uint8_t*, dst_data[1], dst_data[2]);
  1278. av_image_copy(dst_data, dst_linesize,
  1279. (const uint8_t**)frame->data, frame->linesize, frame->format,
  1280. avctx->width, avctx->height);
  1281. return 0;
  1282. }
  1283. static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
  1284. {
  1285. NvencContext *ctx = avctx->priv_data;
  1286. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  1287. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  1288. NVENCSTATUS nv_status;
  1289. int i;
  1290. if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
  1291. for (i = 0; i < ctx->nb_registered_frames; i++) {
  1292. if (!ctx->registered_frames[i].mapped) {
  1293. if (ctx->registered_frames[i].regptr) {
  1294. nv_status = p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
  1295. if (nv_status != NV_ENC_SUCCESS)
  1296. return nvenc_print_error(avctx, nv_status, "Failed unregistering unused input resource");
  1297. ctx->registered_frames[i].ptr = NULL;
  1298. ctx->registered_frames[i].regptr = NULL;
  1299. }
  1300. return i;
  1301. }
  1302. }
  1303. } else {
  1304. return ctx->nb_registered_frames++;
  1305. }
  1306. av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
  1307. return AVERROR(ENOMEM);
  1308. }
  1309. static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
  1310. {
  1311. NvencContext *ctx = avctx->priv_data;
  1312. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  1313. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  1314. enum AVPixelFormat sw_format = ctx->data_pix_fmt;
  1315. NV_ENC_REGISTER_RESOURCE reg;
  1316. int i, idx, ret;
  1317. if (frame->hw_frames_ctx) {
  1318. AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frame->hw_frames_ctx->data;
  1319. sw_format = frames_ctx->sw_format;
  1320. }
  1321. for (i = 0; i < ctx->nb_registered_frames; i++) {
  1322. if (avctx->pix_fmt == AV_PIX_FMT_CUDA && ctx->registered_frames[i].ptr == frame->data[0])
  1323. return i;
  1324. else if (avctx->pix_fmt == AV_PIX_FMT_D3D11 && ctx->registered_frames[i].ptr == frame->data[0] && ctx->registered_frames[i].ptr_index == (intptr_t)frame->data[1])
  1325. return i;
  1326. }
  1327. idx = nvenc_find_free_reg_resource(avctx);
  1328. if (idx < 0)
  1329. return idx;
  1330. reg.version = NV_ENC_REGISTER_RESOURCE_VER;
  1331. reg.width = frame->width;
  1332. reg.height = frame->height;
  1333. reg.pitch = frame->linesize[0];
  1334. reg.resourceToRegister = frame->data[0];
  1335. if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
  1336. reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
  1337. }
  1338. else if (avctx->pix_fmt == AV_PIX_FMT_D3D11) {
  1339. reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX;
  1340. reg.subResourceIndex = (intptr_t)frame->data[1];
  1341. }
  1342. reg.bufferFormat = nvenc_map_buffer_format(sw_format);
  1343. if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
  1344. av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
  1345. av_get_pix_fmt_name(sw_format));
  1346. return AVERROR(EINVAL);
  1347. }
  1348. ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, &reg);
  1349. if (ret != NV_ENC_SUCCESS) {
  1350. nvenc_print_error(avctx, ret, "Error registering an input resource");
  1351. return AVERROR_UNKNOWN;
  1352. }
  1353. ctx->registered_frames[idx].ptr = frame->data[0];
  1354. ctx->registered_frames[idx].ptr_index = reg.subResourceIndex;
  1355. ctx->registered_frames[idx].regptr = reg.registeredResource;
  1356. return idx;
  1357. }
  1358. static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
  1359. NvencSurface *nvenc_frame)
  1360. {
  1361. NvencContext *ctx = avctx->priv_data;
  1362. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  1363. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  1364. int res;
  1365. NVENCSTATUS nv_status;
  1366. if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
  1367. int reg_idx = nvenc_register_frame(avctx, frame);
  1368. if (reg_idx < 0) {
  1369. av_log(avctx, AV_LOG_ERROR, "Could not register an input HW frame\n");
  1370. return reg_idx;
  1371. }
  1372. res = av_frame_ref(nvenc_frame->in_ref, frame);
  1373. if (res < 0)
  1374. return res;
  1375. if (!ctx->registered_frames[reg_idx].mapped) {
  1376. ctx->registered_frames[reg_idx].in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
  1377. ctx->registered_frames[reg_idx].in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
  1378. nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &ctx->registered_frames[reg_idx].in_map);
  1379. if (nv_status != NV_ENC_SUCCESS) {
  1380. av_frame_unref(nvenc_frame->in_ref);
  1381. return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
  1382. }
  1383. }
  1384. ctx->registered_frames[reg_idx].mapped += 1;
  1385. nvenc_frame->reg_idx = reg_idx;
  1386. nvenc_frame->input_surface = ctx->registered_frames[reg_idx].in_map.mappedResource;
  1387. nvenc_frame->format = ctx->registered_frames[reg_idx].in_map.mappedBufferFmt;
  1388. nvenc_frame->pitch = frame->linesize[0];
  1389. return 0;
  1390. } else {
  1391. NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
  1392. lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
  1393. lockBufferParams.inputBuffer = nvenc_frame->input_surface;
  1394. nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
  1395. if (nv_status != NV_ENC_SUCCESS) {
  1396. return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
  1397. }
  1398. nvenc_frame->pitch = lockBufferParams.pitch;
  1399. res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
  1400. nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
  1401. if (nv_status != NV_ENC_SUCCESS) {
  1402. return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
  1403. }
  1404. return res;
  1405. }
  1406. }
  1407. static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
  1408. NV_ENC_PIC_PARAMS *params)
  1409. {
  1410. NvencContext *ctx = avctx->priv_data;
  1411. switch (avctx->codec->id) {
  1412. case AV_CODEC_ID_H264:
  1413. params->codecPicParams.h264PicParams.sliceMode =
  1414. ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
  1415. params->codecPicParams.h264PicParams.sliceModeData =
  1416. ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
  1417. break;
  1418. case AV_CODEC_ID_HEVC:
  1419. params->codecPicParams.hevcPicParams.sliceMode =
  1420. ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
  1421. params->codecPicParams.hevcPicParams.sliceModeData =
  1422. ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
  1423. break;
  1424. }
  1425. }
  1426. static inline void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
  1427. {
  1428. av_fifo_generic_write(queue, &timestamp, sizeof(timestamp), NULL);
  1429. }
  1430. static inline int64_t timestamp_queue_dequeue(AVFifoBuffer* queue)
  1431. {
  1432. int64_t timestamp = AV_NOPTS_VALUE;
  1433. if (av_fifo_size(queue) > 0)
  1434. av_fifo_generic_read(queue, &timestamp, sizeof(timestamp), NULL);
  1435. return timestamp;
  1436. }
  1437. static int nvenc_set_timestamp(AVCodecContext *avctx,
  1438. NV_ENC_LOCK_BITSTREAM *params,
  1439. AVPacket *pkt)
  1440. {
  1441. NvencContext *ctx = avctx->priv_data;
  1442. pkt->pts = params->outputTimeStamp;
  1443. /* generate the first dts by linearly extrapolating the
  1444. * first two pts values to the past */
  1445. if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
  1446. ctx->initial_pts[1] != AV_NOPTS_VALUE) {
  1447. int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
  1448. int64_t delta;
  1449. if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
  1450. (ts0 > 0 && ts1 < INT64_MIN + ts0))
  1451. return AVERROR(ERANGE);
  1452. delta = ts1 - ts0;
  1453. if ((delta < 0 && ts0 > INT64_MAX + delta) ||
  1454. (delta > 0 && ts0 < INT64_MIN + delta))
  1455. return AVERROR(ERANGE);
  1456. pkt->dts = ts0 - delta;
  1457. ctx->first_packet_output = 1;
  1458. return 0;
  1459. }
  1460. pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
  1461. return 0;
  1462. }
  1463. static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
  1464. {
  1465. NvencContext *ctx = avctx->priv_data;
  1466. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  1467. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  1468. uint32_t slice_mode_data;
  1469. uint32_t *slice_offsets = NULL;
  1470. NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
  1471. NVENCSTATUS nv_status;
  1472. int res = 0;
  1473. enum AVPictureType pict_type;
  1474. switch (avctx->codec->id) {
  1475. case AV_CODEC_ID_H264:
  1476. slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
  1477. break;
  1478. case AV_CODEC_ID_H265:
  1479. slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
  1480. break;
  1481. default:
  1482. av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
  1483. res = AVERROR(EINVAL);
  1484. goto error;
  1485. }
  1486. slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
  1487. if (!slice_offsets) {
  1488. res = AVERROR(ENOMEM);
  1489. goto error;
  1490. }
  1491. lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
  1492. lock_params.doNotWait = 0;
  1493. lock_params.outputBitstream = tmpoutsurf->output_surface;
  1494. lock_params.sliceOffsets = slice_offsets;
  1495. nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
  1496. if (nv_status != NV_ENC_SUCCESS) {
  1497. res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
  1498. goto error;
  1499. }
  1500. if (res = ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes,0)) {
  1501. p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
  1502. goto error;
  1503. }
  1504. memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
  1505. nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
  1506. if (nv_status != NV_ENC_SUCCESS) {
  1507. res = nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
  1508. goto error;
  1509. }
  1510. if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
  1511. ctx->registered_frames[tmpoutsurf->reg_idx].mapped -= 1;
  1512. if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped == 0) {
  1513. nv_status = p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[tmpoutsurf->reg_idx].in_map.mappedResource);
  1514. if (nv_status != NV_ENC_SUCCESS) {
  1515. res = nvenc_print_error(avctx, nv_status, "Failed unmapping input resource");
  1516. goto error;
  1517. }
  1518. nv_status = p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[tmpoutsurf->reg_idx].regptr);
  1519. if (nv_status != NV_ENC_SUCCESS) {
  1520. res = nvenc_print_error(avctx, nv_status, "Failed unregistering input resource");
  1521. goto error;
  1522. }
  1523. ctx->registered_frames[tmpoutsurf->reg_idx].ptr = NULL;
  1524. ctx->registered_frames[tmpoutsurf->reg_idx].regptr = NULL;
  1525. } else if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped < 0) {
  1526. res = AVERROR_BUG;
  1527. goto error;
  1528. }
  1529. av_frame_unref(tmpoutsurf->in_ref);
  1530. tmpoutsurf->input_surface = NULL;
  1531. }
  1532. switch (lock_params.pictureType) {
  1533. case NV_ENC_PIC_TYPE_IDR:
  1534. pkt->flags |= AV_PKT_FLAG_KEY;
  1535. case NV_ENC_PIC_TYPE_I:
  1536. pict_type = AV_PICTURE_TYPE_I;
  1537. break;
  1538. case NV_ENC_PIC_TYPE_P:
  1539. pict_type = AV_PICTURE_TYPE_P;
  1540. break;
  1541. case NV_ENC_PIC_TYPE_B:
  1542. pict_type = AV_PICTURE_TYPE_B;
  1543. break;
  1544. case NV_ENC_PIC_TYPE_BI:
  1545. pict_type = AV_PICTURE_TYPE_BI;
  1546. break;
  1547. default:
  1548. av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
  1549. av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
  1550. res = AVERROR_EXTERNAL;
  1551. goto error;
  1552. }
  1553. #if FF_API_CODED_FRAME
  1554. FF_DISABLE_DEPRECATION_WARNINGS
  1555. avctx->coded_frame->pict_type = pict_type;
  1556. FF_ENABLE_DEPRECATION_WARNINGS
  1557. #endif
  1558. ff_side_data_set_encoder_stats(pkt,
  1559. (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
  1560. res = nvenc_set_timestamp(avctx, &lock_params, pkt);
  1561. if (res < 0)
  1562. goto error2;
  1563. av_free(slice_offsets);
  1564. return 0;
  1565. error:
  1566. timestamp_queue_dequeue(ctx->timestamp_list);
  1567. error2:
  1568. av_free(slice_offsets);
  1569. return res;
  1570. }
  1571. static int output_ready(AVCodecContext *avctx, int flush)
  1572. {
  1573. NvencContext *ctx = avctx->priv_data;
  1574. int nb_ready, nb_pending;
  1575. /* when B-frames are enabled, we wait for two initial timestamps to
  1576. * calculate the first dts */
  1577. if (!flush && avctx->max_b_frames > 0 &&
  1578. (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
  1579. return 0;
  1580. nb_ready = av_fifo_size(ctx->output_surface_ready_queue) / sizeof(NvencSurface*);
  1581. nb_pending = av_fifo_size(ctx->output_surface_queue) / sizeof(NvencSurface*);
  1582. if (flush)
  1583. return nb_ready > 0;
  1584. return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
  1585. }
  1586. int ff_nvenc_send_frame(AVCodecContext *avctx, const AVFrame *frame)
  1587. {
  1588. NVENCSTATUS nv_status;
  1589. NvencSurface *tmp_out_surf, *in_surf;
  1590. int res, res2;
  1591. NvencContext *ctx = avctx->priv_data;
  1592. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  1593. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  1594. NV_ENC_PIC_PARAMS pic_params = { 0 };
  1595. pic_params.version = NV_ENC_PIC_PARAMS_VER;
  1596. if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
  1597. return AVERROR(EINVAL);
  1598. if (ctx->encoder_flushing)
  1599. return AVERROR_EOF;
  1600. if (frame) {
  1601. in_surf = get_free_frame(ctx);
  1602. if (!in_surf)
  1603. return AVERROR(EAGAIN);
  1604. res = nvenc_push_context(avctx);
  1605. if (res < 0)
  1606. return res;
  1607. res = nvenc_upload_frame(avctx, frame, in_surf);
  1608. res2 = nvenc_pop_context(avctx);
  1609. if (res2 < 0)
  1610. return res2;
  1611. if (res)
  1612. return res;
  1613. pic_params.inputBuffer = in_surf->input_surface;
  1614. pic_params.bufferFmt = in_surf->format;
  1615. pic_params.inputWidth = in_surf->width;
  1616. pic_params.inputHeight = in_surf->height;
  1617. pic_params.inputPitch = in_surf->pitch;
  1618. pic_params.outputBitstream = in_surf->output_surface;
  1619. if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
  1620. if (frame->top_field_first)
  1621. pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
  1622. else
  1623. pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
  1624. } else {
  1625. pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
  1626. }
  1627. if (ctx->forced_idr >= 0 && frame->pict_type == AV_PICTURE_TYPE_I) {
  1628. pic_params.encodePicFlags =
  1629. ctx->forced_idr ? NV_ENC_PIC_FLAG_FORCEIDR : NV_ENC_PIC_FLAG_FORCEINTRA;
  1630. } else {
  1631. pic_params.encodePicFlags = 0;
  1632. }
  1633. pic_params.inputTimeStamp = frame->pts;
  1634. nvenc_codec_specific_pic_params(avctx, &pic_params);
  1635. } else {
  1636. pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
  1637. ctx->encoder_flushing = 1;
  1638. }
  1639. res = nvenc_push_context(avctx);
  1640. if (res < 0)
  1641. return res;
  1642. nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
  1643. res = nvenc_pop_context(avctx);
  1644. if (res < 0)
  1645. return res;
  1646. if (nv_status != NV_ENC_SUCCESS &&
  1647. nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
  1648. return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
  1649. if (frame) {
  1650. av_fifo_generic_write(ctx->output_surface_queue, &in_surf, sizeof(in_surf), NULL);
  1651. timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
  1652. if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
  1653. ctx->initial_pts[0] = frame->pts;
  1654. else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
  1655. ctx->initial_pts[1] = frame->pts;
  1656. }
  1657. /* all the pending buffers are now ready for output */
  1658. if (nv_status == NV_ENC_SUCCESS) {
  1659. while (av_fifo_size(ctx->output_surface_queue) > 0) {
  1660. av_fifo_generic_read(ctx->output_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
  1661. av_fifo_generic_write(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
  1662. }
  1663. }
  1664. return 0;
  1665. }
  1666. int ff_nvenc_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
  1667. {
  1668. NvencSurface *tmp_out_surf;
  1669. int res, res2;
  1670. NvencContext *ctx = avctx->priv_data;
  1671. if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
  1672. return AVERROR(EINVAL);
  1673. if (output_ready(avctx, ctx->encoder_flushing)) {
  1674. av_fifo_generic_read(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
  1675. res = nvenc_push_context(avctx);
  1676. if (res < 0)
  1677. return res;
  1678. res = process_output_surface(avctx, pkt, tmp_out_surf);
  1679. res2 = nvenc_pop_context(avctx);
  1680. if (res2 < 0)
  1681. return res2;
  1682. if (res)
  1683. return res;
  1684. av_fifo_generic_write(ctx->unused_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
  1685. } else if (ctx->encoder_flushing) {
  1686. return AVERROR_EOF;
  1687. } else {
  1688. return AVERROR(EAGAIN);
  1689. }
  1690. return 0;
  1691. }
  1692. int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
  1693. const AVFrame *frame, int *got_packet)
  1694. {
  1695. NvencContext *ctx = avctx->priv_data;
  1696. int res;
  1697. if (!ctx->encoder_flushing) {
  1698. res = ff_nvenc_send_frame(avctx, frame);
  1699. if (res < 0)
  1700. return res;
  1701. }
  1702. res = ff_nvenc_receive_packet(avctx, pkt);
  1703. if (res == AVERROR(EAGAIN) || res == AVERROR_EOF) {
  1704. *got_packet = 0;
  1705. } else if (res < 0) {
  1706. return res;
  1707. } else {
  1708. *got_packet = 1;
  1709. }
  1710. return 0;
  1711. }