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.

2221 lines
75KB

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