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.

1859 lines
63KB

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