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.

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