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.

1734 lines
58KB

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