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.

1701 lines
58KB

  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. #if defined(_WIN32)
  22. #include <windows.h>
  23. #else
  24. #include <dlfcn.h>
  25. #endif
  26. #include <nvEncodeAPI.h>
  27. #include "libavutil/fifo.h"
  28. #include "libavutil/internal.h"
  29. #include "libavutil/imgutils.h"
  30. #include "libavutil/avassert.h"
  31. #include "libavutil/opt.h"
  32. #include "libavutil/mem.h"
  33. #include "avcodec.h"
  34. #include "internal.h"
  35. #include "thread.h"
  36. #if defined(_WIN32)
  37. #define CUDAAPI __stdcall
  38. #else
  39. #define CUDAAPI
  40. #endif
  41. #if defined(_WIN32)
  42. #define LOAD_FUNC(l, s) GetProcAddress(l, s)
  43. #define DL_CLOSE_FUNC(l) FreeLibrary(l)
  44. #else
  45. #define LOAD_FUNC(l, s) dlsym(l, s)
  46. #define DL_CLOSE_FUNC(l) dlclose(l)
  47. #endif
  48. typedef enum cudaError_enum {
  49. CUDA_SUCCESS = 0
  50. } CUresult;
  51. typedef int CUdevice;
  52. typedef void* CUcontext;
  53. typedef CUresult(CUDAAPI *PCUINIT)(unsigned int Flags);
  54. typedef CUresult(CUDAAPI *PCUDEVICEGETCOUNT)(int *count);
  55. typedef CUresult(CUDAAPI *PCUDEVICEGET)(CUdevice *device, int ordinal);
  56. typedef CUresult(CUDAAPI *PCUDEVICEGETNAME)(char *name, int len, CUdevice dev);
  57. typedef CUresult(CUDAAPI *PCUDEVICECOMPUTECAPABILITY)(int *major, int *minor, CUdevice dev);
  58. typedef CUresult(CUDAAPI *PCUCTXCREATE)(CUcontext *pctx, unsigned int flags, CUdevice dev);
  59. typedef CUresult(CUDAAPI *PCUCTXPOPCURRENT)(CUcontext *pctx);
  60. typedef CUresult(CUDAAPI *PCUCTXDESTROY)(CUcontext ctx);
  61. typedef NVENCSTATUS (NVENCAPI* PNVENCODEAPICREATEINSTANCE)(NV_ENCODE_API_FUNCTION_LIST *functionList);
  62. typedef struct NvencSurface
  63. {
  64. NV_ENC_INPUT_PTR input_surface;
  65. int width;
  66. int height;
  67. int lockCount;
  68. NV_ENC_BUFFER_FORMAT format;
  69. NV_ENC_OUTPUT_PTR output_surface;
  70. int size;
  71. } NvencSurface;
  72. typedef struct NvencData
  73. {
  74. union {
  75. int64_t timestamp;
  76. NvencSurface *surface;
  77. } u;
  78. } NvencData;
  79. typedef struct NvencDynLoadFunctions
  80. {
  81. PCUINIT cu_init;
  82. PCUDEVICEGETCOUNT cu_device_get_count;
  83. PCUDEVICEGET cu_device_get;
  84. PCUDEVICEGETNAME cu_device_get_name;
  85. PCUDEVICECOMPUTECAPABILITY cu_device_compute_capability;
  86. PCUCTXCREATE cu_ctx_create;
  87. PCUCTXPOPCURRENT cu_ctx_pop_current;
  88. PCUCTXDESTROY cu_ctx_destroy;
  89. NV_ENCODE_API_FUNCTION_LIST nvenc_funcs;
  90. int nvenc_device_count;
  91. CUdevice nvenc_devices[16];
  92. #if defined(_WIN32)
  93. HMODULE cuda_lib;
  94. HMODULE nvenc_lib;
  95. #else
  96. void* cuda_lib;
  97. void* nvenc_lib;
  98. #endif
  99. } NvencDynLoadFunctions;
  100. typedef struct NvencValuePair
  101. {
  102. const char *str;
  103. uint32_t num;
  104. } NvencValuePair;
  105. typedef struct NvencContext
  106. {
  107. AVClass *avclass;
  108. NvencDynLoadFunctions nvenc_dload_funcs;
  109. NV_ENC_INITIALIZE_PARAMS init_encode_params;
  110. NV_ENC_CONFIG encode_config;
  111. CUcontext cu_context;
  112. int max_surface_count;
  113. NvencSurface *surfaces;
  114. AVFifoBuffer *output_surface_queue;
  115. AVFifoBuffer *output_surface_ready_queue;
  116. AVFifoBuffer *timestamp_list;
  117. int64_t last_dts;
  118. void *nvencoder;
  119. char *preset;
  120. char *profile;
  121. char *level;
  122. char *tier;
  123. int cbr;
  124. int twopass;
  125. int gpu;
  126. int buffer_delay;
  127. } NvencContext;
  128. static const NvencValuePair nvenc_h264_level_pairs[] = {
  129. { "auto", NV_ENC_LEVEL_AUTOSELECT },
  130. { "1" , NV_ENC_LEVEL_H264_1 },
  131. { "1.0" , NV_ENC_LEVEL_H264_1 },
  132. { "1b" , NV_ENC_LEVEL_H264_1b },
  133. { "1.0b", NV_ENC_LEVEL_H264_1b },
  134. { "1.1" , NV_ENC_LEVEL_H264_11 },
  135. { "1.2" , NV_ENC_LEVEL_H264_12 },
  136. { "1.3" , NV_ENC_LEVEL_H264_13 },
  137. { "2" , NV_ENC_LEVEL_H264_2 },
  138. { "2.0" , NV_ENC_LEVEL_H264_2 },
  139. { "2.1" , NV_ENC_LEVEL_H264_21 },
  140. { "2.2" , NV_ENC_LEVEL_H264_22 },
  141. { "3" , NV_ENC_LEVEL_H264_3 },
  142. { "3.0" , NV_ENC_LEVEL_H264_3 },
  143. { "3.1" , NV_ENC_LEVEL_H264_31 },
  144. { "3.2" , NV_ENC_LEVEL_H264_32 },
  145. { "4" , NV_ENC_LEVEL_H264_4 },
  146. { "4.0" , NV_ENC_LEVEL_H264_4 },
  147. { "4.1" , NV_ENC_LEVEL_H264_41 },
  148. { "4.2" , NV_ENC_LEVEL_H264_42 },
  149. { "5" , NV_ENC_LEVEL_H264_5 },
  150. { "5.0" , NV_ENC_LEVEL_H264_5 },
  151. { "5.1" , NV_ENC_LEVEL_H264_51 },
  152. { NULL }
  153. };
  154. static const NvencValuePair nvenc_hevc_level_pairs[] = {
  155. { "auto", NV_ENC_LEVEL_AUTOSELECT },
  156. { "1" , NV_ENC_LEVEL_HEVC_1 },
  157. { "1.0" , NV_ENC_LEVEL_HEVC_1 },
  158. { "2" , NV_ENC_LEVEL_HEVC_2 },
  159. { "2.0" , NV_ENC_LEVEL_HEVC_2 },
  160. { "2.1" , NV_ENC_LEVEL_HEVC_21 },
  161. { "3" , NV_ENC_LEVEL_HEVC_3 },
  162. { "3.0" , NV_ENC_LEVEL_HEVC_3 },
  163. { "3.1" , NV_ENC_LEVEL_HEVC_31 },
  164. { "4" , NV_ENC_LEVEL_HEVC_4 },
  165. { "4.0" , NV_ENC_LEVEL_HEVC_4 },
  166. { "4.1" , NV_ENC_LEVEL_HEVC_41 },
  167. { "5" , NV_ENC_LEVEL_HEVC_5 },
  168. { "5.0" , NV_ENC_LEVEL_HEVC_5 },
  169. { "5.1" , NV_ENC_LEVEL_HEVC_51 },
  170. { "5.2" , NV_ENC_LEVEL_HEVC_52 },
  171. { "6" , NV_ENC_LEVEL_HEVC_6 },
  172. { "6.0" , NV_ENC_LEVEL_HEVC_6 },
  173. { "6.1" , NV_ENC_LEVEL_HEVC_61 },
  174. { "6.2" , NV_ENC_LEVEL_HEVC_62 },
  175. { NULL }
  176. };
  177. static const struct {
  178. NVENCSTATUS nverr;
  179. int averr;
  180. const char *desc;
  181. } nvenc_errors[] = {
  182. { NV_ENC_SUCCESS, 0, "success" },
  183. { NV_ENC_ERR_NO_ENCODE_DEVICE, AVERROR(ENOENT), "no encode device" },
  184. { NV_ENC_ERR_UNSUPPORTED_DEVICE, AVERROR(ENOSYS), "unsupported device" },
  185. { NV_ENC_ERR_INVALID_ENCODERDEVICE, AVERROR(EINVAL), "invalid encoder device" },
  186. { NV_ENC_ERR_INVALID_DEVICE, AVERROR(EINVAL), "invalid device" },
  187. { NV_ENC_ERR_DEVICE_NOT_EXIST, AVERROR(EIO), "device does not exist" },
  188. { NV_ENC_ERR_INVALID_PTR, AVERROR(EFAULT), "invalid ptr" },
  189. { NV_ENC_ERR_INVALID_EVENT, AVERROR(EINVAL), "invalid event" },
  190. { NV_ENC_ERR_INVALID_PARAM, AVERROR(EINVAL), "invalid param" },
  191. { NV_ENC_ERR_INVALID_CALL, AVERROR(EINVAL), "invalid call" },
  192. { NV_ENC_ERR_OUT_OF_MEMORY, AVERROR(ENOMEM), "out of memory" },
  193. { NV_ENC_ERR_ENCODER_NOT_INITIALIZED, AVERROR(EINVAL), "encoder not initialized" },
  194. { NV_ENC_ERR_UNSUPPORTED_PARAM, AVERROR(ENOSYS), "unsupported param" },
  195. { NV_ENC_ERR_LOCK_BUSY, AVERROR(EAGAIN), "lock busy" },
  196. { NV_ENC_ERR_NOT_ENOUGH_BUFFER, AVERROR(ENOBUFS), "not enough buffer" },
  197. { NV_ENC_ERR_INVALID_VERSION, AVERROR(EINVAL), "invalid version" },
  198. { NV_ENC_ERR_MAP_FAILED, AVERROR(EIO), "map failed" },
  199. { NV_ENC_ERR_NEED_MORE_INPUT, AVERROR(EAGAIN), "need more input" },
  200. { NV_ENC_ERR_ENCODER_BUSY, AVERROR(EAGAIN), "encoder busy" },
  201. { NV_ENC_ERR_EVENT_NOT_REGISTERD, AVERROR(EBADF), "event not registered" },
  202. { NV_ENC_ERR_GENERIC, AVERROR_UNKNOWN, "generic error" },
  203. { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY, AVERROR(EINVAL), "incompatible client key" },
  204. { NV_ENC_ERR_UNIMPLEMENTED, AVERROR(ENOSYS), "unimplemented" },
  205. { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO), "resource register failed" },
  206. { NV_ENC_ERR_RESOURCE_NOT_REGISTERED, AVERROR(EBADF), "resource not registered" },
  207. { NV_ENC_ERR_RESOURCE_NOT_MAPPED, AVERROR(EBADF), "resource not mapped" },
  208. };
  209. static int nvenc_map_error(NVENCSTATUS err, const char **desc)
  210. {
  211. int i;
  212. for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
  213. if (nvenc_errors[i].nverr == err) {
  214. if (desc)
  215. *desc = nvenc_errors[i].desc;
  216. return nvenc_errors[i].averr;
  217. }
  218. }
  219. if (desc)
  220. *desc = "unknown error";
  221. return AVERROR_UNKNOWN;
  222. }
  223. static int nvenc_print_error(void *log_ctx, NVENCSTATUS err,
  224. const char *error_string)
  225. {
  226. const char *desc;
  227. int ret;
  228. ret = nvenc_map_error(err, &desc);
  229. av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
  230. return ret;
  231. }
  232. static int input_string_to_uint32(AVCodecContext *avctx, const NvencValuePair *pair, const char *input, uint32_t *output)
  233. {
  234. for (; pair->str; ++pair) {
  235. if (!strcmp(input, pair->str)) {
  236. *output = pair->num;
  237. return 0;
  238. }
  239. }
  240. return AVERROR(EINVAL);
  241. }
  242. static void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
  243. {
  244. av_fifo_generic_write(queue, &timestamp, sizeof(timestamp), NULL);
  245. }
  246. static int64_t timestamp_queue_dequeue(AVFifoBuffer* queue)
  247. {
  248. int64_t timestamp = AV_NOPTS_VALUE;
  249. if (av_fifo_size(queue) > 0)
  250. av_fifo_generic_read(queue, &timestamp, sizeof(timestamp), NULL);
  251. return timestamp;
  252. }
  253. #define CHECK_LOAD_FUNC(t, f, s) \
  254. do { \
  255. (f) = (t)LOAD_FUNC(dl_fn->cuda_lib, s); \
  256. if (!(f)) { \
  257. av_log(avctx, AV_LOG_FATAL, "Failed loading %s from CUDA library\n", s); \
  258. goto error; \
  259. } \
  260. } while (0)
  261. static av_cold int nvenc_dyload_cuda(AVCodecContext *avctx)
  262. {
  263. NvencContext *ctx = avctx->priv_data;
  264. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  265. if (dl_fn->cuda_lib)
  266. return 1;
  267. #if defined(_WIN32)
  268. dl_fn->cuda_lib = LoadLibrary(TEXT("nvcuda.dll"));
  269. #else
  270. dl_fn->cuda_lib = dlopen("libcuda.so", RTLD_LAZY);
  271. #endif
  272. if (!dl_fn->cuda_lib) {
  273. av_log(avctx, AV_LOG_FATAL, "Failed loading CUDA library\n");
  274. goto error;
  275. }
  276. CHECK_LOAD_FUNC(PCUINIT, dl_fn->cu_init, "cuInit");
  277. CHECK_LOAD_FUNC(PCUDEVICEGETCOUNT, dl_fn->cu_device_get_count, "cuDeviceGetCount");
  278. CHECK_LOAD_FUNC(PCUDEVICEGET, dl_fn->cu_device_get, "cuDeviceGet");
  279. CHECK_LOAD_FUNC(PCUDEVICEGETNAME, dl_fn->cu_device_get_name, "cuDeviceGetName");
  280. CHECK_LOAD_FUNC(PCUDEVICECOMPUTECAPABILITY, dl_fn->cu_device_compute_capability, "cuDeviceComputeCapability");
  281. CHECK_LOAD_FUNC(PCUCTXCREATE, dl_fn->cu_ctx_create, "cuCtxCreate_v2");
  282. CHECK_LOAD_FUNC(PCUCTXPOPCURRENT, dl_fn->cu_ctx_pop_current, "cuCtxPopCurrent_v2");
  283. CHECK_LOAD_FUNC(PCUCTXDESTROY, dl_fn->cu_ctx_destroy, "cuCtxDestroy_v2");
  284. return 1;
  285. error:
  286. if (dl_fn->cuda_lib)
  287. DL_CLOSE_FUNC(dl_fn->cuda_lib);
  288. dl_fn->cuda_lib = NULL;
  289. return 0;
  290. }
  291. static av_cold int check_cuda_errors(AVCodecContext *avctx, CUresult err, const char *func)
  292. {
  293. if (err != CUDA_SUCCESS) {
  294. av_log(avctx, AV_LOG_FATAL, ">> %s - failed with error code 0x%x\n", func, err);
  295. return 0;
  296. }
  297. return 1;
  298. }
  299. #define check_cuda_errors(f) if (!check_cuda_errors(avctx, f, #f)) goto error
  300. static av_cold int nvenc_check_cuda(AVCodecContext *avctx)
  301. {
  302. int device_count = 0;
  303. CUdevice cu_device = 0;
  304. char gpu_name[128];
  305. int smminor = 0, smmajor = 0;
  306. int i, smver, target_smver;
  307. NvencContext *ctx = avctx->priv_data;
  308. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  309. switch (avctx->codec->id) {
  310. case AV_CODEC_ID_H264:
  311. target_smver = avctx->pix_fmt == AV_PIX_FMT_YUV444P ? 0x52 : 0x30;
  312. break;
  313. case AV_CODEC_ID_H265:
  314. target_smver = 0x52;
  315. break;
  316. default:
  317. av_log(avctx, AV_LOG_FATAL, "Unknown codec name\n");
  318. goto error;
  319. }
  320. if (!nvenc_dyload_cuda(avctx))
  321. return 0;
  322. if (dl_fn->nvenc_device_count > 0)
  323. return 1;
  324. check_cuda_errors(dl_fn->cu_init(0));
  325. check_cuda_errors(dl_fn->cu_device_get_count(&device_count));
  326. if (!device_count) {
  327. av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
  328. goto error;
  329. }
  330. av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", device_count);
  331. dl_fn->nvenc_device_count = 0;
  332. for (i = 0; i < device_count; ++i) {
  333. check_cuda_errors(dl_fn->cu_device_get(&cu_device, i));
  334. check_cuda_errors(dl_fn->cu_device_get_name(gpu_name, sizeof(gpu_name), cu_device));
  335. check_cuda_errors(dl_fn->cu_device_compute_capability(&smmajor, &smminor, cu_device));
  336. smver = (smmajor << 4) | smminor;
  337. 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");
  338. if (smver >= target_smver)
  339. dl_fn->nvenc_devices[dl_fn->nvenc_device_count++] = cu_device;
  340. }
  341. if (!dl_fn->nvenc_device_count) {
  342. av_log(avctx, AV_LOG_FATAL, "No NVENC capable devices found\n");
  343. goto error;
  344. }
  345. return 1;
  346. error:
  347. dl_fn->nvenc_device_count = 0;
  348. return 0;
  349. }
  350. static av_cold int nvenc_dyload_nvenc(AVCodecContext *avctx)
  351. {
  352. PNVENCODEAPICREATEINSTANCE nvEncodeAPICreateInstance = 0;
  353. NVENCSTATUS nvstatus;
  354. NvencContext *ctx = avctx->priv_data;
  355. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  356. if (!nvenc_check_cuda(avctx))
  357. return 0;
  358. if (dl_fn->nvenc_lib)
  359. return 1;
  360. #if defined(_WIN32)
  361. if (sizeof(void*) == 8) {
  362. dl_fn->nvenc_lib = LoadLibrary(TEXT("nvEncodeAPI64.dll"));
  363. } else {
  364. dl_fn->nvenc_lib = LoadLibrary(TEXT("nvEncodeAPI.dll"));
  365. }
  366. #else
  367. dl_fn->nvenc_lib = dlopen("libnvidia-encode.so.1", RTLD_LAZY);
  368. #endif
  369. if (!dl_fn->nvenc_lib) {
  370. av_log(avctx, AV_LOG_FATAL, "Failed loading the nvenc library\n");
  371. goto error;
  372. }
  373. nvEncodeAPICreateInstance = (PNVENCODEAPICREATEINSTANCE)LOAD_FUNC(dl_fn->nvenc_lib, "NvEncodeAPICreateInstance");
  374. if (!nvEncodeAPICreateInstance) {
  375. av_log(avctx, AV_LOG_FATAL, "Failed to load nvenc entrypoint\n");
  376. goto error;
  377. }
  378. dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
  379. nvstatus = nvEncodeAPICreateInstance(&dl_fn->nvenc_funcs);
  380. if (nvstatus != NV_ENC_SUCCESS) {
  381. nvenc_print_error(avctx, nvstatus, "Failed to create nvenc instance");
  382. goto error;
  383. }
  384. av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
  385. return 1;
  386. error:
  387. if (dl_fn->nvenc_lib)
  388. DL_CLOSE_FUNC(dl_fn->nvenc_lib);
  389. dl_fn->nvenc_lib = NULL;
  390. return 0;
  391. }
  392. static av_cold void nvenc_unload_nvenc(AVCodecContext *avctx)
  393. {
  394. NvencContext *ctx = avctx->priv_data;
  395. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  396. DL_CLOSE_FUNC(dl_fn->nvenc_lib);
  397. dl_fn->nvenc_lib = NULL;
  398. dl_fn->nvenc_device_count = 0;
  399. DL_CLOSE_FUNC(dl_fn->cuda_lib);
  400. dl_fn->cuda_lib = NULL;
  401. dl_fn->cu_init = NULL;
  402. dl_fn->cu_device_get_count = NULL;
  403. dl_fn->cu_device_get = NULL;
  404. dl_fn->cu_device_get_name = NULL;
  405. dl_fn->cu_device_compute_capability = NULL;
  406. dl_fn->cu_ctx_create = NULL;
  407. dl_fn->cu_ctx_pop_current = NULL;
  408. dl_fn->cu_ctx_destroy = NULL;
  409. av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
  410. }
  411. static av_cold int nvenc_setup_device(AVCodecContext *avctx)
  412. {
  413. NvencContext *ctx = avctx->priv_data;
  414. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  415. CUresult cu_res;
  416. CUcontext cu_context_curr;
  417. if (ctx->gpu >= dl_fn->nvenc_device_count) {
  418. av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->gpu, dl_fn->nvenc_device_count);
  419. return AVERROR(EINVAL);
  420. }
  421. ctx->cu_context = NULL;
  422. cu_res = dl_fn->cu_ctx_create(&ctx->cu_context, 4, dl_fn->nvenc_devices[ctx->gpu]); // CU_CTX_SCHED_BLOCKING_SYNC=4, avoid CPU spins
  423. if (cu_res != CUDA_SUCCESS) {
  424. av_log(avctx, AV_LOG_FATAL, "Failed creating CUDA context for NVENC: 0x%x\n", (int)cu_res);
  425. return AVERROR_EXTERNAL;
  426. }
  427. cu_res = dl_fn->cu_ctx_pop_current(&cu_context_curr);
  428. if (cu_res != CUDA_SUCCESS) {
  429. av_log(avctx, AV_LOG_FATAL, "Failed popping CUDA context: 0x%x\n", (int)cu_res);
  430. return AVERROR_EXTERNAL;
  431. }
  432. return 0;
  433. }
  434. static av_cold int nvenc_open_session(AVCodecContext *avctx)
  435. {
  436. NvencContext *ctx = avctx->priv_data;
  437. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  438. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  439. NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS encode_session_params = { 0 };
  440. NVENCSTATUS nv_status;
  441. encode_session_params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
  442. encode_session_params.apiVersion = NVENCAPI_VERSION;
  443. encode_session_params.device = ctx->cu_context;
  444. encode_session_params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
  445. nv_status = p_nvenc->nvEncOpenEncodeSessionEx(&encode_session_params, &ctx->nvencoder);
  446. if (nv_status != NV_ENC_SUCCESS) {
  447. ctx->nvencoder = NULL;
  448. return nvenc_print_error(avctx, nv_status, "OpenEncodeSessionEx failed");
  449. }
  450. return 0;
  451. }
  452. static av_cold void set_constqp(AVCodecContext *avctx)
  453. {
  454. NvencContext *ctx = avctx->priv_data;
  455. ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
  456. ctx->encode_config.rcParams.constQP.qpInterB = avctx->global_quality;
  457. ctx->encode_config.rcParams.constQP.qpInterP = avctx->global_quality;
  458. ctx->encode_config.rcParams.constQP.qpIntra = avctx->global_quality;
  459. }
  460. static av_cold void set_vbr(AVCodecContext *avctx)
  461. {
  462. NvencContext *ctx = avctx->priv_data;
  463. ctx->encode_config.rcParams.enableMinQP = 1;
  464. ctx->encode_config.rcParams.enableMaxQP = 1;
  465. ctx->encode_config.rcParams.minQP.qpInterB = avctx->qmin;
  466. ctx->encode_config.rcParams.minQP.qpInterP = avctx->qmin;
  467. ctx->encode_config.rcParams.minQP.qpIntra = avctx->qmin;
  468. ctx->encode_config.rcParams.maxQP.qpInterB = avctx->qmax;
  469. ctx->encode_config.rcParams.maxQP.qpInterP = avctx->qmax;
  470. ctx->encode_config.rcParams.maxQP.qpIntra = avctx->qmax;
  471. }
  472. static av_cold void set_lossless(AVCodecContext *avctx)
  473. {
  474. NvencContext *ctx = avctx->priv_data;
  475. ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
  476. ctx->encode_config.rcParams.constQP.qpInterB = 0;
  477. ctx->encode_config.rcParams.constQP.qpInterP = 0;
  478. ctx->encode_config.rcParams.constQP.qpIntra = 0;
  479. }
  480. static av_cold void nvenc_setup_rate_control(AVCodecContext *avctx, int lossless)
  481. {
  482. NvencContext *ctx = avctx->priv_data;
  483. int qp_inter_p;
  484. if (avctx->bit_rate > 0) {
  485. ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
  486. } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
  487. ctx->encode_config.rcParams.maxBitRate = ctx->encode_config.rcParams.averageBitRate;
  488. }
  489. if (avctx->rc_max_rate > 0)
  490. ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
  491. if (lossless) {
  492. if (avctx->codec->id == AV_CODEC_ID_H264)
  493. ctx->encode_config.encodeCodecConfig.h264Config.qpPrimeYZeroTransformBypassFlag = 1;
  494. set_lossless(avctx);
  495. avctx->qmin = -1;
  496. avctx->qmax = -1;
  497. } else if (ctx->cbr) {
  498. if (!ctx->twopass) {
  499. ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_CBR;
  500. } else {
  501. ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_2_PASS_QUALITY;
  502. if (avctx->codec->id == AV_CODEC_ID_H264) {
  503. ctx->encode_config.encodeCodecConfig.h264Config.adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
  504. ctx->encode_config.encodeCodecConfig.h264Config.fmoMode = NV_ENC_H264_FMO_DISABLE;
  505. }
  506. }
  507. if (avctx->codec->id == AV_CODEC_ID_H264) {
  508. ctx->encode_config.encodeCodecConfig.h264Config.outputBufferingPeriodSEI = 1;
  509. ctx->encode_config.encodeCodecConfig.h264Config.outputPictureTimingSEI = 1;
  510. } else if (avctx->codec->id == AV_CODEC_ID_H265) {
  511. ctx->encode_config.encodeCodecConfig.hevcConfig.outputBufferingPeriodSEI = 1;
  512. ctx->encode_config.encodeCodecConfig.hevcConfig.outputPictureTimingSEI = 1;
  513. }
  514. } else if (avctx->global_quality > 0) {
  515. set_constqp(avctx);
  516. avctx->qmin = -1;
  517. avctx->qmax = -1;
  518. } else {
  519. if (avctx->qmin >= 0 && avctx->qmax >= 0) {
  520. set_vbr(avctx);
  521. qp_inter_p = (avctx->qmax + 3 * avctx->qmin) / 4; // biased towards Qmin
  522. if (ctx->twopass) {
  523. ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_2_PASS_VBR;
  524. if (avctx->codec->id == AV_CODEC_ID_H264) {
  525. ctx->encode_config.encodeCodecConfig.h264Config.adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
  526. ctx->encode_config.encodeCodecConfig.h264Config.fmoMode = NV_ENC_H264_FMO_DISABLE;
  527. }
  528. } else {
  529. ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR_MINQP;
  530. }
  531. } else {
  532. qp_inter_p = 26; // default to 26
  533. if (ctx->twopass) {
  534. ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_2_PASS_VBR;
  535. } else {
  536. ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
  537. }
  538. }
  539. ctx->encode_config.rcParams.enableInitialRCQP = 1;
  540. ctx->encode_config.rcParams.initialRCQP.qpInterP = qp_inter_p;
  541. if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
  542. ctx->encode_config.rcParams.initialRCQP.qpIntra = av_clip(
  543. qp_inter_p * fabs(avctx->i_quant_factor) + avctx->i_quant_offset, 0, 51);
  544. ctx->encode_config.rcParams.initialRCQP.qpInterB = av_clip(
  545. qp_inter_p * fabs(avctx->b_quant_factor) + avctx->b_quant_offset, 0, 51);
  546. } else {
  547. ctx->encode_config.rcParams.initialRCQP.qpIntra = qp_inter_p;
  548. ctx->encode_config.rcParams.initialRCQP.qpInterB = qp_inter_p;
  549. }
  550. }
  551. if (avctx->rc_buffer_size > 0) {
  552. ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
  553. } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
  554. ctx->encode_config.rcParams.vbvBufferSize = 2 * ctx->encode_config.rcParams.averageBitRate;
  555. }
  556. }
  557. static av_cold int nvenc_setup_h264_config(AVCodecContext *avctx, int lossless)
  558. {
  559. NvencContext *ctx = avctx->priv_data;
  560. int res;
  561. ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.colourMatrix = avctx->colorspace;
  562. ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.colourPrimaries = avctx->color_primaries;
  563. ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.transferCharacteristics = avctx->color_trc;
  564. ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
  565. || avctx->pix_fmt == AV_PIX_FMT_YUVJ420P || avctx->pix_fmt == AV_PIX_FMT_YUVJ422P || avctx->pix_fmt == AV_PIX_FMT_YUVJ444P);
  566. ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.colourDescriptionPresentFlag =
  567. (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
  568. ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.videoSignalTypePresentFlag =
  569. (ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.colourDescriptionPresentFlag
  570. || ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.videoFormat != 5
  571. || ctx->encode_config.encodeCodecConfig.h264Config.h264VUIParameters.videoFullRangeFlag != 0);
  572. ctx->encode_config.encodeCodecConfig.h264Config.sliceMode = 3;
  573. ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData = 1;
  574. ctx->encode_config.encodeCodecConfig.h264Config.disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
  575. ctx->encode_config.encodeCodecConfig.h264Config.repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
  576. ctx->encode_config.encodeCodecConfig.h264Config.outputAUD = 1;
  577. if (!ctx->profile && !lossless) {
  578. switch (avctx->profile) {
  579. case FF_PROFILE_H264_HIGH_444_PREDICTIVE:
  580. ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
  581. break;
  582. case FF_PROFILE_H264_BASELINE:
  583. ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
  584. break;
  585. case FF_PROFILE_H264_MAIN:
  586. ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
  587. break;
  588. case FF_PROFILE_H264_HIGH:
  589. case FF_PROFILE_UNKNOWN:
  590. ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
  591. break;
  592. default:
  593. av_log(avctx, AV_LOG_WARNING, "Unsupported profile requested, falling back to high\n");
  594. ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
  595. break;
  596. }
  597. } else if (!lossless) {
  598. if (!strcmp(ctx->profile, "high")) {
  599. ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
  600. avctx->profile = FF_PROFILE_H264_HIGH;
  601. } else if (!strcmp(ctx->profile, "main")) {
  602. ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
  603. avctx->profile = FF_PROFILE_H264_MAIN;
  604. } else if (!strcmp(ctx->profile, "baseline")) {
  605. ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
  606. avctx->profile = FF_PROFILE_H264_BASELINE;
  607. } else if (!strcmp(ctx->profile, "high444p")) {
  608. ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
  609. avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
  610. } else {
  611. av_log(avctx, AV_LOG_FATAL, "Profile \"%s\" is unknown! Supported profiles: high, main, baseline\n", ctx->profile);
  612. return AVERROR(EINVAL);
  613. }
  614. }
  615. // force setting profile as high444p if input is AV_PIX_FMT_YUV444P
  616. if (avctx->pix_fmt == AV_PIX_FMT_YUV444P) {
  617. ctx->encode_config.profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
  618. avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
  619. }
  620. ctx->encode_config.encodeCodecConfig.h264Config.chromaFormatIDC = avctx->profile == FF_PROFILE_H264_HIGH_444_PREDICTIVE ? 3 : 1;
  621. if (ctx->level) {
  622. res = input_string_to_uint32(avctx, nvenc_h264_level_pairs, ctx->level, &ctx->encode_config.encodeCodecConfig.h264Config.level);
  623. if (res) {
  624. av_log(avctx, AV_LOG_FATAL, "Level \"%s\" is unknown! Supported levels: auto, 1, 1b, 1.1, 1.2, 1.3, 2, 2.1, 2.2, 3, 3.1, 3.2, 4, 4.1, 4.2, 5, 5.1\n", ctx->level);
  625. return res;
  626. }
  627. } else {
  628. ctx->encode_config.encodeCodecConfig.h264Config.level = NV_ENC_LEVEL_AUTOSELECT;
  629. }
  630. return 0;
  631. }
  632. static av_cold int nvenc_setup_hevc_config(AVCodecContext *avctx)
  633. {
  634. NvencContext *ctx = avctx->priv_data;
  635. int res;
  636. ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.colourMatrix = avctx->colorspace;
  637. ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.colourPrimaries = avctx->color_primaries;
  638. ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.transferCharacteristics = avctx->color_trc;
  639. ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
  640. || avctx->pix_fmt == AV_PIX_FMT_YUVJ420P || avctx->pix_fmt == AV_PIX_FMT_YUVJ422P || avctx->pix_fmt == AV_PIX_FMT_YUVJ444P);
  641. ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.colourDescriptionPresentFlag =
  642. (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
  643. ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.videoSignalTypePresentFlag =
  644. (ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.colourDescriptionPresentFlag
  645. || ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.videoFormat != 5
  646. || ctx->encode_config.encodeCodecConfig.hevcConfig.hevcVUIParameters.videoFullRangeFlag != 0);
  647. ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode = 3;
  648. ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData = 1;
  649. ctx->encode_config.encodeCodecConfig.hevcConfig.disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
  650. ctx->encode_config.encodeCodecConfig.hevcConfig.repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
  651. ctx->encode_config.encodeCodecConfig.hevcConfig.outputAUD = 1;
  652. /* No other profile is supported in the current SDK version 5 */
  653. ctx->encode_config.profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
  654. avctx->profile = FF_PROFILE_HEVC_MAIN;
  655. if (ctx->level) {
  656. res = input_string_to_uint32(avctx, nvenc_hevc_level_pairs, ctx->level, &ctx->encode_config.encodeCodecConfig.hevcConfig.level);
  657. if (res) {
  658. av_log(avctx, AV_LOG_FATAL, "Level \"%s\" is unknown! Supported levels: auto, 1, 2, 2.1, 3, 3.1, 4, 4.1, 5, 5.1, 5.2, 6, 6.1, 6.2\n", ctx->level);
  659. return res;
  660. }
  661. } else {
  662. ctx->encode_config.encodeCodecConfig.hevcConfig.level = NV_ENC_LEVEL_AUTOSELECT;
  663. }
  664. if (ctx->tier) {
  665. if (!strcmp(ctx->tier, "main")) {
  666. ctx->encode_config.encodeCodecConfig.hevcConfig.tier = NV_ENC_TIER_HEVC_MAIN;
  667. } else if (!strcmp(ctx->tier, "high")) {
  668. ctx->encode_config.encodeCodecConfig.hevcConfig.tier = NV_ENC_TIER_HEVC_HIGH;
  669. } else {
  670. av_log(avctx, AV_LOG_FATAL, "Tier \"%s\" is unknown! Supported tiers: main, high\n", ctx->tier);
  671. return AVERROR(EINVAL);
  672. }
  673. }
  674. return 0;
  675. }
  676. static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx, int lossless)
  677. {
  678. switch (avctx->codec->id) {
  679. case AV_CODEC_ID_H264:
  680. return nvenc_setup_h264_config(avctx, lossless);
  681. case AV_CODEC_ID_H265:
  682. return nvenc_setup_hevc_config(avctx);
  683. /* Earlier switch/case will return if unknown codec is passed. */
  684. }
  685. return 0;
  686. }
  687. static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
  688. {
  689. NvencContext *ctx = avctx->priv_data;
  690. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  691. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  692. NV_ENC_PRESET_CONFIG preset_config = { 0 };
  693. GUID encoder_preset = NV_ENC_PRESET_HQ_GUID;
  694. GUID codec;
  695. NVENCSTATUS nv_status = NV_ENC_SUCCESS;
  696. AVCPBProperties *cpb_props;
  697. int num_mbs;
  698. int isLL = 0;
  699. int lossless = 0;
  700. int res = 0;
  701. int dw, dh;
  702. ctx->last_dts = AV_NOPTS_VALUE;
  703. ctx->encode_config.version = NV_ENC_CONFIG_VER;
  704. ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
  705. preset_config.version = NV_ENC_PRESET_CONFIG_VER;
  706. preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
  707. if (ctx->preset) {
  708. if (!strcmp(ctx->preset, "slow")) {
  709. encoder_preset = NV_ENC_PRESET_HQ_GUID;
  710. ctx->twopass = 1;
  711. } else if (!strcmp(ctx->preset, "medium")) {
  712. encoder_preset = NV_ENC_PRESET_HQ_GUID;
  713. ctx->twopass = 0;
  714. } else if (!strcmp(ctx->preset, "fast")) {
  715. encoder_preset = NV_ENC_PRESET_HP_GUID;
  716. ctx->twopass = 0;
  717. } else if (!strcmp(ctx->preset, "hq")) {
  718. encoder_preset = NV_ENC_PRESET_HQ_GUID;
  719. } else if (!strcmp(ctx->preset, "hp")) {
  720. encoder_preset = NV_ENC_PRESET_HP_GUID;
  721. } else if (!strcmp(ctx->preset, "bd")) {
  722. encoder_preset = NV_ENC_PRESET_BD_GUID;
  723. } else if (!strcmp(ctx->preset, "ll")) {
  724. encoder_preset = NV_ENC_PRESET_LOW_LATENCY_DEFAULT_GUID;
  725. isLL = 1;
  726. } else if (!strcmp(ctx->preset, "llhp")) {
  727. encoder_preset = NV_ENC_PRESET_LOW_LATENCY_HP_GUID;
  728. isLL = 1;
  729. } else if (!strcmp(ctx->preset, "llhq")) {
  730. encoder_preset = NV_ENC_PRESET_LOW_LATENCY_HQ_GUID;
  731. isLL = 1;
  732. } else if (!strcmp(ctx->preset, "lossless")) {
  733. encoder_preset = NV_ENC_PRESET_LOSSLESS_DEFAULT_GUID;
  734. lossless = 1;
  735. } else if (!strcmp(ctx->preset, "losslesshp")) {
  736. encoder_preset = NV_ENC_PRESET_LOSSLESS_HP_GUID;
  737. lossless = 1;
  738. } else if (!strcmp(ctx->preset, "default")) {
  739. encoder_preset = NV_ENC_PRESET_DEFAULT_GUID;
  740. } else {
  741. av_log(avctx, AV_LOG_FATAL, "Preset \"%s\" is unknown! Supported presets: slow, medium, fast, hp, hq, bd, ll, llhp, llhq, lossless, losslesshp, default\n", ctx->preset);
  742. return AVERROR(EINVAL);
  743. }
  744. }
  745. if (ctx->twopass < 0) {
  746. ctx->twopass = isLL;
  747. }
  748. switch (avctx->codec->id) {
  749. case AV_CODEC_ID_H264:
  750. codec = NV_ENC_CODEC_H264_GUID;
  751. break;
  752. case AV_CODEC_ID_H265:
  753. codec = NV_ENC_CODEC_HEVC_GUID;
  754. break;
  755. default:
  756. av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
  757. return AVERROR(EINVAL);
  758. }
  759. nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder, codec, encoder_preset, &preset_config);
  760. if (nv_status != NV_ENC_SUCCESS) {
  761. return nvenc_print_error(avctx, nv_status, "GetEncodePresetConfig failed");
  762. }
  763. ctx->init_encode_params.encodeGUID = codec;
  764. ctx->init_encode_params.encodeHeight = avctx->height;
  765. ctx->init_encode_params.encodeWidth = avctx->width;
  766. if (avctx->sample_aspect_ratio.num && avctx->sample_aspect_ratio.den &&
  767. (avctx->sample_aspect_ratio.num != 1 || avctx->sample_aspect_ratio.num != 1)) {
  768. av_reduce(&dw, &dh,
  769. avctx->width * avctx->sample_aspect_ratio.num,
  770. avctx->height * avctx->sample_aspect_ratio.den,
  771. 1024 * 1024);
  772. ctx->init_encode_params.darHeight = dh;
  773. ctx->init_encode_params.darWidth = dw;
  774. } else {
  775. ctx->init_encode_params.darHeight = avctx->height;
  776. ctx->init_encode_params.darWidth = avctx->width;
  777. }
  778. // De-compensate for hardware, dubiously, trying to compensate for
  779. // playback at 704 pixel width.
  780. if (avctx->width == 720 &&
  781. (avctx->height == 480 || avctx->height == 576)) {
  782. av_reduce(&dw, &dh,
  783. ctx->init_encode_params.darWidth * 44,
  784. ctx->init_encode_params.darHeight * 45,
  785. 1024 * 1024);
  786. ctx->init_encode_params.darHeight = dh;
  787. ctx->init_encode_params.darWidth = dw;
  788. }
  789. ctx->init_encode_params.frameRateNum = avctx->time_base.den;
  790. ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
  791. num_mbs = ((avctx->width + 15) >> 4) * ((avctx->height + 15) >> 4);
  792. ctx->max_surface_count = (num_mbs >= 8160) ? 32 : 48;
  793. if (ctx->buffer_delay >= ctx->max_surface_count)
  794. ctx->buffer_delay = ctx->max_surface_count - 1;
  795. ctx->init_encode_params.enableEncodeAsync = 0;
  796. ctx->init_encode_params.enablePTD = 1;
  797. ctx->init_encode_params.presetGUID = encoder_preset;
  798. ctx->init_encode_params.encodeConfig = &ctx->encode_config;
  799. memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
  800. ctx->encode_config.version = NV_ENC_CONFIG_VER;
  801. if (avctx->refs >= 0) {
  802. /* 0 means "let the hardware decide" */
  803. switch (avctx->codec->id) {
  804. case AV_CODEC_ID_H264:
  805. ctx->encode_config.encodeCodecConfig.h264Config.maxNumRefFrames = avctx->refs;
  806. break;
  807. case AV_CODEC_ID_H265:
  808. ctx->encode_config.encodeCodecConfig.hevcConfig.maxNumRefFramesInDPB = avctx->refs;
  809. break;
  810. /* Earlier switch/case will return if unknown codec is passed. */
  811. }
  812. }
  813. if (avctx->gop_size > 0) {
  814. if (avctx->max_b_frames >= 0) {
  815. /* 0 is intra-only, 1 is I/P only, 2 is one B Frame, 3 two B frames, and so on. */
  816. ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
  817. }
  818. ctx->encode_config.gopLength = avctx->gop_size;
  819. switch (avctx->codec->id) {
  820. case AV_CODEC_ID_H264:
  821. ctx->encode_config.encodeCodecConfig.h264Config.idrPeriod = avctx->gop_size;
  822. break;
  823. case AV_CODEC_ID_H265:
  824. ctx->encode_config.encodeCodecConfig.hevcConfig.idrPeriod = avctx->gop_size;
  825. break;
  826. /* Earlier switch/case will return if unknown codec is passed. */
  827. }
  828. } else if (avctx->gop_size == 0) {
  829. ctx->encode_config.frameIntervalP = 0;
  830. ctx->encode_config.gopLength = 1;
  831. switch (avctx->codec->id) {
  832. case AV_CODEC_ID_H264:
  833. ctx->encode_config.encodeCodecConfig.h264Config.idrPeriod = 1;
  834. break;
  835. case AV_CODEC_ID_H265:
  836. ctx->encode_config.encodeCodecConfig.hevcConfig.idrPeriod = 1;
  837. break;
  838. /* Earlier switch/case will return if unknown codec is passed. */
  839. }
  840. }
  841. /* when there're b frames, set dts offset */
  842. if (ctx->encode_config.frameIntervalP >= 2)
  843. ctx->last_dts = -2;
  844. nvenc_setup_rate_control(avctx, lossless);
  845. if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
  846. ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
  847. } else {
  848. ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
  849. }
  850. res = nvenc_setup_codec_config(avctx, lossless);
  851. if (res)
  852. return res;
  853. nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
  854. if (nv_status != NV_ENC_SUCCESS) {
  855. return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
  856. }
  857. if (ctx->encode_config.frameIntervalP > 1)
  858. avctx->has_b_frames = 2;
  859. if (ctx->encode_config.rcParams.averageBitRate > 0)
  860. avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
  861. cpb_props = ff_add_cpb_side_data(avctx);
  862. if (!cpb_props)
  863. return AVERROR(ENOMEM);
  864. cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
  865. cpb_props->avg_bitrate = avctx->bit_rate;
  866. cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
  867. return 0;
  868. }
  869. static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
  870. {
  871. NvencContext *ctx = avctx->priv_data;
  872. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  873. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  874. NVENCSTATUS nv_status;
  875. NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
  876. NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
  877. allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
  878. allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
  879. allocSurf.width = (avctx->width + 31) & ~31;
  880. allocSurf.height = (avctx->height + 31) & ~31;
  881. allocSurf.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
  882. switch (avctx->pix_fmt) {
  883. case AV_PIX_FMT_YUV420P:
  884. allocSurf.bufferFmt = NV_ENC_BUFFER_FORMAT_YV12_PL;
  885. break;
  886. case AV_PIX_FMT_NV12:
  887. allocSurf.bufferFmt = NV_ENC_BUFFER_FORMAT_NV12_PL;
  888. break;
  889. case AV_PIX_FMT_YUV444P:
  890. allocSurf.bufferFmt = NV_ENC_BUFFER_FORMAT_YUV444_PL;
  891. break;
  892. default:
  893. av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format\n");
  894. return AVERROR(EINVAL);
  895. }
  896. nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
  897. if (nv_status != NV_ENC_SUCCESS) {
  898. return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
  899. }
  900. ctx->surfaces[idx].lockCount = 0;
  901. ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
  902. ctx->surfaces[idx].format = allocSurf.bufferFmt;
  903. ctx->surfaces[idx].width = allocSurf.width;
  904. ctx->surfaces[idx].height = allocSurf.height;
  905. /* 1MB is large enough to hold most output frames. NVENC increases this automaticaly if it's not enough. */
  906. allocOut.size = 1024 * 1024;
  907. allocOut.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
  908. nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
  909. if (nv_status != NV_ENC_SUCCESS) {
  910. int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
  911. p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
  912. return err;
  913. }
  914. ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
  915. ctx->surfaces[idx].size = allocOut.size;
  916. return 0;
  917. }
  918. static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx, int* surfaceCount)
  919. {
  920. int res;
  921. NvencContext *ctx = avctx->priv_data;
  922. ctx->surfaces = av_malloc(ctx->max_surface_count * sizeof(*ctx->surfaces));
  923. if (!ctx->surfaces) {
  924. return AVERROR(ENOMEM);
  925. }
  926. ctx->timestamp_list = av_fifo_alloc(ctx->max_surface_count * sizeof(int64_t));
  927. if (!ctx->timestamp_list)
  928. return AVERROR(ENOMEM);
  929. ctx->output_surface_queue = av_fifo_alloc(ctx->max_surface_count * sizeof(NvencSurface*));
  930. if (!ctx->output_surface_queue)
  931. return AVERROR(ENOMEM);
  932. ctx->output_surface_ready_queue = av_fifo_alloc(ctx->max_surface_count * sizeof(NvencSurface*));
  933. if (!ctx->output_surface_ready_queue)
  934. return AVERROR(ENOMEM);
  935. for (*surfaceCount = 0; *surfaceCount < ctx->max_surface_count; ++*surfaceCount) {
  936. res = nvenc_alloc_surface(avctx, *surfaceCount);
  937. if (res)
  938. return res;
  939. }
  940. return 0;
  941. }
  942. static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
  943. {
  944. NvencContext *ctx = avctx->priv_data;
  945. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  946. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  947. NVENCSTATUS nv_status;
  948. uint32_t outSize = 0;
  949. char tmpHeader[256];
  950. NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
  951. payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
  952. payload.spsppsBuffer = tmpHeader;
  953. payload.inBufferSize = sizeof(tmpHeader);
  954. payload.outSPSPPSPayloadSize = &outSize;
  955. nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
  956. if (nv_status != NV_ENC_SUCCESS) {
  957. return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
  958. }
  959. avctx->extradata_size = outSize;
  960. avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
  961. if (!avctx->extradata) {
  962. return AVERROR(ENOMEM);
  963. }
  964. memcpy(avctx->extradata, tmpHeader, outSize);
  965. return 0;
  966. }
  967. static av_cold int nvenc_encode_init(AVCodecContext *avctx)
  968. {
  969. NvencContext *ctx = avctx->priv_data;
  970. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  971. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  972. int res;
  973. int i;
  974. int surfaceCount = 0;
  975. if (!nvenc_dyload_nvenc(avctx))
  976. return AVERROR_EXTERNAL;
  977. res = nvenc_setup_device(avctx);
  978. if (res)
  979. goto error;
  980. res = nvenc_open_session(avctx);
  981. if (res)
  982. goto error;
  983. res = nvenc_setup_encoder(avctx);
  984. if (res)
  985. goto error;
  986. res = nvenc_setup_surfaces(avctx, &surfaceCount);
  987. if (res)
  988. goto error;
  989. if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
  990. res = nvenc_setup_extradata(avctx);
  991. if (res)
  992. goto error;
  993. }
  994. return 0;
  995. error:
  996. av_fifo_freep(&ctx->timestamp_list);
  997. av_fifo_freep(&ctx->output_surface_ready_queue);
  998. av_fifo_freep(&ctx->output_surface_queue);
  999. for (i = 0; i < surfaceCount; ++i) {
  1000. p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
  1001. p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
  1002. }
  1003. av_freep(&ctx->surfaces);
  1004. if (ctx->nvencoder)
  1005. p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
  1006. if (ctx->cu_context)
  1007. dl_fn->cu_ctx_destroy(ctx->cu_context);
  1008. nvenc_unload_nvenc(avctx);
  1009. ctx->nvencoder = NULL;
  1010. ctx->cu_context = NULL;
  1011. return res;
  1012. }
  1013. static av_cold int nvenc_encode_close(AVCodecContext *avctx)
  1014. {
  1015. NvencContext *ctx = avctx->priv_data;
  1016. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  1017. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  1018. int i;
  1019. av_fifo_freep(&ctx->timestamp_list);
  1020. av_fifo_freep(&ctx->output_surface_ready_queue);
  1021. av_fifo_freep(&ctx->output_surface_queue);
  1022. for (i = 0; i < ctx->max_surface_count; ++i) {
  1023. p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
  1024. p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
  1025. }
  1026. av_freep(&ctx->surfaces);
  1027. ctx->max_surface_count = 0;
  1028. p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
  1029. ctx->nvencoder = NULL;
  1030. dl_fn->cu_ctx_destroy(ctx->cu_context);
  1031. ctx->cu_context = NULL;
  1032. nvenc_unload_nvenc(avctx);
  1033. return 0;
  1034. }
  1035. static NvencSurface *get_free_frame(NvencContext *ctx)
  1036. {
  1037. int i;
  1038. for (i = 0; i < ctx->max_surface_count; ++i) {
  1039. if (!ctx->surfaces[i].lockCount) {
  1040. ctx->surfaces[i].lockCount = 1;
  1041. return &ctx->surfaces[i];
  1042. }
  1043. }
  1044. return NULL;
  1045. }
  1046. static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *inSurf,
  1047. NV_ENC_LOCK_INPUT_BUFFER *lockBufferParams, const AVFrame *frame)
  1048. {
  1049. uint8_t *buf = lockBufferParams->bufferDataPtr;
  1050. int off = inSurf->height * lockBufferParams->pitch;
  1051. if (avctx->pix_fmt == AV_PIX_FMT_YUV420P) {
  1052. av_image_copy_plane(buf, lockBufferParams->pitch,
  1053. frame->data[0], frame->linesize[0],
  1054. avctx->width, avctx->height);
  1055. buf += off;
  1056. av_image_copy_plane(buf, lockBufferParams->pitch >> 1,
  1057. frame->data[2], frame->linesize[2],
  1058. avctx->width >> 1, avctx->height >> 1);
  1059. buf += off >> 2;
  1060. av_image_copy_plane(buf, lockBufferParams->pitch >> 1,
  1061. frame->data[1], frame->linesize[1],
  1062. avctx->width >> 1, avctx->height >> 1);
  1063. } else if (avctx->pix_fmt == AV_PIX_FMT_NV12) {
  1064. av_image_copy_plane(buf, lockBufferParams->pitch,
  1065. frame->data[0], frame->linesize[0],
  1066. avctx->width, avctx->height);
  1067. buf += off;
  1068. av_image_copy_plane(buf, lockBufferParams->pitch,
  1069. frame->data[1], frame->linesize[1],
  1070. avctx->width, avctx->height >> 1);
  1071. } else if (avctx->pix_fmt == AV_PIX_FMT_YUV444P) {
  1072. av_image_copy_plane(buf, lockBufferParams->pitch,
  1073. frame->data[0], frame->linesize[0],
  1074. avctx->width, avctx->height);
  1075. buf += off;
  1076. av_image_copy_plane(buf, lockBufferParams->pitch,
  1077. frame->data[1], frame->linesize[1],
  1078. avctx->width, avctx->height);
  1079. buf += off;
  1080. av_image_copy_plane(buf, lockBufferParams->pitch,
  1081. frame->data[2], frame->linesize[2],
  1082. avctx->width, avctx->height);
  1083. } else {
  1084. av_log(avctx, AV_LOG_FATAL, "Invalid pixel format!\n");
  1085. return AVERROR(EINVAL);
  1086. }
  1087. return 0;
  1088. }
  1089. static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
  1090. NvencSurface *nvenc_frame)
  1091. {
  1092. NvencContext *ctx = avctx->priv_data;
  1093. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  1094. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  1095. int res;
  1096. NVENCSTATUS nv_status;
  1097. NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
  1098. lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
  1099. lockBufferParams.inputBuffer = nvenc_frame->input_surface;
  1100. nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
  1101. if (nv_status != NV_ENC_SUCCESS) {
  1102. return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
  1103. }
  1104. res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
  1105. nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
  1106. if (nv_status != NV_ENC_SUCCESS) {
  1107. return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
  1108. }
  1109. return res;
  1110. }
  1111. static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
  1112. NV_ENC_PIC_PARAMS *params)
  1113. {
  1114. NvencContext *ctx = avctx->priv_data;
  1115. switch (avctx->codec->id) {
  1116. case AV_CODEC_ID_H264:
  1117. params->codecPicParams.h264PicParams.sliceMode = ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
  1118. params->codecPicParams.h264PicParams.sliceModeData = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
  1119. break;
  1120. case AV_CODEC_ID_H265:
  1121. params->codecPicParams.hevcPicParams.sliceMode = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
  1122. params->codecPicParams.hevcPicParams.sliceModeData = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
  1123. break;
  1124. }
  1125. }
  1126. static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
  1127. {
  1128. NvencContext *ctx = avctx->priv_data;
  1129. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  1130. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  1131. uint32_t slice_mode_data;
  1132. uint32_t *slice_offsets;
  1133. NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
  1134. NVENCSTATUS nv_status;
  1135. int res = 0;
  1136. enum AVPictureType pict_type;
  1137. switch (avctx->codec->id) {
  1138. case AV_CODEC_ID_H264:
  1139. slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
  1140. break;
  1141. case AV_CODEC_ID_H265:
  1142. slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
  1143. break;
  1144. default:
  1145. av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
  1146. res = AVERROR(EINVAL);
  1147. goto error;
  1148. }
  1149. slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
  1150. if (!slice_offsets)
  1151. return AVERROR(ENOMEM);
  1152. lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
  1153. lock_params.doNotWait = 0;
  1154. lock_params.outputBitstream = tmpoutsurf->output_surface;
  1155. lock_params.sliceOffsets = slice_offsets;
  1156. nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
  1157. if (nv_status != NV_ENC_SUCCESS) {
  1158. res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
  1159. goto error;
  1160. }
  1161. if (res = ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes,0)) {
  1162. p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
  1163. goto error;
  1164. }
  1165. memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
  1166. nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
  1167. if (nv_status != NV_ENC_SUCCESS)
  1168. nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
  1169. switch (lock_params.pictureType) {
  1170. case NV_ENC_PIC_TYPE_IDR:
  1171. pkt->flags |= AV_PKT_FLAG_KEY;
  1172. case NV_ENC_PIC_TYPE_I:
  1173. pict_type = AV_PICTURE_TYPE_I;
  1174. break;
  1175. case NV_ENC_PIC_TYPE_P:
  1176. pict_type = AV_PICTURE_TYPE_P;
  1177. break;
  1178. case NV_ENC_PIC_TYPE_B:
  1179. pict_type = AV_PICTURE_TYPE_B;
  1180. break;
  1181. case NV_ENC_PIC_TYPE_BI:
  1182. pict_type = AV_PICTURE_TYPE_BI;
  1183. break;
  1184. default:
  1185. av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
  1186. av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
  1187. res = AVERROR_EXTERNAL;
  1188. goto error;
  1189. }
  1190. #if FF_API_CODED_FRAME
  1191. FF_DISABLE_DEPRECATION_WARNINGS
  1192. avctx->coded_frame->pict_type = pict_type;
  1193. FF_ENABLE_DEPRECATION_WARNINGS
  1194. #endif
  1195. ff_side_data_set_encoder_stats(pkt,
  1196. (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
  1197. pkt->pts = lock_params.outputTimeStamp;
  1198. pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
  1199. /* when there're b frame(s), set dts offset */
  1200. if (ctx->encode_config.frameIntervalP >= 2)
  1201. pkt->dts -= 1;
  1202. if (pkt->dts > pkt->pts)
  1203. pkt->dts = pkt->pts;
  1204. if (ctx->last_dts != AV_NOPTS_VALUE && pkt->dts <= ctx->last_dts)
  1205. pkt->dts = ctx->last_dts + 1;
  1206. ctx->last_dts = pkt->dts;
  1207. av_free(slice_offsets);
  1208. return 0;
  1209. error:
  1210. av_free(slice_offsets);
  1211. timestamp_queue_dequeue(ctx->timestamp_list);
  1212. return res;
  1213. }
  1214. static int output_ready(NvencContext *ctx, int flush)
  1215. {
  1216. int nb_ready, nb_pending;
  1217. nb_ready = av_fifo_size(ctx->output_surface_ready_queue) / sizeof(NvencSurface*);
  1218. nb_pending = av_fifo_size(ctx->output_surface_queue) / sizeof(NvencSurface*);
  1219. return nb_ready > 0 && (flush || nb_ready + nb_pending >= ctx->buffer_delay);
  1220. }
  1221. static int nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
  1222. const AVFrame *frame, int *got_packet)
  1223. {
  1224. NVENCSTATUS nv_status;
  1225. NvencSurface *tmpoutsurf, *inSurf;
  1226. int res;
  1227. NvencContext *ctx = avctx->priv_data;
  1228. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  1229. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  1230. NV_ENC_PIC_PARAMS pic_params = { 0 };
  1231. pic_params.version = NV_ENC_PIC_PARAMS_VER;
  1232. if (frame) {
  1233. inSurf = get_free_frame(ctx);
  1234. av_assert0(inSurf);
  1235. res = nvenc_upload_frame(avctx, frame, inSurf);
  1236. if (res) {
  1237. inSurf->lockCount = 0;
  1238. return res;
  1239. }
  1240. pic_params.inputBuffer = inSurf->input_surface;
  1241. pic_params.bufferFmt = inSurf->format;
  1242. pic_params.inputWidth = avctx->width;
  1243. pic_params.inputHeight = avctx->height;
  1244. pic_params.outputBitstream = inSurf->output_surface;
  1245. pic_params.completionEvent = 0;
  1246. if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
  1247. if (frame->top_field_first) {
  1248. pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
  1249. } else {
  1250. pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
  1251. }
  1252. } else {
  1253. pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
  1254. }
  1255. pic_params.encodePicFlags = 0;
  1256. pic_params.inputTimeStamp = frame->pts;
  1257. pic_params.inputDuration = 0;
  1258. nvenc_codec_specific_pic_params(avctx, &pic_params);
  1259. timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
  1260. } else {
  1261. pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
  1262. }
  1263. nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
  1264. if (frame && nv_status == NV_ENC_ERR_NEED_MORE_INPUT)
  1265. av_fifo_generic_write(ctx->output_surface_queue, &inSurf, sizeof(inSurf), NULL);
  1266. if (nv_status != NV_ENC_SUCCESS && nv_status != NV_ENC_ERR_NEED_MORE_INPUT) {
  1267. return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
  1268. }
  1269. if (nv_status != NV_ENC_ERR_NEED_MORE_INPUT) {
  1270. while (av_fifo_size(ctx->output_surface_queue) > 0) {
  1271. av_fifo_generic_read(ctx->output_surface_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
  1272. av_fifo_generic_write(ctx->output_surface_ready_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
  1273. }
  1274. if (frame)
  1275. av_fifo_generic_write(ctx->output_surface_ready_queue, &inSurf, sizeof(inSurf), NULL);
  1276. }
  1277. if (output_ready(ctx, !frame)) {
  1278. av_fifo_generic_read(ctx->output_surface_ready_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
  1279. res = process_output_surface(avctx, pkt, tmpoutsurf);
  1280. if (res)
  1281. return res;
  1282. av_assert0(tmpoutsurf->lockCount);
  1283. tmpoutsurf->lockCount--;
  1284. *got_packet = 1;
  1285. } else {
  1286. *got_packet = 0;
  1287. }
  1288. return 0;
  1289. }
  1290. static const enum AVPixelFormat pix_fmts_nvenc[] = {
  1291. AV_PIX_FMT_YUV420P,
  1292. AV_PIX_FMT_NV12,
  1293. AV_PIX_FMT_YUV444P,
  1294. AV_PIX_FMT_NONE
  1295. };
  1296. #define OFFSET(x) offsetof(NvencContext, x)
  1297. #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
  1298. static const AVOption options[] = {
  1299. { "preset", "Set the encoding preset (one of slow = hq 2pass, medium = hq, fast = hp, hq, hp, bd, ll, llhq, llhp, lossless, losslesshp, default)", OFFSET(preset), AV_OPT_TYPE_STRING, { .str = "medium" }, 0, 0, VE },
  1300. { "profile", "Set the encoding profile (high, main, baseline or high444p)", OFFSET(profile), AV_OPT_TYPE_STRING, { .str = "main" }, 0, 0, VE },
  1301. { "level", "Set the encoding level restriction (auto, 1.0, 1.0b, 1.1, 1.2, ..., 4.2, 5.0, 5.1)", OFFSET(level), AV_OPT_TYPE_STRING, { .str = "auto" }, 0, 0, VE },
  1302. { "tier", "Set the encoding tier (main or high)", OFFSET(tier), AV_OPT_TYPE_STRING, { .str = "main" }, 0, 0, VE },
  1303. { "cbr", "Use cbr encoding mode", OFFSET(cbr), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VE },
  1304. { "2pass", "Use 2pass encoding mode", OFFSET(twopass), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, VE },
  1305. { "gpu", "Selects which NVENC capable GPU to use. First GPU is 0, second is 1, and so on.", OFFSET(gpu), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, VE },
  1306. { "delay", "Delays frame output by the given amount of frames.", OFFSET(buffer_delay), AV_OPT_TYPE_INT, { .i64 = INT_MAX }, 0, INT_MAX, VE },
  1307. { NULL }
  1308. };
  1309. static const AVCodecDefault nvenc_defaults[] = {
  1310. { "b", "2M" },
  1311. { "qmin", "-1" },
  1312. { "qmax", "-1" },
  1313. { "qdiff", "-1" },
  1314. { "qblur", "-1" },
  1315. { "qcomp", "-1" },
  1316. { "g", "250" },
  1317. { "bf", "0" },
  1318. { NULL },
  1319. };
  1320. #if CONFIG_NVENC_ENCODER
  1321. static const AVClass nvenc_class = {
  1322. .class_name = "nvenc",
  1323. .item_name = av_default_item_name,
  1324. .option = options,
  1325. .version = LIBAVUTIL_VERSION_INT,
  1326. };
  1327. AVCodec ff_nvenc_encoder = {
  1328. .name = "nvenc",
  1329. .long_name = NULL_IF_CONFIG_SMALL("NVIDIA NVENC h264 encoder"),
  1330. .type = AVMEDIA_TYPE_VIDEO,
  1331. .id = AV_CODEC_ID_H264,
  1332. .priv_data_size = sizeof(NvencContext),
  1333. .init = nvenc_encode_init,
  1334. .encode2 = nvenc_encode_frame,
  1335. .close = nvenc_encode_close,
  1336. .capabilities = AV_CODEC_CAP_DELAY,
  1337. .priv_class = &nvenc_class,
  1338. .defaults = nvenc_defaults,
  1339. .pix_fmts = pix_fmts_nvenc,
  1340. };
  1341. #endif
  1342. /* Add an alias for nvenc_h264 */
  1343. #if CONFIG_NVENC_H264_ENCODER
  1344. static const AVClass nvenc_h264_class = {
  1345. .class_name = "nvenc_h264",
  1346. .item_name = av_default_item_name,
  1347. .option = options,
  1348. .version = LIBAVUTIL_VERSION_INT,
  1349. };
  1350. AVCodec ff_nvenc_h264_encoder = {
  1351. .name = "nvenc_h264",
  1352. .long_name = NULL_IF_CONFIG_SMALL("NVIDIA NVENC h264 encoder"),
  1353. .type = AVMEDIA_TYPE_VIDEO,
  1354. .id = AV_CODEC_ID_H264,
  1355. .priv_data_size = sizeof(NvencContext),
  1356. .init = nvenc_encode_init,
  1357. .encode2 = nvenc_encode_frame,
  1358. .close = nvenc_encode_close,
  1359. .capabilities = AV_CODEC_CAP_DELAY,
  1360. .priv_class = &nvenc_h264_class,
  1361. .defaults = nvenc_defaults,
  1362. .pix_fmts = pix_fmts_nvenc,
  1363. };
  1364. #endif
  1365. #if CONFIG_NVENC_HEVC_ENCODER
  1366. static const AVClass nvenc_hevc_class = {
  1367. .class_name = "nvenc_hevc",
  1368. .item_name = av_default_item_name,
  1369. .option = options,
  1370. .version = LIBAVUTIL_VERSION_INT,
  1371. };
  1372. AVCodec ff_nvenc_hevc_encoder = {
  1373. .name = "nvenc_hevc",
  1374. .long_name = NULL_IF_CONFIG_SMALL("NVIDIA NVENC hevc encoder"),
  1375. .type = AVMEDIA_TYPE_VIDEO,
  1376. .id = AV_CODEC_ID_H265,
  1377. .priv_data_size = sizeof(NvencContext),
  1378. .init = nvenc_encode_init,
  1379. .encode2 = nvenc_encode_frame,
  1380. .close = nvenc_encode_close,
  1381. .capabilities = AV_CODEC_CAP_DELAY,
  1382. .priv_class = &nvenc_hevc_class,
  1383. .defaults = nvenc_defaults,
  1384. .pix_fmts = pix_fmts_nvenc,
  1385. };
  1386. #endif