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.

1380 lines
44KB

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