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.

2352 lines
79KB

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