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.

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