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.

1829 lines
62KB

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