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.

1240 lines
38KB

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