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.

1722 lines
57KB

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