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.

498 lines
14KB

  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. }
  50. return -1;
  51. }
  52. static int map_chroma_format(enum AVPixelFormat pix_fmt)
  53. {
  54. int shift_h = 0, shift_v = 0;
  55. av_pix_fmt_get_chroma_sub_sample(pix_fmt, &shift_h, &shift_v);
  56. if (shift_h == 1 && shift_v == 1)
  57. return cudaVideoChromaFormat_420;
  58. else if (shift_h == 1 && shift_v == 0)
  59. return cudaVideoChromaFormat_422;
  60. else if (shift_h == 0 && shift_v == 0)
  61. return cudaVideoChromaFormat_444;
  62. return -1;
  63. }
  64. static int nvdec_test_capabilities(NVDECDecoder *decoder,
  65. CUVIDDECODECREATEINFO *params, void *logctx)
  66. {
  67. CUresult err;
  68. CUVIDDECODECAPS caps = { 0 };
  69. caps.eCodecType = params->CodecType;
  70. caps.eChromaFormat = params->ChromaFormat;
  71. caps.nBitDepthMinus8 = params->bitDepthMinus8;
  72. err = decoder->cvdl->cuvidGetDecoderCaps(&caps);
  73. if (err != CUDA_SUCCESS) {
  74. av_log(logctx, AV_LOG_ERROR, "Failed querying decoder capabilities\n");
  75. return AVERROR_UNKNOWN;
  76. }
  77. av_log(logctx, AV_LOG_VERBOSE, "NVDEC capabilities:\n");
  78. av_log(logctx, AV_LOG_VERBOSE, "format supported: %s, max_mb_count: %d\n",
  79. caps.bIsSupported ? "yes" : "no", caps.nMaxMBCount);
  80. av_log(logctx, AV_LOG_VERBOSE, "min_width: %d, max_width: %d\n",
  81. caps.nMinWidth, caps.nMaxWidth);
  82. av_log(logctx, AV_LOG_VERBOSE, "min_height: %d, max_height: %d\n",
  83. caps.nMinHeight, caps.nMaxHeight);
  84. if (!caps.bIsSupported) {
  85. av_log(logctx, AV_LOG_ERROR, "Hardware is lacking required capabilities\n");
  86. return AVERROR(EINVAL);
  87. }
  88. if (params->ulWidth > caps.nMaxWidth || params->ulWidth < caps.nMinWidth) {
  89. av_log(logctx, AV_LOG_ERROR, "Video width %d not within range from %d to %d\n",
  90. (int)params->ulWidth, caps.nMinWidth, caps.nMaxWidth);
  91. return AVERROR(EINVAL);
  92. }
  93. if (params->ulHeight > caps.nMaxHeight || params->ulHeight < caps.nMinHeight) {
  94. av_log(logctx, AV_LOG_ERROR, "Video height %d not within range from %d to %d\n",
  95. (int)params->ulHeight, caps.nMinHeight, caps.nMaxHeight);
  96. return AVERROR(EINVAL);
  97. }
  98. if ((params->ulWidth * params->ulHeight) / 256 > caps.nMaxMBCount) {
  99. av_log(logctx, AV_LOG_ERROR, "Video macroblock count %d exceeds maximum of %d\n",
  100. (int)(params->ulWidth * params->ulHeight) / 256, caps.nMaxMBCount);
  101. return AVERROR(EINVAL);
  102. }
  103. return 0;
  104. }
  105. static void nvdec_decoder_free(void *opaque, uint8_t *data)
  106. {
  107. NVDECDecoder *decoder = (NVDECDecoder*)data;
  108. if (decoder->decoder)
  109. decoder->cvdl->cuvidDestroyDecoder(decoder->decoder);
  110. av_buffer_unref(&decoder->hw_device_ref);
  111. cuvid_free_functions(&decoder->cvdl);
  112. av_freep(&decoder);
  113. }
  114. static int nvdec_decoder_create(AVBufferRef **out, AVBufferRef *hw_device_ref,
  115. CUVIDDECODECREATEINFO *params, void *logctx)
  116. {
  117. AVHWDeviceContext *hw_device_ctx = (AVHWDeviceContext*)hw_device_ref->data;
  118. AVCUDADeviceContext *device_hwctx = hw_device_ctx->hwctx;
  119. AVBufferRef *decoder_ref;
  120. NVDECDecoder *decoder;
  121. CUcontext dummy;
  122. CUresult err;
  123. int ret;
  124. decoder = av_mallocz(sizeof(*decoder));
  125. if (!decoder)
  126. return AVERROR(ENOMEM);
  127. decoder_ref = av_buffer_create((uint8_t*)decoder, sizeof(*decoder),
  128. nvdec_decoder_free, NULL, AV_BUFFER_FLAG_READONLY);
  129. if (!decoder_ref) {
  130. av_freep(&decoder);
  131. return AVERROR(ENOMEM);
  132. }
  133. decoder->hw_device_ref = av_buffer_ref(hw_device_ref);
  134. if (!decoder->hw_device_ref) {
  135. ret = AVERROR(ENOMEM);
  136. goto fail;
  137. }
  138. decoder->cuda_ctx = device_hwctx->cuda_ctx;
  139. decoder->cudl = device_hwctx->internal->cuda_dl;
  140. ret = cuvid_load_functions(&decoder->cvdl);
  141. if (ret < 0) {
  142. av_log(logctx, AV_LOG_ERROR, "Failed loading nvcuvid.\n");
  143. goto fail;
  144. }
  145. err = decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx);
  146. if (err != CUDA_SUCCESS) {
  147. ret = AVERROR_UNKNOWN;
  148. goto fail;
  149. }
  150. ret = nvdec_test_capabilities(decoder, params, logctx);
  151. if (ret < 0) {
  152. decoder->cudl->cuCtxPopCurrent(&dummy);
  153. goto fail;
  154. }
  155. err = decoder->cvdl->cuvidCreateDecoder(&decoder->decoder, params);
  156. decoder->cudl->cuCtxPopCurrent(&dummy);
  157. if (err != CUDA_SUCCESS) {
  158. av_log(logctx, AV_LOG_ERROR, "Error creating a NVDEC decoder: %d\n", err);
  159. ret = AVERROR_UNKNOWN;
  160. goto fail;
  161. }
  162. *out = decoder_ref;
  163. return 0;
  164. fail:
  165. av_buffer_unref(&decoder_ref);
  166. return ret;
  167. }
  168. static AVBufferRef *nvdec_decoder_frame_alloc(void *opaque, int size)
  169. {
  170. NVDECFramePool *pool = opaque;
  171. AVBufferRef *ret;
  172. if (pool->nb_allocated >= pool->dpb_size)
  173. return NULL;
  174. ret = av_buffer_alloc(sizeof(unsigned int));
  175. if (!ret)
  176. return NULL;
  177. *(unsigned int*)ret->data = pool->nb_allocated++;
  178. return ret;
  179. }
  180. int ff_nvdec_decode_uninit(AVCodecContext *avctx)
  181. {
  182. NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
  183. av_freep(&ctx->bitstream);
  184. ctx->bitstream_len = 0;
  185. ctx->bitstream_allocated = 0;
  186. av_freep(&ctx->slice_offsets);
  187. ctx->nb_slices = 0;
  188. ctx->slice_offsets_allocated = 0;
  189. av_buffer_unref(&ctx->decoder_ref);
  190. av_buffer_pool_uninit(&ctx->decoder_pool);
  191. return 0;
  192. }
  193. int ff_nvdec_decode_init(AVCodecContext *avctx)
  194. {
  195. NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
  196. NVDECFramePool *pool;
  197. AVHWFramesContext *frames_ctx;
  198. const AVPixFmtDescriptor *sw_desc;
  199. CUVIDDECODECREATEINFO params = { 0 };
  200. int cuvid_codec_type, cuvid_chroma_format;
  201. int ret = 0;
  202. sw_desc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);
  203. if (!sw_desc)
  204. return AVERROR_BUG;
  205. cuvid_codec_type = map_avcodec_id(avctx->codec_id);
  206. if (cuvid_codec_type < 0) {
  207. av_log(avctx, AV_LOG_ERROR, "Unsupported codec ID\n");
  208. return AVERROR_BUG;
  209. }
  210. cuvid_chroma_format = map_chroma_format(avctx->sw_pix_fmt);
  211. if (cuvid_chroma_format < 0) {
  212. av_log(avctx, AV_LOG_ERROR, "Unsupported chroma format\n");
  213. return AVERROR(ENOSYS);
  214. }
  215. if (!avctx->hw_frames_ctx) {
  216. ret = ff_decode_get_hw_frames_ctx(avctx, AV_HWDEVICE_TYPE_CUDA);
  217. if (ret < 0)
  218. return ret;
  219. }
  220. frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  221. params.ulWidth = avctx->coded_width;
  222. params.ulHeight = avctx->coded_height;
  223. params.ulTargetWidth = avctx->coded_width;
  224. params.ulTargetHeight = avctx->coded_height;
  225. params.bitDepthMinus8 = sw_desc->comp[0].depth - 8;
  226. params.OutputFormat = params.bitDepthMinus8 ?
  227. cudaVideoSurfaceFormat_P016 : cudaVideoSurfaceFormat_NV12;
  228. params.CodecType = cuvid_codec_type;
  229. params.ChromaFormat = cuvid_chroma_format;
  230. params.ulNumDecodeSurfaces = frames_ctx->initial_pool_size;
  231. params.ulNumOutputSurfaces = 1;
  232. ret = nvdec_decoder_create(&ctx->decoder_ref, frames_ctx->device_ref, &params, avctx);
  233. if (ret < 0)
  234. return ret;
  235. pool = av_mallocz(sizeof(*pool));
  236. if (!pool) {
  237. ret = AVERROR(ENOMEM);
  238. goto fail;
  239. }
  240. pool->dpb_size = frames_ctx->initial_pool_size;
  241. ctx->decoder_pool = av_buffer_pool_init2(sizeof(int), pool,
  242. nvdec_decoder_frame_alloc, av_free);
  243. if (!ctx->decoder_pool) {
  244. ret = AVERROR(ENOMEM);
  245. goto fail;
  246. }
  247. return 0;
  248. fail:
  249. ff_nvdec_decode_uninit(avctx);
  250. return ret;
  251. }
  252. static void nvdec_fdd_priv_free(void *priv)
  253. {
  254. NVDECFrame *cf = priv;
  255. if (!cf)
  256. return;
  257. av_buffer_unref(&cf->idx_ref);
  258. av_buffer_unref(&cf->decoder_ref);
  259. av_freep(&priv);
  260. }
  261. static int nvdec_retrieve_data(void *logctx, AVFrame *frame)
  262. {
  263. FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
  264. NVDECFrame *cf = (NVDECFrame*)fdd->hwaccel_priv;
  265. NVDECDecoder *decoder = (NVDECDecoder*)cf->decoder_ref->data;
  266. CUVIDPROCPARAMS vpp = { .progressive_frame = 1 };
  267. CUresult err;
  268. CUcontext dummy;
  269. CUdeviceptr devptr;
  270. unsigned int pitch, i;
  271. unsigned int offset = 0;
  272. int ret = 0;
  273. err = decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx);
  274. if (err != CUDA_SUCCESS)
  275. return AVERROR_UNKNOWN;
  276. err = decoder->cvdl->cuvidMapVideoFrame(decoder->decoder, cf->idx, &devptr,
  277. &pitch, &vpp);
  278. if (err != CUDA_SUCCESS) {
  279. av_log(logctx, AV_LOG_ERROR, "Error mapping a picture with CUVID: %d\n",
  280. err);
  281. ret = AVERROR_UNKNOWN;
  282. goto finish;
  283. }
  284. for (i = 0; frame->data[i]; i++) {
  285. CUDA_MEMCPY2D cpy = {
  286. .srcMemoryType = CU_MEMORYTYPE_DEVICE,
  287. .dstMemoryType = CU_MEMORYTYPE_DEVICE,
  288. .srcDevice = devptr,
  289. .dstDevice = (CUdeviceptr)frame->data[i],
  290. .srcPitch = pitch,
  291. .dstPitch = frame->linesize[i],
  292. .srcY = offset,
  293. .WidthInBytes = FFMIN(pitch, frame->linesize[i]),
  294. .Height = frame->height >> (i ? 1 : 0),
  295. };
  296. err = decoder->cudl->cuMemcpy2D(&cpy);
  297. if (err != CUDA_SUCCESS) {
  298. av_log(logctx, AV_LOG_ERROR, "Error copying decoded frame: %d\n",
  299. err);
  300. ret = AVERROR_UNKNOWN;
  301. goto copy_fail;
  302. }
  303. offset += cpy.Height;
  304. }
  305. copy_fail:
  306. decoder->cvdl->cuvidUnmapVideoFrame(decoder->decoder, devptr);
  307. finish:
  308. decoder->cudl->cuCtxPopCurrent(&dummy);
  309. return ret;
  310. }
  311. int ff_nvdec_start_frame(AVCodecContext *avctx, AVFrame *frame)
  312. {
  313. NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
  314. FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
  315. NVDECFrame *cf = NULL;
  316. int ret;
  317. ctx->bitstream_len = 0;
  318. ctx->nb_slices = 0;
  319. if (fdd->hwaccel_priv)
  320. return 0;
  321. cf = av_mallocz(sizeof(*cf));
  322. if (!cf)
  323. return AVERROR(ENOMEM);
  324. cf->decoder_ref = av_buffer_ref(ctx->decoder_ref);
  325. if (!cf->decoder_ref)
  326. goto fail;
  327. cf->idx_ref = av_buffer_pool_get(ctx->decoder_pool);
  328. if (!cf->idx_ref) {
  329. av_log(avctx, AV_LOG_ERROR, "No decoder surfaces left\n");
  330. ret = AVERROR(ENOMEM);
  331. goto fail;
  332. }
  333. cf->idx = *(unsigned int*)cf->idx_ref->data;
  334. fdd->hwaccel_priv = cf;
  335. fdd->hwaccel_priv_free = nvdec_fdd_priv_free;
  336. fdd->post_process = nvdec_retrieve_data;
  337. return 0;
  338. fail:
  339. nvdec_fdd_priv_free(cf);
  340. return ret;
  341. }
  342. int ff_nvdec_end_frame(AVCodecContext *avctx)
  343. {
  344. NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
  345. NVDECDecoder *decoder = (NVDECDecoder*)ctx->decoder_ref->data;
  346. CUVIDPICPARAMS *pp = &ctx->pic_params;
  347. CUresult err;
  348. CUcontext dummy;
  349. int ret = 0;
  350. pp->nBitstreamDataLen = ctx->bitstream_len;
  351. pp->pBitstreamData = ctx->bitstream;
  352. pp->nNumSlices = ctx->nb_slices;
  353. pp->pSliceDataOffsets = ctx->slice_offsets;
  354. err = decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx);
  355. if (err != CUDA_SUCCESS)
  356. return AVERROR_UNKNOWN;
  357. err = decoder->cvdl->cuvidDecodePicture(decoder->decoder, &ctx->pic_params);
  358. if (err != CUDA_SUCCESS) {
  359. av_log(avctx, AV_LOG_ERROR, "Error decoding a picture with NVDEC: %d\n",
  360. err);
  361. ret = AVERROR_UNKNOWN;
  362. goto finish;
  363. }
  364. finish:
  365. decoder->cudl->cuCtxPopCurrent(&dummy);
  366. return ret;
  367. }
  368. int ff_nvdec_frame_params(AVCodecContext *avctx,
  369. AVBufferRef *hw_frames_ctx,
  370. int dpb_size)
  371. {
  372. AVHWFramesContext *frames_ctx = (AVHWFramesContext*)hw_frames_ctx->data;
  373. const AVPixFmtDescriptor *sw_desc;
  374. int cuvid_codec_type, cuvid_chroma_format;
  375. sw_desc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);
  376. if (!sw_desc)
  377. return AVERROR_BUG;
  378. cuvid_codec_type = map_avcodec_id(avctx->codec_id);
  379. if (cuvid_codec_type < 0) {
  380. av_log(avctx, AV_LOG_ERROR, "Unsupported codec ID\n");
  381. return AVERROR_BUG;
  382. }
  383. cuvid_chroma_format = map_chroma_format(avctx->sw_pix_fmt);
  384. if (cuvid_chroma_format < 0) {
  385. av_log(avctx, AV_LOG_VERBOSE, "Unsupported chroma format\n");
  386. return AVERROR(EINVAL);
  387. }
  388. frames_ctx->format = AV_PIX_FMT_CUDA;
  389. frames_ctx->width = avctx->coded_width;
  390. frames_ctx->height = avctx->coded_height;
  391. frames_ctx->sw_format = sw_desc->comp[0].depth > 8 ?
  392. AV_PIX_FMT_P010 : AV_PIX_FMT_NV12;
  393. frames_ctx->initial_pool_size = dpb_size;
  394. return 0;
  395. }