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.

1459 lines
47KB

  1. /*
  2. * NVIDIA NVENC Support
  3. * Copyright (C) 2015 Luca Barbato
  4. * Copyright (C) 2015 Philip Langdale <philipl@overt.org>
  5. * Copyright (C) 2014 Timo Rothenpieler <timo@rothenpieler.org>
  6. *
  7. * This file is part of Libav.
  8. *
  9. * Libav is free software; you can redistribute it and/or
  10. * modify it under the terms of the GNU Lesser General Public
  11. * License as published by the Free Software Foundation; either
  12. * version 2.1 of the License, or (at your option) any later version.
  13. *
  14. * Libav is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  17. * Lesser General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU Lesser General Public
  20. * License along with Libav; if not, write to the Free Software
  21. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  22. */
  23. #include "config.h"
  24. #include <nvEncodeAPI.h>
  25. #include <string.h>
  26. #define CUDA_LIBNAME "libcuda.so"
  27. #if HAVE_DLFCN_H
  28. #include <dlfcn.h>
  29. #define NVENC_LIBNAME "libnvidia-encode.so"
  30. #elif HAVE_WINDOWS_H
  31. #include <windows.h>
  32. #if ARCH_X86_64
  33. #define NVENC_LIBNAME "nvEncodeAPI64.dll"
  34. #else
  35. #define NVENC_LIBNAME "nvEncodeAPI.dll"
  36. #endif
  37. #define dlopen(filename, flags) LoadLibrary((filename))
  38. #define dlsym(handle, symbol) GetProcAddress(handle, symbol)
  39. #define dlclose(handle) FreeLibrary(handle)
  40. #endif
  41. #include "libavutil/common.h"
  42. #include "libavutil/hwcontext.h"
  43. #include "libavutil/imgutils.h"
  44. #include "libavutil/mem.h"
  45. #include "avcodec.h"
  46. #include "internal.h"
  47. #include "nvenc.h"
  48. #if CONFIG_CUDA
  49. #include "libavutil/hwcontext_cuda.h"
  50. #endif
  51. #define NVENC_CAP 0x30
  52. #define BITSTREAM_BUFFER_SIZE 1024 * 1024
  53. #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR || \
  54. rc == NV_ENC_PARAMS_RC_2_PASS_QUALITY || \
  55. rc == NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP)
  56. #define LOAD_LIBRARY(l, path) \
  57. do { \
  58. if (!((l) = dlopen(path, RTLD_LAZY))) { \
  59. av_log(avctx, AV_LOG_ERROR, \
  60. "Cannot load %s\n", \
  61. path); \
  62. return AVERROR_UNKNOWN; \
  63. } \
  64. } while (0)
  65. #define LOAD_SYMBOL(fun, lib, symbol) \
  66. do { \
  67. if (!((fun) = dlsym(lib, symbol))) { \
  68. av_log(avctx, AV_LOG_ERROR, \
  69. "Cannot load %s\n", \
  70. symbol); \
  71. return AVERROR_UNKNOWN; \
  72. } \
  73. } while (0)
  74. const enum AVPixelFormat ff_nvenc_pix_fmts[] = {
  75. AV_PIX_FMT_NV12,
  76. AV_PIX_FMT_YUV420P,
  77. AV_PIX_FMT_YUV444P,
  78. #if CONFIG_CUDA
  79. AV_PIX_FMT_CUDA,
  80. #endif
  81. AV_PIX_FMT_NONE
  82. };
  83. static const struct {
  84. NVENCSTATUS nverr;
  85. int averr;
  86. const char *desc;
  87. } nvenc_errors[] = {
  88. { NV_ENC_SUCCESS, 0, "success" },
  89. { NV_ENC_ERR_NO_ENCODE_DEVICE, AVERROR(ENOENT), "no encode device" },
  90. { NV_ENC_ERR_UNSUPPORTED_DEVICE, AVERROR(ENOSYS), "unsupported device" },
  91. { NV_ENC_ERR_INVALID_ENCODERDEVICE, AVERROR(EINVAL), "invalid encoder device" },
  92. { NV_ENC_ERR_INVALID_DEVICE, AVERROR(EINVAL), "invalid device" },
  93. { NV_ENC_ERR_DEVICE_NOT_EXIST, AVERROR(EIO), "device does not exist" },
  94. { NV_ENC_ERR_INVALID_PTR, AVERROR(EFAULT), "invalid ptr" },
  95. { NV_ENC_ERR_INVALID_EVENT, AVERROR(EINVAL), "invalid event" },
  96. { NV_ENC_ERR_INVALID_PARAM, AVERROR(EINVAL), "invalid param" },
  97. { NV_ENC_ERR_INVALID_CALL, AVERROR(EINVAL), "invalid call" },
  98. { NV_ENC_ERR_OUT_OF_MEMORY, AVERROR(ENOMEM), "out of memory" },
  99. { NV_ENC_ERR_ENCODER_NOT_INITIALIZED, AVERROR(EINVAL), "encoder not initialized" },
  100. { NV_ENC_ERR_UNSUPPORTED_PARAM, AVERROR(ENOSYS), "unsupported param" },
  101. { NV_ENC_ERR_LOCK_BUSY, AVERROR(EAGAIN), "lock busy" },
  102. { NV_ENC_ERR_NOT_ENOUGH_BUFFER, AVERROR(ENOBUFS), "not enough buffer" },
  103. { NV_ENC_ERR_INVALID_VERSION, AVERROR(EINVAL), "invalid version" },
  104. { NV_ENC_ERR_MAP_FAILED, AVERROR(EIO), "map failed" },
  105. { NV_ENC_ERR_NEED_MORE_INPUT, AVERROR(EAGAIN), "need more input" },
  106. { NV_ENC_ERR_ENCODER_BUSY, AVERROR(EAGAIN), "encoder busy" },
  107. { NV_ENC_ERR_EVENT_NOT_REGISTERD, AVERROR(EBADF), "event not registered" },
  108. { NV_ENC_ERR_GENERIC, AVERROR_UNKNOWN, "generic error" },
  109. { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY, AVERROR(EINVAL), "incompatible client key" },
  110. { NV_ENC_ERR_UNIMPLEMENTED, AVERROR(ENOSYS), "unimplemented" },
  111. { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO), "resource register failed" },
  112. { NV_ENC_ERR_RESOURCE_NOT_REGISTERED, AVERROR(EBADF), "resource not registered" },
  113. { NV_ENC_ERR_RESOURCE_NOT_MAPPED, AVERROR(EBADF), "resource not mapped" },
  114. };
  115. static int nvenc_map_error(NVENCSTATUS err, const char **desc)
  116. {
  117. int i;
  118. for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
  119. if (nvenc_errors[i].nverr == err) {
  120. if (desc)
  121. *desc = nvenc_errors[i].desc;
  122. return nvenc_errors[i].averr;
  123. }
  124. }
  125. if (desc)
  126. *desc = "unknown error";
  127. return AVERROR_UNKNOWN;
  128. }
  129. static int nvenc_print_error(void *log_ctx, NVENCSTATUS err,
  130. const char *error_string)
  131. {
  132. const char *desc;
  133. int ret;
  134. ret = nvenc_map_error(err, &desc);
  135. av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
  136. return ret;
  137. }
  138. static av_cold int nvenc_load_libraries(AVCodecContext *avctx)
  139. {
  140. NVENCContext *ctx = avctx->priv_data;
  141. NVENCLibraryContext *nvel = &ctx->nvel;
  142. PNVENCODEAPICREATEINSTANCE nvenc_create_instance;
  143. NVENCSTATUS err;
  144. #if CONFIG_CUDA
  145. nvel->cu_init = cuInit;
  146. nvel->cu_device_get_count = cuDeviceGetCount;
  147. nvel->cu_device_get = cuDeviceGet;
  148. nvel->cu_device_get_name = cuDeviceGetName;
  149. nvel->cu_device_compute_capability = cuDeviceComputeCapability;
  150. nvel->cu_ctx_create = cuCtxCreate_v2;
  151. nvel->cu_ctx_pop_current = cuCtxPopCurrent_v2;
  152. nvel->cu_ctx_destroy = cuCtxDestroy_v2;
  153. #else
  154. LOAD_LIBRARY(nvel->cuda, CUDA_LIBNAME);
  155. LOAD_SYMBOL(nvel->cu_init, nvel->cuda, "cuInit");
  156. LOAD_SYMBOL(nvel->cu_device_get_count, nvel->cuda, "cuDeviceGetCount");
  157. LOAD_SYMBOL(nvel->cu_device_get, nvel->cuda, "cuDeviceGet");
  158. LOAD_SYMBOL(nvel->cu_device_get_name, nvel->cuda, "cuDeviceGetName");
  159. LOAD_SYMBOL(nvel->cu_device_compute_capability, nvel->cuda,
  160. "cuDeviceComputeCapability");
  161. LOAD_SYMBOL(nvel->cu_ctx_create, nvel->cuda, "cuCtxCreate_v2");
  162. LOAD_SYMBOL(nvel->cu_ctx_pop_current, nvel->cuda, "cuCtxPopCurrent_v2");
  163. LOAD_SYMBOL(nvel->cu_ctx_destroy, nvel->cuda, "cuCtxDestroy_v2");
  164. #endif
  165. LOAD_LIBRARY(nvel->nvenc, NVENC_LIBNAME);
  166. LOAD_SYMBOL(nvenc_create_instance, nvel->nvenc,
  167. "NvEncodeAPICreateInstance");
  168. nvel->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
  169. err = nvenc_create_instance(&nvel->nvenc_funcs);
  170. if (err != NV_ENC_SUCCESS)
  171. return nvenc_print_error(avctx, err, "Cannot create the NVENC instance");
  172. return 0;
  173. }
  174. static int nvenc_open_session(AVCodecContext *avctx)
  175. {
  176. NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
  177. NVENCContext *ctx = avctx->priv_data;
  178. NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
  179. int ret;
  180. params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
  181. params.apiVersion = NVENCAPI_VERSION;
  182. params.device = ctx->cu_context;
  183. params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
  184. ret = nv->nvEncOpenEncodeSessionEx(&params, &ctx->nvenc_ctx);
  185. if (ret != NV_ENC_SUCCESS) {
  186. ctx->nvenc_ctx = NULL;
  187. return nvenc_print_error(avctx, ret, "Cannot open the NVENC Session");
  188. }
  189. return 0;
  190. }
  191. static int nvenc_check_codec_support(AVCodecContext *avctx)
  192. {
  193. NVENCContext *ctx = avctx->priv_data;
  194. NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
  195. int i, ret, count = 0;
  196. GUID *guids = NULL;
  197. ret = nv->nvEncGetEncodeGUIDCount(ctx->nvenc_ctx, &count);
  198. if (ret != NV_ENC_SUCCESS || !count)
  199. return AVERROR(ENOSYS);
  200. guids = av_malloc(count * sizeof(GUID));
  201. if (!guids)
  202. return AVERROR(ENOMEM);
  203. ret = nv->nvEncGetEncodeGUIDs(ctx->nvenc_ctx, guids, count, &count);
  204. if (ret != NV_ENC_SUCCESS) {
  205. ret = AVERROR(ENOSYS);
  206. goto fail;
  207. }
  208. ret = AVERROR(ENOSYS);
  209. for (i = 0; i < count; i++) {
  210. if (!memcmp(&guids[i], &ctx->params.encodeGUID, sizeof(*guids))) {
  211. ret = 0;
  212. break;
  213. }
  214. }
  215. fail:
  216. av_free(guids);
  217. return ret;
  218. }
  219. static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
  220. {
  221. NVENCContext *ctx = avctx->priv_data;
  222. NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
  223. NV_ENC_CAPS_PARAM params = { 0 };
  224. int ret, val = 0;
  225. params.version = NV_ENC_CAPS_PARAM_VER;
  226. params.capsToQuery = cap;
  227. ret = nv->nvEncGetEncodeCaps(ctx->nvenc_ctx, ctx->params.encodeGUID, &params, &val);
  228. if (ret == NV_ENC_SUCCESS)
  229. return val;
  230. return 0;
  231. }
  232. static int nvenc_check_capabilities(AVCodecContext *avctx)
  233. {
  234. NVENCContext *ctx = avctx->priv_data;
  235. int ret;
  236. ret = nvenc_check_codec_support(avctx);
  237. if (ret < 0) {
  238. av_log(avctx, AV_LOG_VERBOSE, "Codec not supported\n");
  239. return ret;
  240. }
  241. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
  242. if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P && ret <= 0) {
  243. av_log(avctx, AV_LOG_VERBOSE, "YUV444P not supported\n");
  244. return AVERROR(ENOSYS);
  245. }
  246. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
  247. if (ret < avctx->width) {
  248. av_log(avctx, AV_LOG_VERBOSE, "Width %d exceeds %d\n",
  249. avctx->width, ret);
  250. return AVERROR(ENOSYS);
  251. }
  252. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
  253. if (ret < avctx->height) {
  254. av_log(avctx, AV_LOG_VERBOSE, "Height %d exceeds %d\n",
  255. avctx->height, ret);
  256. return AVERROR(ENOSYS);
  257. }
  258. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
  259. if (ret < avctx->max_b_frames) {
  260. av_log(avctx, AV_LOG_VERBOSE, "Max B-frames %d exceed %d\n",
  261. avctx->max_b_frames, ret);
  262. return AVERROR(ENOSYS);
  263. }
  264. return 0;
  265. }
  266. static int nvenc_check_device(AVCodecContext *avctx, int idx)
  267. {
  268. NVENCContext *ctx = avctx->priv_data;
  269. NVENCLibraryContext *nvel = &ctx->nvel;
  270. char name[128] = { 0 };
  271. int major, minor, ret;
  272. CUdevice cu_device;
  273. CUcontext dummy;
  274. int loglevel = AV_LOG_VERBOSE;
  275. if (ctx->device == LIST_DEVICES)
  276. loglevel = AV_LOG_INFO;
  277. ret = nvel->cu_device_get(&cu_device, idx);
  278. if (ret != CUDA_SUCCESS) {
  279. av_log(avctx, AV_LOG_ERROR,
  280. "Cannot access the CUDA device %d\n",
  281. idx);
  282. return -1;
  283. }
  284. ret = nvel->cu_device_get_name(name, sizeof(name), cu_device);
  285. if (ret != CUDA_SUCCESS)
  286. return -1;
  287. ret = nvel->cu_device_compute_capability(&major, &minor, cu_device);
  288. if (ret != CUDA_SUCCESS)
  289. return -1;
  290. av_log(avctx, loglevel, "Device %d [%s] ", cu_device, name);
  291. if (((major << 4) | minor) < NVENC_CAP)
  292. goto fail;
  293. ret = nvel->cu_ctx_create(&ctx->cu_context_internal, 0, cu_device);
  294. if (ret != CUDA_SUCCESS)
  295. goto fail;
  296. ctx->cu_context = ctx->cu_context_internal;
  297. ret = nvel->cu_ctx_pop_current(&dummy);
  298. if (ret != CUDA_SUCCESS)
  299. goto fail2;
  300. if ((ret = nvenc_open_session(avctx)) < 0)
  301. goto fail2;
  302. if ((ret = nvenc_check_capabilities(avctx)) < 0)
  303. goto fail3;
  304. av_log(avctx, loglevel, "supports NVENC\n");
  305. if (ctx->device == cu_device || ctx->device == ANY_DEVICE)
  306. return 0;
  307. fail3:
  308. nvel->nvenc_funcs.nvEncDestroyEncoder(ctx->nvenc_ctx);
  309. ctx->nvenc_ctx = NULL;
  310. fail2:
  311. nvel->cu_ctx_destroy(ctx->cu_context_internal);
  312. ctx->cu_context_internal = NULL;
  313. fail:
  314. if (ret != 0)
  315. av_log(avctx, loglevel, "does not support NVENC (major %d minor %d)\n",
  316. major, minor);
  317. return AVERROR(ENOSYS);
  318. }
  319. static int nvenc_setup_device(AVCodecContext *avctx)
  320. {
  321. NVENCContext *ctx = avctx->priv_data;
  322. NVENCLibraryContext *nvel = &ctx->nvel;
  323. switch (avctx->codec->id) {
  324. case AV_CODEC_ID_H264:
  325. ctx->params.encodeGUID = NV_ENC_CODEC_H264_GUID;
  326. break;
  327. case AV_CODEC_ID_HEVC:
  328. ctx->params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
  329. break;
  330. default:
  331. return AVERROR_BUG;
  332. }
  333. if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
  334. #if CONFIG_CUDA
  335. AVHWFramesContext *frames_ctx;
  336. AVCUDADeviceContext *device_hwctx;
  337. int ret;
  338. if (!avctx->hw_frames_ctx)
  339. return AVERROR(EINVAL);
  340. frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  341. device_hwctx = frames_ctx->device_ctx->hwctx;
  342. ctx->cu_context = device_hwctx->cuda_ctx;
  343. ret = nvenc_open_session(avctx);
  344. if (ret < 0)
  345. return ret;
  346. ret = nvenc_check_capabilities(avctx);
  347. if (ret < 0)
  348. return ret;
  349. #else
  350. return AVERROR_BUG;
  351. #endif
  352. } else {
  353. int i, nb_devices = 0;
  354. if ((nvel->cu_init(0)) != CUDA_SUCCESS) {
  355. av_log(avctx, AV_LOG_ERROR,
  356. "Cannot init CUDA\n");
  357. return AVERROR_UNKNOWN;
  358. }
  359. if ((nvel->cu_device_get_count(&nb_devices)) != CUDA_SUCCESS) {
  360. av_log(avctx, AV_LOG_ERROR,
  361. "Cannot enumerate the CUDA devices\n");
  362. return AVERROR_UNKNOWN;
  363. }
  364. for (i = 0; i < nb_devices; ++i) {
  365. if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
  366. return 0;
  367. }
  368. if (ctx->device == LIST_DEVICES)
  369. return AVERROR_EXIT;
  370. return AVERROR(ENOSYS);
  371. }
  372. return 0;
  373. }
  374. typedef struct GUIDTuple {
  375. const GUID guid;
  376. int flags;
  377. } GUIDTuple;
  378. static int nvec_map_preset(NVENCContext *ctx)
  379. {
  380. GUIDTuple presets[] = {
  381. { NV_ENC_PRESET_DEFAULT_GUID },
  382. { NV_ENC_PRESET_HP_GUID },
  383. { NV_ENC_PRESET_HQ_GUID },
  384. { NV_ENC_PRESET_BD_GUID },
  385. { NV_ENC_PRESET_LOW_LATENCY_DEFAULT_GUID, NVENC_LOWLATENCY },
  386. { NV_ENC_PRESET_LOW_LATENCY_HP_GUID, NVENC_LOWLATENCY },
  387. { NV_ENC_PRESET_LOW_LATENCY_HQ_GUID, NVENC_LOWLATENCY },
  388. { NV_ENC_PRESET_LOSSLESS_DEFAULT_GUID, NVENC_LOSSLESS },
  389. { NV_ENC_PRESET_LOSSLESS_HP_GUID, NVENC_LOSSLESS },
  390. { { 0 } }
  391. };
  392. GUIDTuple *t = &presets[ctx->preset];
  393. ctx->params.presetGUID = t->guid;
  394. ctx->flags = t->flags;
  395. return AVERROR(EINVAL);
  396. }
  397. static void set_constqp(AVCodecContext *avctx, NV_ENC_RC_PARAMS *rc)
  398. {
  399. rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
  400. rc->constQP.qpInterB = avctx->global_quality;
  401. rc->constQP.qpInterP = avctx->global_quality;
  402. rc->constQP.qpIntra = avctx->global_quality;
  403. }
  404. static void set_vbr(AVCodecContext *avctx, NV_ENC_RC_PARAMS *rc)
  405. {
  406. if (avctx->qmin >= 0) {
  407. rc->enableMinQP = 1;
  408. rc->minQP.qpInterB = avctx->qmin;
  409. rc->minQP.qpInterP = avctx->qmin;
  410. rc->minQP.qpIntra = avctx->qmin;
  411. }
  412. if (avctx->qmax >= 0) {
  413. rc->enableMaxQP = 1;
  414. rc->maxQP.qpInterB = avctx->qmax;
  415. rc->maxQP.qpInterP = avctx->qmax;
  416. rc->maxQP.qpIntra = avctx->qmax;
  417. }
  418. }
  419. static void set_lossless(AVCodecContext *avctx, NV_ENC_RC_PARAMS *rc)
  420. {
  421. rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
  422. rc->constQP.qpInterB = 0;
  423. rc->constQP.qpInterP = 0;
  424. rc->constQP.qpIntra = 0;
  425. }
  426. static void nvenc_override_rate_control(AVCodecContext *avctx,
  427. NV_ENC_RC_PARAMS *rc)
  428. {
  429. NVENCContext *ctx = avctx->priv_data;
  430. switch (ctx->rc) {
  431. case NV_ENC_PARAMS_RC_CONSTQP:
  432. if (avctx->global_quality < 0) {
  433. av_log(avctx, AV_LOG_WARNING,
  434. "The constant quality rate-control requires "
  435. "the 'global_quality' option set.\n");
  436. return;
  437. }
  438. set_constqp(avctx, rc);
  439. return;
  440. case NV_ENC_PARAMS_RC_2_PASS_VBR:
  441. case NV_ENC_PARAMS_RC_VBR:
  442. if (avctx->qmin < 0 && avctx->qmax < 0) {
  443. av_log(avctx, AV_LOG_WARNING,
  444. "The variable bitrate rate-control requires "
  445. "the 'qmin' and/or 'qmax' option set.\n");
  446. return;
  447. }
  448. case NV_ENC_PARAMS_RC_VBR_MINQP:
  449. if (avctx->qmin < 0) {
  450. av_log(avctx, AV_LOG_WARNING,
  451. "The variable bitrate rate-control requires "
  452. "the 'qmin' option set.\n");
  453. return;
  454. }
  455. set_vbr(avctx, rc);
  456. break;
  457. case NV_ENC_PARAMS_RC_CBR:
  458. break;
  459. case NV_ENC_PARAMS_RC_2_PASS_QUALITY:
  460. case NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP:
  461. if (!(ctx->flags & NVENC_LOWLATENCY)) {
  462. av_log(avctx, AV_LOG_WARNING,
  463. "The multipass rate-control requires "
  464. "a low-latency preset.\n");
  465. return;
  466. }
  467. }
  468. rc->rateControlMode = ctx->rc;
  469. }
  470. static void nvenc_setup_rate_control(AVCodecContext *avctx)
  471. {
  472. NVENCContext *ctx = avctx->priv_data;
  473. NV_ENC_RC_PARAMS *rc = &ctx->config.rcParams;
  474. if (avctx->bit_rate > 0)
  475. rc->averageBitRate = avctx->bit_rate;
  476. if (avctx->rc_max_rate > 0)
  477. rc->maxBitRate = avctx->rc_max_rate;
  478. if (ctx->rc > 0) {
  479. nvenc_override_rate_control(avctx, rc);
  480. } else if (ctx->flags & NVENC_LOSSLESS) {
  481. set_lossless(avctx, rc);
  482. } else if (avctx->global_quality > 0) {
  483. set_constqp(avctx, rc);
  484. } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
  485. rc->rateControlMode = NV_ENC_PARAMS_RC_VBR;
  486. set_vbr(avctx, rc);
  487. }
  488. if (avctx->rc_buffer_size > 0)
  489. rc->vbvBufferSize = avctx->rc_buffer_size;
  490. if (rc->averageBitRate > 0)
  491. avctx->bit_rate = rc->averageBitRate;
  492. }
  493. static int nvenc_setup_h264_config(AVCodecContext *avctx)
  494. {
  495. NVENCContext *ctx = avctx->priv_data;
  496. NV_ENC_CONFIG *cc = &ctx->config;
  497. NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
  498. NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
  499. vui->colourDescriptionPresentFlag = avctx->colorspace != AVCOL_SPC_UNSPECIFIED ||
  500. avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
  501. avctx->color_trc != AVCOL_TRC_UNSPECIFIED;
  502. vui->colourMatrix = avctx->colorspace;
  503. vui->colourPrimaries = avctx->color_primaries;
  504. vui->transferCharacteristics = avctx->color_trc;
  505. vui->videoFullRangeFlag = avctx->color_range == AVCOL_RANGE_JPEG;
  506. vui->videoSignalTypePresentFlag = vui->colourDescriptionPresentFlag ||
  507. vui->videoFullRangeFlag;
  508. h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
  509. h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
  510. h264->outputAUD = 1;
  511. h264->maxNumRefFrames = avctx->refs;
  512. h264->idrPeriod = cc->gopLength;
  513. h264->sliceMode = 3;
  514. h264->sliceModeData = FFMAX(avctx->slices, 1);
  515. if (ctx->flags & NVENC_LOSSLESS)
  516. h264->qpPrimeYZeroTransformBypassFlag = 1;
  517. if (IS_CBR(cc->rcParams.rateControlMode)) {
  518. h264->outputBufferingPeriodSEI = 1;
  519. h264->outputPictureTimingSEI = 1;
  520. }
  521. if (ctx->profile)
  522. avctx->profile = ctx->profile;
  523. if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P)
  524. h264->chromaFormatIDC = 3;
  525. else
  526. h264->chromaFormatIDC = 1;
  527. switch (ctx->profile) {
  528. case NV_ENC_H264_PROFILE_BASELINE:
  529. cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
  530. break;
  531. case NV_ENC_H264_PROFILE_MAIN:
  532. cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
  533. break;
  534. case NV_ENC_H264_PROFILE_HIGH:
  535. cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
  536. break;
  537. case NV_ENC_H264_PROFILE_HIGH_444:
  538. cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
  539. break;
  540. case NV_ENC_H264_PROFILE_CONSTRAINED_HIGH:
  541. cc->profileGUID = NV_ENC_H264_PROFILE_CONSTRAINED_HIGH_GUID;
  542. break;
  543. }
  544. h264->level = ctx->level;
  545. return 0;
  546. }
  547. static int nvenc_setup_hevc_config(AVCodecContext *avctx)
  548. {
  549. NVENCContext *ctx = avctx->priv_data;
  550. NV_ENC_CONFIG *cc = &ctx->config;
  551. NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
  552. NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
  553. vui->colourDescriptionPresentFlag = avctx->colorspace != AVCOL_SPC_UNSPECIFIED ||
  554. avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
  555. avctx->color_trc != AVCOL_TRC_UNSPECIFIED;
  556. vui->colourMatrix = avctx->colorspace;
  557. vui->colourPrimaries = avctx->color_primaries;
  558. vui->transferCharacteristics = avctx->color_trc;
  559. vui->videoFullRangeFlag = avctx->color_range == AVCOL_RANGE_JPEG;
  560. vui->videoSignalTypePresentFlag = vui->colourDescriptionPresentFlag ||
  561. vui->videoFullRangeFlag;
  562. hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
  563. hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
  564. hevc->outputAUD = 1;
  565. hevc->maxNumRefFramesInDPB = avctx->refs;
  566. hevc->idrPeriod = cc->gopLength;
  567. if (IS_CBR(cc->rcParams.rateControlMode)) {
  568. hevc->outputBufferingPeriodSEI = 1;
  569. hevc->outputPictureTimingSEI = 1;
  570. }
  571. /* No other profile is supported in the current SDK version 5 */
  572. cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
  573. avctx->profile = FF_PROFILE_HEVC_MAIN;
  574. hevc->sliceMode = 3;
  575. hevc->sliceModeData = FFMAX(avctx->slices, 1);
  576. if (ctx->level) {
  577. hevc->level = ctx->level;
  578. } else {
  579. hevc->level = NV_ENC_LEVEL_AUTOSELECT;
  580. }
  581. if (ctx->tier) {
  582. hevc->tier = ctx->tier;
  583. }
  584. return 0;
  585. }
  586. static int nvenc_setup_codec_config(AVCodecContext *avctx)
  587. {
  588. switch (avctx->codec->id) {
  589. case AV_CODEC_ID_H264:
  590. return nvenc_setup_h264_config(avctx);
  591. case AV_CODEC_ID_HEVC:
  592. return nvenc_setup_hevc_config(avctx);
  593. }
  594. return 0;
  595. }
  596. static int nvenc_setup_encoder(AVCodecContext *avctx)
  597. {
  598. NVENCContext *ctx = avctx->priv_data;
  599. NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
  600. NV_ENC_PRESET_CONFIG preset_cfg = { 0 };
  601. AVCPBProperties *cpb_props;
  602. int ret;
  603. ctx->params.version = NV_ENC_INITIALIZE_PARAMS_VER;
  604. ctx->params.encodeHeight = avctx->height;
  605. ctx->params.encodeWidth = avctx->width;
  606. if (avctx->sample_aspect_ratio.num &&
  607. avctx->sample_aspect_ratio.den &&
  608. (avctx->sample_aspect_ratio.num != 1 ||
  609. avctx->sample_aspect_ratio.den != 1)) {
  610. av_reduce(&ctx->params.darWidth,
  611. &ctx->params.darHeight,
  612. avctx->width * avctx->sample_aspect_ratio.num,
  613. avctx->height * avctx->sample_aspect_ratio.den,
  614. INT_MAX / 8);
  615. } else {
  616. ctx->params.darHeight = avctx->height;
  617. ctx->params.darWidth = avctx->width;
  618. }
  619. // De-compensate for hardware, dubiously, trying to compensate for
  620. // playback at 704 pixel width.
  621. if (avctx->width == 720 && (avctx->height == 480 || avctx->height == 576)) {
  622. av_reduce(&ctx->params.darWidth, &ctx->params.darHeight,
  623. ctx->params.darWidth * 44,
  624. ctx->params.darHeight * 45,
  625. 1024 * 1024);
  626. }
  627. ctx->params.frameRateNum = avctx->time_base.den;
  628. ctx->params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
  629. ctx->params.enableEncodeAsync = 0;
  630. ctx->params.enablePTD = 1;
  631. ctx->params.encodeConfig = &ctx->config;
  632. nvec_map_preset(ctx);
  633. preset_cfg.version = NV_ENC_PRESET_CONFIG_VER;
  634. preset_cfg.presetCfg.version = NV_ENC_CONFIG_VER;
  635. ret = nv->nvEncGetEncodePresetConfig(ctx->nvenc_ctx,
  636. ctx->params.encodeGUID,
  637. ctx->params.presetGUID,
  638. &preset_cfg);
  639. if (ret != NV_ENC_SUCCESS)
  640. return nvenc_print_error(avctx, ret, "Cannot get the preset configuration");
  641. memcpy(&ctx->config, &preset_cfg.presetCfg, sizeof(ctx->config));
  642. ctx->config.version = NV_ENC_CONFIG_VER;
  643. if (avctx->gop_size > 0) {
  644. if (avctx->max_b_frames > 0) {
  645. /* 0 is intra-only,
  646. * 1 is I/P only,
  647. * 2 is one B-Frame,
  648. * 3 two B-frames, and so on. */
  649. ctx->config.frameIntervalP = avctx->max_b_frames + 1;
  650. } else if (avctx->max_b_frames == 0) {
  651. ctx->config.frameIntervalP = 1;
  652. }
  653. ctx->config.gopLength = avctx->gop_size;
  654. } else if (avctx->gop_size == 0) {
  655. ctx->config.frameIntervalP = 0;
  656. ctx->config.gopLength = 1;
  657. }
  658. if (ctx->config.frameIntervalP > 1)
  659. avctx->max_b_frames = ctx->config.frameIntervalP - 1;
  660. ctx->initial_pts[0] = AV_NOPTS_VALUE;
  661. ctx->initial_pts[1] = AV_NOPTS_VALUE;
  662. nvenc_setup_rate_control(avctx);
  663. if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
  664. ctx->config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
  665. } else {
  666. ctx->config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
  667. }
  668. if ((ret = nvenc_setup_codec_config(avctx)) < 0)
  669. return ret;
  670. ret = nv->nvEncInitializeEncoder(ctx->nvenc_ctx, &ctx->params);
  671. if (ret != NV_ENC_SUCCESS)
  672. return nvenc_print_error(avctx, ret, "Cannot initialize the decoder");
  673. cpb_props = ff_add_cpb_side_data(avctx);
  674. if (!cpb_props)
  675. return AVERROR(ENOMEM);
  676. cpb_props->max_bitrate = avctx->rc_max_rate;
  677. cpb_props->min_bitrate = avctx->rc_min_rate;
  678. cpb_props->avg_bitrate = avctx->bit_rate;
  679. cpb_props->buffer_size = avctx->rc_buffer_size;
  680. return 0;
  681. }
  682. static int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
  683. {
  684. NVENCContext *ctx = avctx->priv_data;
  685. NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
  686. int ret;
  687. NV_ENC_CREATE_BITSTREAM_BUFFER out_buffer = { 0 };
  688. switch (ctx->data_pix_fmt) {
  689. case AV_PIX_FMT_YUV420P:
  690. ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YV12_PL;
  691. break;
  692. case AV_PIX_FMT_NV12:
  693. ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_NV12_PL;
  694. break;
  695. case AV_PIX_FMT_YUV444P:
  696. ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YUV444_PL;
  697. break;
  698. default:
  699. return AVERROR_BUG;
  700. }
  701. if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
  702. ctx->frames[idx].in_ref = av_frame_alloc();
  703. if (!ctx->frames[idx].in_ref)
  704. return AVERROR(ENOMEM);
  705. } else {
  706. NV_ENC_CREATE_INPUT_BUFFER in_buffer = { 0 };
  707. in_buffer.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
  708. in_buffer.width = avctx->width;
  709. in_buffer.height = avctx->height;
  710. in_buffer.bufferFmt = ctx->frames[idx].format;
  711. in_buffer.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED;
  712. ret = nv->nvEncCreateInputBuffer(ctx->nvenc_ctx, &in_buffer);
  713. if (ret != NV_ENC_SUCCESS)
  714. return nvenc_print_error(avctx, ret, "CreateInputBuffer failed");
  715. ctx->frames[idx].in = in_buffer.inputBuffer;
  716. }
  717. out_buffer.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
  718. /* 1MB is large enough to hold most output frames.
  719. * NVENC increases this automatically if it is not enough. */
  720. out_buffer.size = BITSTREAM_BUFFER_SIZE;
  721. out_buffer.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED;
  722. ret = nv->nvEncCreateBitstreamBuffer(ctx->nvenc_ctx, &out_buffer);
  723. if (ret != NV_ENC_SUCCESS)
  724. return nvenc_print_error(avctx, ret, "CreateBitstreamBuffer failed");
  725. ctx->frames[idx].out = out_buffer.bitstreamBuffer;
  726. return 0;
  727. }
  728. static int nvenc_setup_surfaces(AVCodecContext *avctx)
  729. {
  730. NVENCContext *ctx = avctx->priv_data;
  731. int i, ret;
  732. ctx->nb_surfaces = FFMAX(4 + avctx->max_b_frames,
  733. ctx->nb_surfaces);
  734. ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
  735. ctx->frames = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->frames));
  736. if (!ctx->frames)
  737. return AVERROR(ENOMEM);
  738. ctx->timestamps = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
  739. if (!ctx->timestamps)
  740. return AVERROR(ENOMEM);
  741. ctx->pending = av_fifo_alloc(ctx->nb_surfaces * sizeof(*ctx->frames));
  742. if (!ctx->pending)
  743. return AVERROR(ENOMEM);
  744. ctx->ready = av_fifo_alloc(ctx->nb_surfaces * sizeof(*ctx->frames));
  745. if (!ctx->ready)
  746. return AVERROR(ENOMEM);
  747. for (i = 0; i < ctx->nb_surfaces; i++) {
  748. if ((ret = nvenc_alloc_surface(avctx, i)) < 0)
  749. return ret;
  750. }
  751. return 0;
  752. }
  753. #define EXTRADATA_SIZE 512
  754. static int nvenc_setup_extradata(AVCodecContext *avctx)
  755. {
  756. NVENCContext *ctx = avctx->priv_data;
  757. NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
  758. NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
  759. int ret;
  760. avctx->extradata = av_mallocz(EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
  761. if (!avctx->extradata)
  762. return AVERROR(ENOMEM);
  763. payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
  764. payload.spsppsBuffer = avctx->extradata;
  765. payload.inBufferSize = EXTRADATA_SIZE;
  766. payload.outSPSPPSPayloadSize = &avctx->extradata_size;
  767. ret = nv->nvEncGetSequenceParams(ctx->nvenc_ctx, &payload);
  768. if (ret != NV_ENC_SUCCESS)
  769. return nvenc_print_error(avctx, ret, "Cannot get the extradata");
  770. return 0;
  771. }
  772. av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
  773. {
  774. NVENCContext *ctx = avctx->priv_data;
  775. NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
  776. int i;
  777. /* the encoder has to be flushed before it can be closed */
  778. if (ctx->nvenc_ctx) {
  779. NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
  780. .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
  781. nv->nvEncEncodePicture(ctx->nvenc_ctx, &params);
  782. }
  783. av_fifo_free(ctx->timestamps);
  784. av_fifo_free(ctx->pending);
  785. av_fifo_free(ctx->ready);
  786. if (ctx->frames) {
  787. for (i = 0; i < ctx->nb_surfaces; ++i) {
  788. if (avctx->pix_fmt != AV_PIX_FMT_CUDA) {
  789. nv->nvEncDestroyInputBuffer(ctx->nvenc_ctx, ctx->frames[i].in);
  790. } else if (ctx->frames[i].in) {
  791. nv->nvEncUnmapInputResource(ctx->nvenc_ctx, ctx->frames[i].in_map.mappedResource);
  792. }
  793. av_frame_free(&ctx->frames[i].in_ref);
  794. nv->nvEncDestroyBitstreamBuffer(ctx->nvenc_ctx, ctx->frames[i].out);
  795. }
  796. }
  797. for (i = 0; i < ctx->nb_registered_frames; i++) {
  798. if (ctx->registered_frames[i].regptr)
  799. nv->nvEncUnregisterResource(ctx->nvenc_ctx, ctx->registered_frames[i].regptr);
  800. }
  801. ctx->nb_registered_frames = 0;
  802. av_freep(&ctx->frames);
  803. if (ctx->nvenc_ctx)
  804. nv->nvEncDestroyEncoder(ctx->nvenc_ctx);
  805. if (ctx->cu_context_internal)
  806. ctx->nvel.cu_ctx_destroy(ctx->cu_context_internal);
  807. if (ctx->nvel.nvenc)
  808. dlclose(ctx->nvel.nvenc);
  809. #if !CONFIG_CUDA
  810. if (ctx->nvel.cuda)
  811. dlclose(ctx->nvel.cuda);
  812. #endif
  813. return 0;
  814. }
  815. av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
  816. {
  817. NVENCContext *ctx = avctx->priv_data;
  818. int ret;
  819. if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
  820. AVHWFramesContext *frames_ctx;
  821. if (!avctx->hw_frames_ctx) {
  822. av_log(avctx, AV_LOG_ERROR,
  823. "hw_frames_ctx must be set when using GPU frames as input\n");
  824. return AVERROR(EINVAL);
  825. }
  826. frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  827. ctx->data_pix_fmt = frames_ctx->sw_format;
  828. } else {
  829. ctx->data_pix_fmt = avctx->pix_fmt;
  830. }
  831. if ((ret = nvenc_load_libraries(avctx)) < 0)
  832. return ret;
  833. if ((ret = nvenc_setup_device(avctx)) < 0)
  834. return ret;
  835. if ((ret = nvenc_setup_encoder(avctx)) < 0)
  836. return ret;
  837. if ((ret = nvenc_setup_surfaces(avctx)) < 0)
  838. return ret;
  839. if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
  840. if ((ret = nvenc_setup_extradata(avctx)) < 0)
  841. return ret;
  842. }
  843. return 0;
  844. }
  845. static NVENCFrame *get_free_frame(NVENCContext *ctx)
  846. {
  847. int i;
  848. for (i = 0; i < ctx->nb_surfaces; i++) {
  849. if (!ctx->frames[i].locked) {
  850. ctx->frames[i].locked = 1;
  851. return &ctx->frames[i];
  852. }
  853. }
  854. return NULL;
  855. }
  856. static int nvenc_copy_frame(NV_ENC_LOCK_INPUT_BUFFER *in, const AVFrame *frame)
  857. {
  858. uint8_t *buf = in->bufferDataPtr;
  859. int off = frame->height * in->pitch;
  860. switch (frame->format) {
  861. case AV_PIX_FMT_YUV420P:
  862. av_image_copy_plane(buf, in->pitch,
  863. frame->data[0], frame->linesize[0],
  864. frame->width, frame->height);
  865. buf += off;
  866. av_image_copy_plane(buf, in->pitch >> 1,
  867. frame->data[2], frame->linesize[2],
  868. frame->width >> 1, frame->height >> 1);
  869. buf += off >> 2;
  870. av_image_copy_plane(buf, in->pitch >> 1,
  871. frame->data[1], frame->linesize[1],
  872. frame->width >> 1, frame->height >> 1);
  873. break;
  874. case AV_PIX_FMT_NV12:
  875. av_image_copy_plane(buf, in->pitch,
  876. frame->data[0], frame->linesize[0],
  877. frame->width, frame->height);
  878. buf += off;
  879. av_image_copy_plane(buf, in->pitch,
  880. frame->data[1], frame->linesize[1],
  881. frame->width, frame->height >> 1);
  882. break;
  883. case AV_PIX_FMT_YUV444P:
  884. av_image_copy_plane(buf, in->pitch,
  885. frame->data[0], frame->linesize[0],
  886. frame->width, frame->height);
  887. buf += off;
  888. av_image_copy_plane(buf, in->pitch,
  889. frame->data[1], frame->linesize[1],
  890. frame->width, frame->height);
  891. buf += off;
  892. av_image_copy_plane(buf, in->pitch,
  893. frame->data[2], frame->linesize[2],
  894. frame->width, frame->height);
  895. break;
  896. default:
  897. return AVERROR_BUG;
  898. }
  899. return 0;
  900. }
  901. static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
  902. {
  903. NVENCContext *ctx = avctx->priv_data;
  904. NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
  905. int i;
  906. if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
  907. for (i = 0; i < ctx->nb_registered_frames; i++) {
  908. if (!ctx->registered_frames[i].mapped) {
  909. if (ctx->registered_frames[i].regptr) {
  910. nv->nvEncUnregisterResource(ctx->nvenc_ctx,
  911. ctx->registered_frames[i].regptr);
  912. ctx->registered_frames[i].regptr = NULL;
  913. }
  914. return i;
  915. }
  916. }
  917. } else {
  918. return ctx->nb_registered_frames++;
  919. }
  920. av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
  921. return AVERROR(ENOMEM);
  922. }
  923. static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
  924. {
  925. NVENCContext *ctx = avctx->priv_data;
  926. NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
  927. AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  928. NV_ENC_REGISTER_RESOURCE reg;
  929. int i, idx, ret;
  930. for (i = 0; i < ctx->nb_registered_frames; i++) {
  931. if (ctx->registered_frames[i].ptr == (CUdeviceptr)frame->data[0])
  932. return i;
  933. }
  934. idx = nvenc_find_free_reg_resource(avctx);
  935. if (idx < 0)
  936. return idx;
  937. reg.version = NV_ENC_REGISTER_RESOURCE_VER;
  938. reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
  939. reg.width = frames_ctx->width;
  940. reg.height = frames_ctx->height;
  941. reg.bufferFormat = ctx->frames[0].format;
  942. reg.pitch = frame->linesize[0];
  943. reg.resourceToRegister = frame->data[0];
  944. ret = nv->nvEncRegisterResource(ctx->nvenc_ctx, &reg);
  945. if (ret != NV_ENC_SUCCESS) {
  946. nvenc_print_error(avctx, ret, "Error registering an input resource");
  947. return AVERROR_UNKNOWN;
  948. }
  949. ctx->registered_frames[idx].ptr = (CUdeviceptr)frame->data[0];
  950. ctx->registered_frames[idx].regptr = reg.registeredResource;
  951. return idx;
  952. }
  953. static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
  954. NVENCFrame *nvenc_frame)
  955. {
  956. NVENCContext *ctx = avctx->priv_data;
  957. NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
  958. int ret;
  959. if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
  960. int reg_idx;
  961. ret = nvenc_register_frame(avctx, frame);
  962. if (ret < 0) {
  963. av_log(avctx, AV_LOG_ERROR, "Could not register an input CUDA frame\n");
  964. return ret;
  965. }
  966. reg_idx = ret;
  967. ret = av_frame_ref(nvenc_frame->in_ref, frame);
  968. if (ret < 0)
  969. return ret;
  970. nvenc_frame->in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
  971. nvenc_frame->in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
  972. ret = nv->nvEncMapInputResource(ctx->nvenc_ctx, &nvenc_frame->in_map);
  973. if (ret != NV_ENC_SUCCESS) {
  974. av_frame_unref(nvenc_frame->in_ref);
  975. return nvenc_print_error(avctx, ret, "Error mapping an input resource");
  976. }
  977. ctx->registered_frames[reg_idx].mapped = 1;
  978. nvenc_frame->reg_idx = reg_idx;
  979. nvenc_frame->in = nvenc_frame->in_map.mappedResource;
  980. } else {
  981. NV_ENC_LOCK_INPUT_BUFFER params = { 0 };
  982. params.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
  983. params.inputBuffer = nvenc_frame->in;
  984. ret = nv->nvEncLockInputBuffer(ctx->nvenc_ctx, &params);
  985. if (ret != NV_ENC_SUCCESS)
  986. return nvenc_print_error(avctx, ret, "Cannot lock the buffer");
  987. ret = nvenc_copy_frame(&params, frame);
  988. if (ret < 0) {
  989. nv->nvEncUnlockInputBuffer(ctx->nvenc_ctx, nvenc_frame->in);
  990. return ret;
  991. }
  992. ret = nv->nvEncUnlockInputBuffer(ctx->nvenc_ctx, nvenc_frame->in);
  993. if (ret != NV_ENC_SUCCESS)
  994. return nvenc_print_error(avctx, ret, "Cannot unlock the buffer");
  995. }
  996. return 0;
  997. }
  998. static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
  999. NV_ENC_PIC_PARAMS *params)
  1000. {
  1001. NVENCContext *ctx = avctx->priv_data;
  1002. switch (avctx->codec->id) {
  1003. case AV_CODEC_ID_H264:
  1004. params->codecPicParams.h264PicParams.sliceMode =
  1005. ctx->config.encodeCodecConfig.h264Config.sliceMode;
  1006. params->codecPicParams.h264PicParams.sliceModeData =
  1007. ctx->config.encodeCodecConfig.h264Config.sliceModeData;
  1008. break;
  1009. case AV_CODEC_ID_HEVC:
  1010. params->codecPicParams.hevcPicParams.sliceMode =
  1011. ctx->config.encodeCodecConfig.hevcConfig.sliceMode;
  1012. params->codecPicParams.hevcPicParams.sliceModeData =
  1013. ctx->config.encodeCodecConfig.hevcConfig.sliceModeData;
  1014. break;
  1015. }
  1016. }
  1017. static inline int nvenc_enqueue_timestamp(AVFifoBuffer *f, int64_t pts)
  1018. {
  1019. return av_fifo_generic_write(f, &pts, sizeof(pts), NULL);
  1020. }
  1021. static inline int nvenc_dequeue_timestamp(AVFifoBuffer *f, int64_t *pts)
  1022. {
  1023. return av_fifo_generic_read(f, pts, sizeof(*pts), NULL);
  1024. }
  1025. static int nvenc_set_timestamp(AVCodecContext *avctx,
  1026. NV_ENC_LOCK_BITSTREAM *params,
  1027. AVPacket *pkt)
  1028. {
  1029. NVENCContext *ctx = avctx->priv_data;
  1030. pkt->pts = params->outputTimeStamp;
  1031. pkt->duration = params->outputDuration;
  1032. /* generate the first dts by linearly extrapolating the
  1033. * first two pts values to the past */
  1034. if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
  1035. ctx->initial_pts[1] != AV_NOPTS_VALUE) {
  1036. int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
  1037. int64_t delta;
  1038. if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
  1039. (ts0 > 0 && ts1 < INT64_MIN + ts0))
  1040. return AVERROR(ERANGE);
  1041. delta = ts1 - ts0;
  1042. if ((delta < 0 && ts0 > INT64_MAX + delta) ||
  1043. (delta > 0 && ts0 < INT64_MIN + delta))
  1044. return AVERROR(ERANGE);
  1045. pkt->dts = ts0 - delta;
  1046. ctx->first_packet_output = 1;
  1047. return 0;
  1048. }
  1049. return nvenc_dequeue_timestamp(ctx->timestamps, &pkt->dts);
  1050. }
  1051. static int nvenc_get_output(AVCodecContext *avctx, AVPacket *pkt)
  1052. {
  1053. NVENCContext *ctx = avctx->priv_data;
  1054. NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
  1055. NV_ENC_LOCK_BITSTREAM params = { 0 };
  1056. NVENCFrame *frame;
  1057. int ret;
  1058. ret = av_fifo_generic_read(ctx->ready, &frame, sizeof(frame), NULL);
  1059. if (ret)
  1060. return ret;
  1061. params.version = NV_ENC_LOCK_BITSTREAM_VER;
  1062. params.outputBitstream = frame->out;
  1063. ret = nv->nvEncLockBitstream(ctx->nvenc_ctx, &params);
  1064. if (ret < 0)
  1065. return nvenc_print_error(avctx, ret, "Cannot lock the bitstream");
  1066. ret = ff_alloc_packet(pkt, params.bitstreamSizeInBytes);
  1067. if (ret < 0)
  1068. return ret;
  1069. memcpy(pkt->data, params.bitstreamBufferPtr, pkt->size);
  1070. ret = nv->nvEncUnlockBitstream(ctx->nvenc_ctx, frame->out);
  1071. if (ret < 0)
  1072. return nvenc_print_error(avctx, ret, "Cannot unlock the bitstream");
  1073. if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
  1074. nv->nvEncUnmapInputResource(ctx->nvenc_ctx, frame->in_map.mappedResource);
  1075. av_frame_unref(frame->in_ref);
  1076. ctx->registered_frames[frame->reg_idx].mapped = 0;
  1077. frame->in = NULL;
  1078. }
  1079. frame->locked = 0;
  1080. ret = nvenc_set_timestamp(avctx, &params, pkt);
  1081. if (ret < 0)
  1082. return ret;
  1083. switch (params.pictureType) {
  1084. case NV_ENC_PIC_TYPE_IDR:
  1085. pkt->flags |= AV_PKT_FLAG_KEY;
  1086. #if FF_API_CODED_FRAME
  1087. FF_DISABLE_DEPRECATION_WARNINGS
  1088. case NV_ENC_PIC_TYPE_INTRA_REFRESH:
  1089. case NV_ENC_PIC_TYPE_I:
  1090. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
  1091. break;
  1092. case NV_ENC_PIC_TYPE_P:
  1093. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
  1094. break;
  1095. case NV_ENC_PIC_TYPE_B:
  1096. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;
  1097. break;
  1098. case NV_ENC_PIC_TYPE_BI:
  1099. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_BI;
  1100. break;
  1101. FF_ENABLE_DEPRECATION_WARNINGS
  1102. #endif
  1103. }
  1104. return 0;
  1105. }
  1106. static int output_ready(AVCodecContext *avctx, int flush)
  1107. {
  1108. NVENCContext *ctx = avctx->priv_data;
  1109. int nb_ready, nb_pending;
  1110. /* when B-frames are enabled, we wait for two initial timestamps to
  1111. * calculate the first dts */
  1112. if (!flush && avctx->max_b_frames > 0 &&
  1113. (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
  1114. return 0;
  1115. nb_ready = av_fifo_size(ctx->ready) / sizeof(NVENCFrame*);
  1116. nb_pending = av_fifo_size(ctx->pending) / sizeof(NVENCFrame*);
  1117. if (flush)
  1118. return nb_ready > 0;
  1119. return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
  1120. }
  1121. int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
  1122. const AVFrame *frame, int *got_packet)
  1123. {
  1124. NVENCContext *ctx = avctx->priv_data;
  1125. NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
  1126. NV_ENC_PIC_PARAMS params = { 0 };
  1127. NVENCFrame *nvenc_frame = NULL;
  1128. int enc_ret, ret;
  1129. params.version = NV_ENC_PIC_PARAMS_VER;
  1130. if (frame) {
  1131. nvenc_frame = get_free_frame(ctx);
  1132. if (!nvenc_frame) {
  1133. av_log(avctx, AV_LOG_ERROR, "No free surfaces\n");
  1134. return AVERROR_BUG;
  1135. }
  1136. ret = nvenc_upload_frame(avctx, frame, nvenc_frame);
  1137. if (ret < 0)
  1138. return ret;
  1139. params.inputBuffer = nvenc_frame->in;
  1140. params.bufferFmt = nvenc_frame->format;
  1141. params.inputWidth = frame->width;
  1142. params.inputHeight = frame->height;
  1143. params.outputBitstream = nvenc_frame->out;
  1144. params.inputTimeStamp = frame->pts;
  1145. if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
  1146. if (frame->top_field_first)
  1147. params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
  1148. else
  1149. params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
  1150. } else {
  1151. params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
  1152. }
  1153. nvenc_codec_specific_pic_params(avctx, &params);
  1154. ret = nvenc_enqueue_timestamp(ctx->timestamps, frame->pts);
  1155. if (ret < 0)
  1156. return ret;
  1157. if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
  1158. ctx->initial_pts[0] = frame->pts;
  1159. else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
  1160. ctx->initial_pts[1] = frame->pts;
  1161. } else {
  1162. params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
  1163. }
  1164. enc_ret = nv->nvEncEncodePicture(ctx->nvenc_ctx, &params);
  1165. if (enc_ret != NV_ENC_SUCCESS &&
  1166. enc_ret != NV_ENC_ERR_NEED_MORE_INPUT)
  1167. return nvenc_print_error(avctx, enc_ret, "Error encoding the frame");
  1168. if (nvenc_frame) {
  1169. ret = av_fifo_generic_write(ctx->pending, &nvenc_frame, sizeof(nvenc_frame), NULL);
  1170. if (ret < 0)
  1171. return ret;
  1172. }
  1173. /* all the pending buffers are now ready for output */
  1174. if (enc_ret == NV_ENC_SUCCESS) {
  1175. while (av_fifo_size(ctx->pending) > 0) {
  1176. av_fifo_generic_read(ctx->pending, &nvenc_frame, sizeof(nvenc_frame), NULL);
  1177. av_fifo_generic_write(ctx->ready, &nvenc_frame, sizeof(nvenc_frame), NULL);
  1178. }
  1179. }
  1180. if (output_ready(avctx, !frame)) {
  1181. ret = nvenc_get_output(avctx, pkt);
  1182. if (ret < 0)
  1183. return ret;
  1184. *got_packet = 1;
  1185. } else {
  1186. *got_packet = 0;
  1187. }
  1188. return 0;
  1189. }