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.

522 lines
15KB

  1. /*
  2. * HW decode acceleration through NVDEC
  3. *
  4. * Copyright (c) 2016 Anton Khirnov
  5. *
  6. * This file is part of FFmpeg.
  7. *
  8. * FFmpeg is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * FFmpeg is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with FFmpeg; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. #include "config.h"
  23. #include "libavutil/common.h"
  24. #include "libavutil/error.h"
  25. #include "libavutil/hwcontext.h"
  26. #include "libavutil/hwcontext_cuda_internal.h"
  27. #include "libavutil/pixdesc.h"
  28. #include "libavutil/pixfmt.h"
  29. #include "avcodec.h"
  30. #include "decode.h"
  31. #include "nvdec.h"
  32. #include "internal.h"
  33. typedef struct NVDECDecoder {
  34. CUvideodecoder decoder;
  35. AVBufferRef *hw_device_ref;
  36. CUcontext cuda_ctx;
  37. CudaFunctions *cudl;
  38. CuvidFunctions *cvdl;
  39. } NVDECDecoder;
  40. typedef struct NVDECFramePool {
  41. unsigned int dpb_size;
  42. unsigned int nb_allocated;
  43. } NVDECFramePool;
  44. static int map_avcodec_id(enum AVCodecID id)
  45. {
  46. switch (id) {
  47. case AV_CODEC_ID_H264: return cudaVideoCodec_H264;
  48. case AV_CODEC_ID_HEVC: return cudaVideoCodec_HEVC;
  49. case AV_CODEC_ID_VC1: return cudaVideoCodec_VC1;
  50. case AV_CODEC_ID_VP9: return cudaVideoCodec_VP9;
  51. case AV_CODEC_ID_WMV3: return cudaVideoCodec_VC1;
  52. }
  53. return -1;
  54. }
  55. static int map_chroma_format(enum AVPixelFormat pix_fmt)
  56. {
  57. int shift_h = 0, shift_v = 0;
  58. av_pix_fmt_get_chroma_sub_sample(pix_fmt, &shift_h, &shift_v);
  59. if (shift_h == 1 && shift_v == 1)
  60. return cudaVideoChromaFormat_420;
  61. else if (shift_h == 1 && shift_v == 0)
  62. return cudaVideoChromaFormat_422;
  63. else if (shift_h == 0 && shift_v == 0)
  64. return cudaVideoChromaFormat_444;
  65. return -1;
  66. }
  67. static int nvdec_test_capabilities(NVDECDecoder *decoder,
  68. CUVIDDECODECREATEINFO *params, void *logctx)
  69. {
  70. CUresult err;
  71. CUVIDDECODECAPS caps = { 0 };
  72. caps.eCodecType = params->CodecType;
  73. caps.eChromaFormat = params->ChromaFormat;
  74. caps.nBitDepthMinus8 = params->bitDepthMinus8;
  75. err = decoder->cvdl->cuvidGetDecoderCaps(&caps);
  76. if (err != CUDA_SUCCESS) {
  77. av_log(logctx, AV_LOG_ERROR, "Failed querying decoder capabilities\n");
  78. return AVERROR_UNKNOWN;
  79. }
  80. av_log(logctx, AV_LOG_VERBOSE, "NVDEC capabilities:\n");
  81. av_log(logctx, AV_LOG_VERBOSE, "format supported: %s, max_mb_count: %d\n",
  82. caps.bIsSupported ? "yes" : "no", caps.nMaxMBCount);
  83. av_log(logctx, AV_LOG_VERBOSE, "min_width: %d, max_width: %d\n",
  84. caps.nMinWidth, caps.nMaxWidth);
  85. av_log(logctx, AV_LOG_VERBOSE, "min_height: %d, max_height: %d\n",
  86. caps.nMinHeight, caps.nMaxHeight);
  87. if (!caps.bIsSupported) {
  88. av_log(logctx, AV_LOG_ERROR, "Hardware is lacking required capabilities\n");
  89. return AVERROR(EINVAL);
  90. }
  91. if (params->ulWidth > caps.nMaxWidth || params->ulWidth < caps.nMinWidth) {
  92. av_log(logctx, AV_LOG_ERROR, "Video width %d not within range from %d to %d\n",
  93. (int)params->ulWidth, caps.nMinWidth, caps.nMaxWidth);
  94. return AVERROR(EINVAL);
  95. }
  96. if (params->ulHeight > caps.nMaxHeight || params->ulHeight < caps.nMinHeight) {
  97. av_log(logctx, AV_LOG_ERROR, "Video height %d not within range from %d to %d\n",
  98. (int)params->ulHeight, caps.nMinHeight, caps.nMaxHeight);
  99. return AVERROR(EINVAL);
  100. }
  101. if ((params->ulWidth * params->ulHeight) / 256 > caps.nMaxMBCount) {
  102. av_log(logctx, AV_LOG_ERROR, "Video macroblock count %d exceeds maximum of %d\n",
  103. (int)(params->ulWidth * params->ulHeight) / 256, caps.nMaxMBCount);
  104. return AVERROR(EINVAL);
  105. }
  106. return 0;
  107. }
  108. static void nvdec_decoder_free(void *opaque, uint8_t *data)
  109. {
  110. NVDECDecoder *decoder = (NVDECDecoder*)data;
  111. if (decoder->decoder)
  112. decoder->cvdl->cuvidDestroyDecoder(decoder->decoder);
  113. av_buffer_unref(&decoder->hw_device_ref);
  114. cuvid_free_functions(&decoder->cvdl);
  115. av_freep(&decoder);
  116. }
  117. static int nvdec_decoder_create(AVBufferRef **out, AVBufferRef *hw_device_ref,
  118. CUVIDDECODECREATEINFO *params, void *logctx)
  119. {
  120. AVHWDeviceContext *hw_device_ctx = (AVHWDeviceContext*)hw_device_ref->data;
  121. AVCUDADeviceContext *device_hwctx = hw_device_ctx->hwctx;
  122. AVBufferRef *decoder_ref;
  123. NVDECDecoder *decoder;
  124. CUcontext dummy;
  125. CUresult err;
  126. int ret;
  127. decoder = av_mallocz(sizeof(*decoder));
  128. if (!decoder)
  129. return AVERROR(ENOMEM);
  130. decoder_ref = av_buffer_create((uint8_t*)decoder, sizeof(*decoder),
  131. nvdec_decoder_free, NULL, AV_BUFFER_FLAG_READONLY);
  132. if (!decoder_ref) {
  133. av_freep(&decoder);
  134. return AVERROR(ENOMEM);
  135. }
  136. decoder->hw_device_ref = av_buffer_ref(hw_device_ref);
  137. if (!decoder->hw_device_ref) {
  138. ret = AVERROR(ENOMEM);
  139. goto fail;
  140. }
  141. decoder->cuda_ctx = device_hwctx->cuda_ctx;
  142. decoder->cudl = device_hwctx->internal->cuda_dl;
  143. ret = cuvid_load_functions(&decoder->cvdl);
  144. if (ret < 0) {
  145. av_log(logctx, AV_LOG_ERROR, "Failed loading nvcuvid.\n");
  146. goto fail;
  147. }
  148. err = decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx);
  149. if (err != CUDA_SUCCESS) {
  150. ret = AVERROR_UNKNOWN;
  151. goto fail;
  152. }
  153. ret = nvdec_test_capabilities(decoder, params, logctx);
  154. if (ret < 0) {
  155. decoder->cudl->cuCtxPopCurrent(&dummy);
  156. goto fail;
  157. }
  158. err = decoder->cvdl->cuvidCreateDecoder(&decoder->decoder, params);
  159. decoder->cudl->cuCtxPopCurrent(&dummy);
  160. if (err != CUDA_SUCCESS) {
  161. av_log(logctx, AV_LOG_ERROR, "Error creating a NVDEC decoder: %d\n", err);
  162. ret = AVERROR_UNKNOWN;
  163. goto fail;
  164. }
  165. *out = decoder_ref;
  166. return 0;
  167. fail:
  168. av_buffer_unref(&decoder_ref);
  169. return ret;
  170. }
  171. static AVBufferRef *nvdec_decoder_frame_alloc(void *opaque, int size)
  172. {
  173. NVDECFramePool *pool = opaque;
  174. AVBufferRef *ret;
  175. if (pool->nb_allocated >= pool->dpb_size)
  176. return NULL;
  177. ret = av_buffer_alloc(sizeof(unsigned int));
  178. if (!ret)
  179. return NULL;
  180. *(unsigned int*)ret->data = pool->nb_allocated++;
  181. return ret;
  182. }
  183. int ff_nvdec_decode_uninit(AVCodecContext *avctx)
  184. {
  185. NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
  186. av_freep(&ctx->bitstream);
  187. ctx->bitstream_len = 0;
  188. ctx->bitstream_allocated = 0;
  189. av_freep(&ctx->slice_offsets);
  190. ctx->nb_slices = 0;
  191. ctx->slice_offsets_allocated = 0;
  192. av_buffer_unref(&ctx->decoder_ref);
  193. av_buffer_pool_uninit(&ctx->decoder_pool);
  194. return 0;
  195. }
  196. int ff_nvdec_decode_init(AVCodecContext *avctx)
  197. {
  198. NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
  199. NVDECFramePool *pool;
  200. AVHWFramesContext *frames_ctx;
  201. const AVPixFmtDescriptor *sw_desc;
  202. CUVIDDECODECREATEINFO params = { 0 };
  203. int cuvid_codec_type, cuvid_chroma_format;
  204. int ret = 0;
  205. sw_desc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);
  206. if (!sw_desc)
  207. return AVERROR_BUG;
  208. cuvid_codec_type = map_avcodec_id(avctx->codec_id);
  209. if (cuvid_codec_type < 0) {
  210. av_log(avctx, AV_LOG_ERROR, "Unsupported codec ID\n");
  211. return AVERROR_BUG;
  212. }
  213. cuvid_chroma_format = map_chroma_format(avctx->sw_pix_fmt);
  214. if (cuvid_chroma_format < 0) {
  215. av_log(avctx, AV_LOG_ERROR, "Unsupported chroma format\n");
  216. return AVERROR(ENOSYS);
  217. }
  218. if (!avctx->hw_frames_ctx) {
  219. ret = ff_decode_get_hw_frames_ctx(avctx, AV_HWDEVICE_TYPE_CUDA);
  220. if (ret < 0)
  221. return ret;
  222. }
  223. frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  224. params.ulWidth = avctx->coded_width;
  225. params.ulHeight = avctx->coded_height;
  226. params.ulTargetWidth = avctx->coded_width;
  227. params.ulTargetHeight = avctx->coded_height;
  228. params.bitDepthMinus8 = sw_desc->comp[0].depth - 8;
  229. params.OutputFormat = params.bitDepthMinus8 ?
  230. cudaVideoSurfaceFormat_P016 : cudaVideoSurfaceFormat_NV12;
  231. params.CodecType = cuvid_codec_type;
  232. params.ChromaFormat = cuvid_chroma_format;
  233. params.ulNumDecodeSurfaces = frames_ctx->initial_pool_size;
  234. params.ulNumOutputSurfaces = 1;
  235. ret = nvdec_decoder_create(&ctx->decoder_ref, frames_ctx->device_ref, &params, avctx);
  236. if (ret < 0) {
  237. if (params.ulNumDecodeSurfaces > 32) {
  238. av_log(avctx, AV_LOG_WARNING, "Using more than 32 (%d) decode surfaces might cause nvdec to fail.\n",
  239. (int)params.ulNumDecodeSurfaces);
  240. av_log(avctx, AV_LOG_WARNING, "Try lowering the amount of threads. Using %d right now.\n",
  241. avctx->thread_count);
  242. }
  243. return ret;
  244. }
  245. pool = av_mallocz(sizeof(*pool));
  246. if (!pool) {
  247. ret = AVERROR(ENOMEM);
  248. goto fail;
  249. }
  250. pool->dpb_size = frames_ctx->initial_pool_size;
  251. ctx->decoder_pool = av_buffer_pool_init2(sizeof(int), pool,
  252. nvdec_decoder_frame_alloc, av_free);
  253. if (!ctx->decoder_pool) {
  254. ret = AVERROR(ENOMEM);
  255. goto fail;
  256. }
  257. return 0;
  258. fail:
  259. ff_nvdec_decode_uninit(avctx);
  260. return ret;
  261. }
  262. static void nvdec_fdd_priv_free(void *priv)
  263. {
  264. NVDECFrame *cf = priv;
  265. if (!cf)
  266. return;
  267. av_buffer_unref(&cf->idx_ref);
  268. av_buffer_unref(&cf->decoder_ref);
  269. av_freep(&priv);
  270. }
  271. static int nvdec_retrieve_data(void *logctx, AVFrame *frame)
  272. {
  273. FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
  274. NVDECFrame *cf = (NVDECFrame*)fdd->hwaccel_priv;
  275. NVDECDecoder *decoder = (NVDECDecoder*)cf->decoder_ref->data;
  276. CUVIDPROCPARAMS vpp = { .progressive_frame = 1 };
  277. CUresult err;
  278. CUcontext dummy;
  279. CUdeviceptr devptr;
  280. unsigned int pitch, i;
  281. unsigned int offset = 0;
  282. int ret = 0;
  283. err = decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx);
  284. if (err != CUDA_SUCCESS)
  285. return AVERROR_UNKNOWN;
  286. err = decoder->cvdl->cuvidMapVideoFrame(decoder->decoder, cf->idx, &devptr,
  287. &pitch, &vpp);
  288. if (err != CUDA_SUCCESS) {
  289. av_log(logctx, AV_LOG_ERROR, "Error mapping a picture with CUVID: %d\n",
  290. err);
  291. ret = AVERROR_UNKNOWN;
  292. goto finish;
  293. }
  294. for (i = 0; frame->data[i]; i++) {
  295. CUDA_MEMCPY2D cpy = {
  296. .srcMemoryType = CU_MEMORYTYPE_DEVICE,
  297. .dstMemoryType = CU_MEMORYTYPE_DEVICE,
  298. .srcDevice = devptr,
  299. .dstDevice = (CUdeviceptr)frame->data[i],
  300. .srcPitch = pitch,
  301. .dstPitch = frame->linesize[i],
  302. .srcY = offset,
  303. .WidthInBytes = FFMIN(pitch, frame->linesize[i]),
  304. .Height = frame->height >> (i ? 1 : 0),
  305. };
  306. err = decoder->cudl->cuMemcpy2D(&cpy);
  307. if (err != CUDA_SUCCESS) {
  308. av_log(logctx, AV_LOG_ERROR, "Error copying decoded frame: %d\n",
  309. err);
  310. ret = AVERROR_UNKNOWN;
  311. goto copy_fail;
  312. }
  313. offset += cpy.Height;
  314. }
  315. copy_fail:
  316. decoder->cvdl->cuvidUnmapVideoFrame(decoder->decoder, devptr);
  317. finish:
  318. decoder->cudl->cuCtxPopCurrent(&dummy);
  319. return ret;
  320. }
  321. int ff_nvdec_start_frame(AVCodecContext *avctx, AVFrame *frame)
  322. {
  323. NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
  324. FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
  325. NVDECFrame *cf = NULL;
  326. int ret;
  327. ctx->bitstream_len = 0;
  328. ctx->nb_slices = 0;
  329. if (fdd->hwaccel_priv)
  330. return 0;
  331. cf = av_mallocz(sizeof(*cf));
  332. if (!cf)
  333. return AVERROR(ENOMEM);
  334. cf->decoder_ref = av_buffer_ref(ctx->decoder_ref);
  335. if (!cf->decoder_ref) {
  336. ret = AVERROR(ENOMEM);
  337. goto fail;
  338. }
  339. cf->idx_ref = av_buffer_pool_get(ctx->decoder_pool);
  340. if (!cf->idx_ref) {
  341. av_log(avctx, AV_LOG_ERROR, "No decoder surfaces left\n");
  342. ret = AVERROR(ENOMEM);
  343. goto fail;
  344. }
  345. cf->idx = *(unsigned int*)cf->idx_ref->data;
  346. fdd->hwaccel_priv = cf;
  347. fdd->hwaccel_priv_free = nvdec_fdd_priv_free;
  348. fdd->post_process = nvdec_retrieve_data;
  349. return 0;
  350. fail:
  351. nvdec_fdd_priv_free(cf);
  352. return ret;
  353. }
  354. int ff_nvdec_end_frame(AVCodecContext *avctx)
  355. {
  356. NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
  357. NVDECDecoder *decoder = (NVDECDecoder*)ctx->decoder_ref->data;
  358. CUVIDPICPARAMS *pp = &ctx->pic_params;
  359. CUresult err;
  360. CUcontext dummy;
  361. int ret = 0;
  362. pp->nBitstreamDataLen = ctx->bitstream_len;
  363. pp->pBitstreamData = ctx->bitstream;
  364. pp->nNumSlices = ctx->nb_slices;
  365. pp->pSliceDataOffsets = ctx->slice_offsets;
  366. err = decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx);
  367. if (err != CUDA_SUCCESS)
  368. return AVERROR_UNKNOWN;
  369. err = decoder->cvdl->cuvidDecodePicture(decoder->decoder, &ctx->pic_params);
  370. if (err != CUDA_SUCCESS) {
  371. av_log(avctx, AV_LOG_ERROR, "Error decoding a picture with NVDEC: %d\n",
  372. err);
  373. ret = AVERROR_UNKNOWN;
  374. goto finish;
  375. }
  376. finish:
  377. decoder->cudl->cuCtxPopCurrent(&dummy);
  378. return ret;
  379. }
  380. int ff_nvdec_frame_params(AVCodecContext *avctx,
  381. AVBufferRef *hw_frames_ctx,
  382. int dpb_size)
  383. {
  384. AVHWFramesContext *frames_ctx = (AVHWFramesContext*)hw_frames_ctx->data;
  385. const AVPixFmtDescriptor *sw_desc;
  386. int cuvid_codec_type, cuvid_chroma_format;
  387. sw_desc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);
  388. if (!sw_desc)
  389. return AVERROR_BUG;
  390. cuvid_codec_type = map_avcodec_id(avctx->codec_id);
  391. if (cuvid_codec_type < 0) {
  392. av_log(avctx, AV_LOG_ERROR, "Unsupported codec ID\n");
  393. return AVERROR_BUG;
  394. }
  395. cuvid_chroma_format = map_chroma_format(avctx->sw_pix_fmt);
  396. if (cuvid_chroma_format < 0) {
  397. av_log(avctx, AV_LOG_VERBOSE, "Unsupported chroma format\n");
  398. return AVERROR(EINVAL);
  399. }
  400. frames_ctx->format = AV_PIX_FMT_CUDA;
  401. frames_ctx->width = avctx->coded_width;
  402. frames_ctx->height = avctx->coded_height;
  403. frames_ctx->initial_pool_size = dpb_size;
  404. switch (sw_desc->comp[0].depth) {
  405. case 8:
  406. frames_ctx->sw_format = AV_PIX_FMT_NV12;
  407. break;
  408. case 10:
  409. frames_ctx->sw_format = AV_PIX_FMT_P010;
  410. break;
  411. case 12:
  412. frames_ctx->sw_format = AV_PIX_FMT_P016;
  413. break;
  414. default:
  415. return AVERROR(EINVAL);
  416. }
  417. return 0;
  418. }