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.

1752 lines
58KB

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