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.

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