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.

1565 lines
52KB

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