qsvdec.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. /*
  2. * Copyright (c) 2015 Anton Khirnov
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  17. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. * THE SOFTWARE.
  21. */
  22. /**
  23. * @file
  24. * Intel QSV-accelerated H.264 decoding example.
  25. *
  26. * @example qsvdec.c
  27. * This example shows how to do QSV-accelerated H.264 decoding with output
  28. * frames in the VA-API video surfaces.
  29. */
  30. #include "config.h"
  31. #include <stdio.h>
  32. #include <mfx/mfxvideo.h>
  33. #include <va/va.h>
  34. #include <va/va_x11.h>
  35. #include <X11/Xlib.h>
  36. #include "libavformat/avformat.h"
  37. #include "libavformat/avio.h"
  38. #include "libavcodec/avcodec.h"
  39. #include "libavcodec/qsv.h"
  40. #include "libavutil/error.h"
  41. #include "libavutil/mem.h"
  42. typedef struct DecodeContext {
  43. mfxSession mfx_session;
  44. VADisplay va_dpy;
  45. VASurfaceID *surfaces;
  46. mfxMemId *surface_ids;
  47. int *surface_used;
  48. int nb_surfaces;
  49. mfxFrameInfo frame_info;
  50. } DecodeContext;
  51. static mfxStatus frame_alloc(mfxHDL pthis, mfxFrameAllocRequest *req,
  52. mfxFrameAllocResponse *resp)
  53. {
  54. DecodeContext *decode = pthis;
  55. int err, i;
  56. if (decode->surfaces) {
  57. fprintf(stderr, "Multiple allocation requests.\n");
  58. return MFX_ERR_MEMORY_ALLOC;
  59. }
  60. if (!(req->Type & MFX_MEMTYPE_VIDEO_MEMORY_DECODER_TARGET)) {
  61. fprintf(stderr, "Unsupported surface type: %d\n", req->Type);
  62. return MFX_ERR_UNSUPPORTED;
  63. }
  64. if (req->Info.BitDepthLuma != 8 || req->Info.BitDepthChroma != 8 ||
  65. req->Info.Shift || req->Info.FourCC != MFX_FOURCC_NV12 ||
  66. req->Info.ChromaFormat != MFX_CHROMAFORMAT_YUV420) {
  67. fprintf(stderr, "Unsupported surface properties.\n");
  68. return MFX_ERR_UNSUPPORTED;
  69. }
  70. decode->surfaces = av_malloc_array (req->NumFrameSuggested, sizeof(*decode->surfaces));
  71. decode->surface_ids = av_malloc_array (req->NumFrameSuggested, sizeof(*decode->surface_ids));
  72. decode->surface_used = av_mallocz_array(req->NumFrameSuggested, sizeof(*decode->surface_used));
  73. if (!decode->surfaces || !decode->surface_ids || !decode->surface_used)
  74. goto fail;
  75. err = vaCreateSurfaces(decode->va_dpy, VA_RT_FORMAT_YUV420,
  76. req->Info.Width, req->Info.Height,
  77. decode->surfaces, req->NumFrameSuggested,
  78. NULL, 0);
  79. if (err != VA_STATUS_SUCCESS) {
  80. fprintf(stderr, "Error allocating VA surfaces\n");
  81. goto fail;
  82. }
  83. decode->nb_surfaces = req->NumFrameSuggested;
  84. for (i = 0; i < decode->nb_surfaces; i++)
  85. decode->surface_ids[i] = &decode->surfaces[i];
  86. resp->mids = decode->surface_ids;
  87. resp->NumFrameActual = decode->nb_surfaces;
  88. decode->frame_info = req->Info;
  89. return MFX_ERR_NONE;
  90. fail:
  91. av_freep(&decode->surfaces);
  92. av_freep(&decode->surface_ids);
  93. av_freep(&decode->surface_used);
  94. return MFX_ERR_MEMORY_ALLOC;
  95. }
  96. static mfxStatus frame_free(mfxHDL pthis, mfxFrameAllocResponse *resp)
  97. {
  98. return MFX_ERR_NONE;
  99. }
  100. static mfxStatus frame_lock(mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr)
  101. {
  102. return MFX_ERR_UNSUPPORTED;
  103. }
  104. static mfxStatus frame_unlock(mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr)
  105. {
  106. return MFX_ERR_UNSUPPORTED;
  107. }
  108. static mfxStatus frame_get_hdl(mfxHDL pthis, mfxMemId mid, mfxHDL *hdl)
  109. {
  110. *hdl = mid;
  111. return MFX_ERR_NONE;
  112. }
  113. static void free_surfaces(DecodeContext *decode)
  114. {
  115. if (decode->surfaces)
  116. vaDestroySurfaces(decode->va_dpy, decode->surfaces, decode->nb_surfaces);
  117. av_freep(&decode->surfaces);
  118. av_freep(&decode->surface_ids);
  119. av_freep(&decode->surface_used);
  120. decode->nb_surfaces = 0;
  121. }
  122. static void free_buffer(void *opaque, uint8_t *data)
  123. {
  124. int *used = opaque;
  125. *used = 0;
  126. av_freep(&data);
  127. }
  128. static int get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)
  129. {
  130. DecodeContext *decode = avctx->opaque;
  131. mfxFrameSurface1 *surf;
  132. AVBufferRef *surf_buf;
  133. int idx;
  134. for (idx = 0; idx < decode->nb_surfaces; idx++) {
  135. if (!decode->surface_used[idx])
  136. break;
  137. }
  138. if (idx == decode->nb_surfaces) {
  139. fprintf(stderr, "No free surfaces\n");
  140. return AVERROR(ENOMEM);
  141. }
  142. surf = av_mallocz(sizeof(*surf));
  143. if (!surf)
  144. return AVERROR(ENOMEM);
  145. surf_buf = av_buffer_create((uint8_t*)surf, sizeof(*surf), free_buffer,
  146. &decode->surface_used[idx], AV_BUFFER_FLAG_READONLY);
  147. if (!surf_buf) {
  148. av_freep(&surf);
  149. return AVERROR(ENOMEM);
  150. }
  151. surf->Info = decode->frame_info;
  152. surf->Data.MemId = &decode->surfaces[idx];
  153. frame->buf[0] = surf_buf;
  154. frame->data[3] = (uint8_t*)surf;
  155. decode->surface_used[idx] = 1;
  156. return 0;
  157. }
  158. static int get_format(AVCodecContext *avctx, const enum AVPixelFormat *pix_fmts)
  159. {
  160. while (*pix_fmts != AV_PIX_FMT_NONE) {
  161. if (*pix_fmts == AV_PIX_FMT_QSV) {
  162. if (!avctx->hwaccel_context) {
  163. DecodeContext *decode = avctx->opaque;
  164. AVQSVContext *qsv = av_qsv_alloc_context();
  165. if (!qsv)
  166. return AV_PIX_FMT_NONE;
  167. qsv->session = decode->mfx_session;
  168. qsv->iopattern = MFX_IOPATTERN_OUT_VIDEO_MEMORY;
  169. avctx->hwaccel_context = qsv;
  170. }
  171. return AV_PIX_FMT_QSV;
  172. }
  173. pix_fmts++;
  174. }
  175. fprintf(stderr, "The QSV pixel format not offered in get_format()\n");
  176. return AV_PIX_FMT_NONE;
  177. }
  178. static int decode_packet(DecodeContext *decode, AVCodecContext *decoder_ctx,
  179. AVFrame *frame, AVPacket *pkt,
  180. AVIOContext *output_ctx)
  181. {
  182. int ret = 0;
  183. int got_frame = 1;
  184. while (pkt->size > 0 || (!pkt->data && got_frame)) {
  185. ret = avcodec_decode_video2(decoder_ctx, frame, &got_frame, pkt);
  186. if (ret < 0) {
  187. fprintf(stderr, "Error during decoding\n");
  188. return ret;
  189. }
  190. pkt->data += ret;
  191. pkt->size -= ret;
  192. /* A real program would do something useful with the decoded frame here.
  193. * We just retrieve the raw data and write it to a file, which is rather
  194. * useless but pedagogic. */
  195. if (got_frame) {
  196. mfxFrameSurface1 *surf = (mfxFrameSurface1*)frame->data[3];
  197. VASurfaceID surface = *(VASurfaceID*)surf->Data.MemId;
  198. VAImageFormat img_fmt = {
  199. .fourcc = VA_FOURCC_NV12,
  200. .byte_order = VA_LSB_FIRST,
  201. .bits_per_pixel = 8,
  202. .depth = 8,
  203. };
  204. VAImage img;
  205. VAStatus err;
  206. uint8_t *data;
  207. int i, j;
  208. img.buf = VA_INVALID_ID;
  209. img.image_id = VA_INVALID_ID;
  210. err = vaCreateImage(decode->va_dpy, &img_fmt,
  211. frame->width, frame->height, &img);
  212. if (err != VA_STATUS_SUCCESS) {
  213. fprintf(stderr, "Error creating an image: %s\n",
  214. vaErrorStr(err));
  215. ret = AVERROR_UNKNOWN;
  216. goto fail;
  217. }
  218. err = vaGetImage(decode->va_dpy, surface, 0, 0,
  219. frame->width, frame->height,
  220. img.image_id);
  221. if (err != VA_STATUS_SUCCESS) {
  222. fprintf(stderr, "Error getting an image: %s\n",
  223. vaErrorStr(err));
  224. ret = AVERROR_UNKNOWN;
  225. goto fail;
  226. }
  227. err = vaMapBuffer(decode->va_dpy, img.buf, (void**)&data);
  228. if (err != VA_STATUS_SUCCESS) {
  229. fprintf(stderr, "Error mapping the image buffer: %s\n",
  230. vaErrorStr(err));
  231. ret = AVERROR_UNKNOWN;
  232. goto fail;
  233. }
  234. for (i = 0; i < img.num_planes; i++)
  235. for (j = 0; j < (img.height >> (i > 0)); j++)
  236. avio_write(output_ctx, data + img.offsets[i] + j * img.pitches[i], img.width);
  237. fail:
  238. if (img.buf != VA_INVALID_ID)
  239. vaUnmapBuffer(decode->va_dpy, img.buf);
  240. if (img.image_id != VA_INVALID_ID)
  241. vaDestroyImage(decode->va_dpy, img.image_id);
  242. av_frame_unref(frame);
  243. if (ret < 0)
  244. return ret;
  245. }
  246. }
  247. return 0;
  248. }
  249. int main(int argc, char **argv)
  250. {
  251. AVFormatContext *input_ctx = NULL;
  252. AVStream *video_st = NULL;
  253. AVCodecContext *decoder_ctx = NULL;
  254. const AVCodec *decoder;
  255. AVPacket pkt = { 0 };
  256. AVFrame *frame = NULL;
  257. DecodeContext decode = { NULL };
  258. Display *dpy = NULL;
  259. int va_ver_major, va_ver_minor;
  260. mfxIMPL mfx_impl = MFX_IMPL_AUTO_ANY;
  261. mfxVersion mfx_ver = { { 1, 1 } };
  262. mfxFrameAllocator frame_allocator = {
  263. .pthis = &decode,
  264. .Alloc = frame_alloc,
  265. .Lock = frame_lock,
  266. .Unlock = frame_unlock,
  267. .GetHDL = frame_get_hdl,
  268. .Free = frame_free,
  269. };
  270. AVIOContext *output_ctx = NULL;
  271. int ret, i, err;
  272. av_register_all();
  273. if (argc < 3) {
  274. fprintf(stderr, "Usage: %s <input file> <output file>\n", argv[0]);
  275. return 1;
  276. }
  277. /* open the input file */
  278. ret = avformat_open_input(&input_ctx, argv[1], NULL, NULL);
  279. if (ret < 0) {
  280. fprintf(stderr, "Cannot open input file '%s': ", argv[1]);
  281. goto finish;
  282. }
  283. /* find the first H.264 video stream */
  284. for (i = 0; i < input_ctx->nb_streams; i++) {
  285. AVStream *st = input_ctx->streams[i];
  286. if (st->codecpar->codec_id == AV_CODEC_ID_H264 && !video_st)
  287. video_st = st;
  288. else
  289. st->discard = AVDISCARD_ALL;
  290. }
  291. if (!video_st) {
  292. fprintf(stderr, "No H.264 video stream in the input file\n");
  293. goto finish;
  294. }
  295. /* initialize VA-API */
  296. dpy = XOpenDisplay(NULL);
  297. if (!dpy) {
  298. fprintf(stderr, "Cannot open the X display\n");
  299. goto finish;
  300. }
  301. decode.va_dpy = vaGetDisplay(dpy);
  302. if (!decode.va_dpy) {
  303. fprintf(stderr, "Cannot open the VA display\n");
  304. goto finish;
  305. }
  306. err = vaInitialize(decode.va_dpy, &va_ver_major, &va_ver_minor);
  307. if (err != VA_STATUS_SUCCESS) {
  308. fprintf(stderr, "Cannot initialize VA: %s\n", vaErrorStr(err));
  309. goto finish;
  310. }
  311. fprintf(stderr, "Initialized VA v%d.%d\n", va_ver_major, va_ver_minor);
  312. /* initialize an MFX session */
  313. err = MFXInit(mfx_impl, &mfx_ver, &decode.mfx_session);
  314. if (err != MFX_ERR_NONE) {
  315. fprintf(stderr, "Error initializing an MFX session\n");
  316. goto finish;
  317. }
  318. MFXVideoCORE_SetHandle(decode.mfx_session, MFX_HANDLE_VA_DISPLAY, decode.va_dpy);
  319. MFXVideoCORE_SetFrameAllocator(decode.mfx_session, &frame_allocator);
  320. /* initialize the decoder */
  321. decoder = avcodec_find_decoder_by_name("h264_qsv");
  322. if (!decoder) {
  323. fprintf(stderr, "The QSV decoder is not present in libavcodec\n");
  324. goto finish;
  325. }
  326. decoder_ctx = avcodec_alloc_context3(decoder);
  327. if (!decoder_ctx) {
  328. ret = AVERROR(ENOMEM);
  329. goto finish;
  330. }
  331. decoder_ctx->codec_id = AV_CODEC_ID_H264;
  332. if (video_st->codecpar->extradata_size) {
  333. decoder_ctx->extradata = av_mallocz(video_st->codecpar->extradata_size +
  334. AV_INPUT_BUFFER_PADDING_SIZE);
  335. if (!decoder_ctx->extradata) {
  336. ret = AVERROR(ENOMEM);
  337. goto finish;
  338. }
  339. memcpy(decoder_ctx->extradata, video_st->codecpar->extradata,
  340. video_st->codecpar->extradata_size);
  341. decoder_ctx->extradata_size = video_st->codecpar->extradata_size;
  342. }
  343. decoder_ctx->refcounted_frames = 1;
  344. decoder_ctx->opaque = &decode;
  345. decoder_ctx->get_buffer2 = get_buffer;
  346. decoder_ctx->get_format = get_format;
  347. ret = avcodec_open2(decoder_ctx, NULL, NULL);
  348. if (ret < 0) {
  349. fprintf(stderr, "Error opening the decoder: ");
  350. goto finish;
  351. }
  352. /* open the output stream */
  353. ret = avio_open(&output_ctx, argv[2], AVIO_FLAG_WRITE);
  354. if (ret < 0) {
  355. fprintf(stderr, "Error opening the output context: ");
  356. goto finish;
  357. }
  358. frame = av_frame_alloc();
  359. if (!frame) {
  360. ret = AVERROR(ENOMEM);
  361. goto finish;
  362. }
  363. /* actual decoding */
  364. while (ret >= 0) {
  365. ret = av_read_frame(input_ctx, &pkt);
  366. if (ret < 0)
  367. break;
  368. if (pkt.stream_index == video_st->index)
  369. ret = decode_packet(&decode, decoder_ctx, frame, &pkt, output_ctx);
  370. av_packet_unref(&pkt);
  371. }
  372. /* flush the decoder */
  373. pkt.data = NULL;
  374. pkt.size = 0;
  375. ret = decode_packet(&decode, decoder_ctx, frame, &pkt, output_ctx);
  376. finish:
  377. if (ret < 0) {
  378. char buf[1024];
  379. av_strerror(ret, buf, sizeof(buf));
  380. fprintf(stderr, "%s\n", buf);
  381. }
  382. avformat_close_input(&input_ctx);
  383. av_frame_free(&frame);
  384. if (decoder_ctx)
  385. av_freep(&decoder_ctx->hwaccel_context);
  386. avcodec_free_context(&decoder_ctx);
  387. free_surfaces(&decode);
  388. if (decode.mfx_session)
  389. MFXClose(decode.mfx_session);
  390. if (decode.va_dpy)
  391. vaTerminate(decode.va_dpy);
  392. if (dpy)
  393. XCloseDisplay(dpy);
  394. avio_close(output_ctx);
  395. return ret;
  396. }