2 * Intel MediaSDK QSV codec-independent code
4 * copyright (c) 2013 Luca Barbato
5 * copyright (c) 2015 Anton Khirnov <anton@khirnov.net>
7 * This file is part of FFmpeg.
9 * FFmpeg is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public
11 * License as published by the Free Software Foundation; either
12 * version 2.1 of the License, or (at your option) any later version.
14 * FFmpeg is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with FFmpeg; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 #include <sys/types.h>
27 #include <mfx/mfxvideo.h>
29 #include "libavutil/common.h"
30 #include "libavutil/hwcontext.h"
31 #include "libavutil/hwcontext_qsv.h"
32 #include "libavutil/mem.h"
33 #include "libavutil/log.h"
34 #include "libavutil/pixdesc.h"
35 #include "libavutil/pixfmt.h"
36 #include "libavutil/time.h"
41 #include "qsv_internal.h"
44 const AVCodecHWConfigInternal *ff_qsv_hw_configs[] = {
45 &(const AVCodecHWConfigInternal) {
47 .pix_fmt = AV_PIX_FMT_QSV,
48 .methods = AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX |
49 AV_CODEC_HW_CONFIG_METHOD_AD_HOC,
50 .device_type = AV_HWDEVICE_TYPE_QSV,
57 static int qsv_init_session(AVCodecContext *avctx, QSVContext *q, mfxSession session,
58 AVBufferRef *hw_frames_ref, AVBufferRef *hw_device_ref)
64 } else if (hw_frames_ref) {
65 if (q->internal_session) {
66 MFXClose(q->internal_session);
67 q->internal_session = NULL;
69 av_buffer_unref(&q->frames_ctx.hw_frames_ctx);
71 q->frames_ctx.hw_frames_ctx = av_buffer_ref(hw_frames_ref);
72 if (!q->frames_ctx.hw_frames_ctx)
73 return AVERROR(ENOMEM);
75 ret = ff_qsv_init_session_frames(avctx, &q->internal_session,
76 &q->frames_ctx, q->load_plugins,
77 q->iopattern == MFX_IOPATTERN_OUT_OPAQUE_MEMORY);
79 av_buffer_unref(&q->frames_ctx.hw_frames_ctx);
83 q->session = q->internal_session;
84 } else if (hw_device_ref) {
85 if (q->internal_session) {
86 MFXClose(q->internal_session);
87 q->internal_session = NULL;
90 ret = ff_qsv_init_session_device(avctx, &q->internal_session,
91 hw_device_ref, q->load_plugins);
95 q->session = q->internal_session;
97 if (!q->internal_session) {
98 ret = ff_qsv_init_internal_session(avctx, &q->internal_session,
104 q->session = q->internal_session;
107 /* make sure the decoder is uninitialized */
108 MFXVideoDECODE_Close(q->session);
113 static inline unsigned int qsv_fifo_item_size(void)
115 return sizeof(mfxSyncPoint*) + sizeof(QSVFrame*);
118 static inline unsigned int qsv_fifo_size(const AVFifoBuffer* fifo)
120 return av_fifo_size(fifo) / qsv_fifo_item_size();
123 static int check_dec_param(AVCodecContext *avctx, QSVContext *q, mfxVideoParam *param_in)
125 mfxVideoParam param_out = { .mfx.CodecId = param_in->mfx.CodecId };
128 #define CHECK_MATCH(x) \
130 if (param_out.mfx.x != param_in->mfx.x) { \
131 av_log(avctx, AV_LOG_WARNING, "Required "#x" %d is unsupported\n", \
136 ret = MFXVideoDECODE_Query(q->session, param_in, ¶m_out);
139 CHECK_MATCH(CodecId);
140 CHECK_MATCH(CodecProfile);
141 CHECK_MATCH(CodecLevel);
142 CHECK_MATCH(FrameInfo.Width);
143 CHECK_MATCH(FrameInfo.Height);
150 static int qsv_decode_init(AVCodecContext *avctx, QSVContext *q)
152 const AVPixFmtDescriptor *desc;
153 mfxSession session = NULL;
155 mfxVideoParam param = { 0 };
156 int frame_width = avctx->coded_width;
157 int frame_height = avctx->coded_height;
160 desc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);
164 if (!q->async_fifo) {
165 q->async_fifo = av_fifo_alloc(q->async_depth * qsv_fifo_item_size());
167 return AVERROR(ENOMEM);
170 if (avctx->pix_fmt == AV_PIX_FMT_QSV && avctx->hwaccel_context) {
171 AVQSVContext *user_ctx = avctx->hwaccel_context;
172 session = user_ctx->session;
173 iopattern = user_ctx->iopattern;
174 q->ext_buffers = user_ctx->ext_buffers;
175 q->nb_ext_buffers = user_ctx->nb_ext_buffers;
178 if (avctx->hw_frames_ctx) {
179 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
180 AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
183 if (frames_hwctx->frame_type & MFX_MEMTYPE_OPAQUE_FRAME)
184 iopattern = MFX_IOPATTERN_OUT_OPAQUE_MEMORY;
185 else if (frames_hwctx->frame_type & MFX_MEMTYPE_VIDEO_MEMORY_DECODER_TARGET)
186 iopattern = MFX_IOPATTERN_OUT_VIDEO_MEMORY;
191 iopattern = MFX_IOPATTERN_OUT_SYSTEM_MEMORY;
192 q->iopattern = iopattern;
194 ret = qsv_init_session(avctx, q, session, avctx->hw_frames_ctx, avctx->hw_device_ctx);
196 av_log(avctx, AV_LOG_ERROR, "Error initializing an MFX session\n");
200 ret = ff_qsv_codec_id_to_mfx(avctx->codec_id);
204 param.mfx.CodecId = ret;
205 param.mfx.CodecProfile = ff_qsv_profile_to_mfx(avctx->codec_id, avctx->profile);
206 param.mfx.CodecLevel = ff_qsv_level_to_mfx(avctx->codec_id, avctx->level);
208 param.mfx.FrameInfo.BitDepthLuma = desc->comp[0].depth;
209 param.mfx.FrameInfo.BitDepthChroma = desc->comp[0].depth;
210 param.mfx.FrameInfo.Shift = desc->comp[0].depth > 8;
211 param.mfx.FrameInfo.FourCC = q->fourcc;
212 param.mfx.FrameInfo.Width = frame_width;
213 param.mfx.FrameInfo.Height = frame_height;
214 param.mfx.FrameInfo.ChromaFormat = MFX_CHROMAFORMAT_YUV420;
216 switch (avctx->field_order) {
217 case AV_FIELD_PROGRESSIVE:
218 param.mfx.FrameInfo.PicStruct = MFX_PICSTRUCT_PROGRESSIVE;
221 param.mfx.FrameInfo.PicStruct = MFX_PICSTRUCT_FIELD_TFF;
224 param.mfx.FrameInfo.PicStruct = MFX_PICSTRUCT_FIELD_BFF;
227 param.mfx.FrameInfo.PicStruct = MFX_PICSTRUCT_UNKNOWN;
231 param.IOPattern = q->iopattern;
232 param.AsyncDepth = q->async_depth;
233 param.ExtParam = q->ext_buffers;
234 param.NumExtParam = q->nb_ext_buffers;
236 if (!check_dec_param(avctx, q, ¶m)) {
237 //Just give a warning instead of an error since it is still decodable possibly.
238 av_log(avctx, AV_LOG_WARNING,
239 "Current input bitstream is not supported by QSV decoder.\n");
242 ret = MFXVideoDECODE_Init(q->session, ¶m);
244 return ff_qsv_print_error(avctx, ret,
245 "Error initializing the MFX video decoder");
247 q->frame_info = param.mfx.FrameInfo;
252 static int alloc_frame(AVCodecContext *avctx, QSVContext *q, QSVFrame *frame)
256 ret = ff_get_buffer(avctx, frame->frame, AV_GET_BUFFER_FLAG_REF);
260 if (frame->frame->format == AV_PIX_FMT_QSV) {
261 frame->surface = *(mfxFrameSurface1*)frame->frame->data[3];
263 frame->surface.Info = q->frame_info;
265 frame->surface.Data.PitchLow = frame->frame->linesize[0];
266 frame->surface.Data.Y = frame->frame->data[0];
267 frame->surface.Data.UV = frame->frame->data[1];
270 if (q->frames_ctx.mids) {
271 ret = ff_qsv_find_surface_idx(&q->frames_ctx, frame);
275 frame->surface.Data.MemId = &q->frames_ctx.mids[ret];
277 frame->surface.Data.ExtParam = &frame->ext_param;
278 frame->surface.Data.NumExtParam = 1;
279 frame->ext_param = (mfxExtBuffer*)&frame->dec_info;
280 frame->dec_info.Header.BufferId = MFX_EXTBUFF_DECODED_FRAME_INFO;
281 frame->dec_info.Header.BufferSz = sizeof(frame->dec_info);
288 static void qsv_clear_unused_frames(QSVContext *q)
290 QSVFrame *cur = q->work_frames;
292 if (cur->used && !cur->surface.Data.Locked && !cur->queued) {
294 av_frame_unref(cur->frame);
300 static int get_surface(AVCodecContext *avctx, QSVContext *q, mfxFrameSurface1 **surf)
302 QSVFrame *frame, **last;
305 qsv_clear_unused_frames(q);
307 frame = q->work_frames;
308 last = &q->work_frames;
311 ret = alloc_frame(avctx, q, frame);
314 *surf = &frame->surface;
322 frame = av_mallocz(sizeof(*frame));
324 return AVERROR(ENOMEM);
325 frame->frame = av_frame_alloc();
328 return AVERROR(ENOMEM);
332 ret = alloc_frame(avctx, q, frame);
336 *surf = &frame->surface;
341 static QSVFrame *find_frame(QSVContext *q, mfxFrameSurface1 *surf)
343 QSVFrame *cur = q->work_frames;
345 if (surf == &cur->surface)
352 static int qsv_decode(AVCodecContext *avctx, QSVContext *q,
353 AVFrame *frame, int *got_frame,
357 mfxFrameSurface1 *insurf;
358 mfxFrameSurface1 *outsurf;
360 mfxBitstream bs = { { { 0 } } };
364 bs.Data = avpkt->data;
365 bs.DataLength = avpkt->size;
366 bs.MaxLength = bs.DataLength;
367 bs.TimeStamp = avpkt->pts;
368 if (avctx->field_order == AV_FIELD_PROGRESSIVE)
369 bs.DataFlag |= MFX_BITSTREAM_COMPLETE_FRAME;
372 sync = av_mallocz(sizeof(*sync));
375 return AVERROR(ENOMEM);
379 ret = get_surface(avctx, q, &insurf);
385 ret = MFXVideoDECODE_DecodeFrameAsync(q->session, avpkt->size ? &bs : NULL,
386 insurf, &outsurf, sync);
387 if (ret == MFX_WRN_DEVICE_BUSY)
390 } while (ret == MFX_WRN_DEVICE_BUSY || ret == MFX_ERR_MORE_SURFACE);
392 if (ret != MFX_ERR_NONE &&
393 ret != MFX_ERR_MORE_DATA &&
394 ret != MFX_WRN_VIDEO_PARAM_CHANGED &&
395 ret != MFX_ERR_MORE_SURFACE) {
397 return ff_qsv_print_error(avctx, ret,
398 "Error during QSV decoding.");
401 /* make sure we do not enter an infinite loop if the SDK
402 * did not consume any data and did not return anything */
403 if (!*sync && !bs.DataOffset) {
404 bs.DataOffset = avpkt->size;
405 ++q->zero_consume_run;
406 if (q->zero_consume_run > 1)
407 ff_qsv_print_warning(avctx, ret, "A decode call did not consume any data");
408 } else if (!*sync && bs.DataOffset) {
411 q->zero_consume_run = 0;
415 QSVFrame *out_frame = find_frame(q, outsurf);
418 av_log(avctx, AV_LOG_ERROR,
419 "The returned surface does not correspond to any frame\n");
424 out_frame->queued = 1;
425 av_fifo_generic_write(q->async_fifo, &out_frame, sizeof(out_frame), NULL);
426 av_fifo_generic_write(q->async_fifo, &sync, sizeof(sync), NULL);
431 if ((qsv_fifo_size(q->async_fifo) >= q->async_depth) ||
432 (!avpkt->size && av_fifo_size(q->async_fifo))) {
435 av_fifo_generic_read(q->async_fifo, &out_frame, sizeof(out_frame), NULL);
436 av_fifo_generic_read(q->async_fifo, &sync, sizeof(sync), NULL);
437 out_frame->queued = 0;
439 if (avctx->pix_fmt != AV_PIX_FMT_QSV) {
441 ret = MFXVideoCORE_SyncOperation(q->session, *sync, 1000);
442 } while (ret == MFX_WRN_IN_EXECUTION);
447 src_frame = out_frame->frame;
449 ret = av_frame_ref(frame, src_frame);
453 outsurf = &out_frame->surface;
456 FF_DISABLE_DEPRECATION_WARNINGS
457 frame->pkt_pts = outsurf->Data.TimeStamp;
458 FF_ENABLE_DEPRECATION_WARNINGS
460 frame->pts = outsurf->Data.TimeStamp;
463 outsurf->Info.PicStruct & MFX_PICSTRUCT_FRAME_TRIPLING ? 4 :
464 outsurf->Info.PicStruct & MFX_PICSTRUCT_FRAME_DOUBLING ? 2 :
465 outsurf->Info.PicStruct & MFX_PICSTRUCT_FIELD_REPEATED ? 1 : 0;
466 frame->top_field_first =
467 outsurf->Info.PicStruct & MFX_PICSTRUCT_FIELD_TFF;
468 frame->interlaced_frame =
469 !(outsurf->Info.PicStruct & MFX_PICSTRUCT_PROGRESSIVE);
470 frame->pict_type = ff_qsv_map_pictype(out_frame->dec_info.FrameType);
471 //Key frame is IDR frame is only suitable for H264. For HEVC, IRAPs are key frames.
472 if (avctx->codec_id == AV_CODEC_ID_H264)
473 frame->key_frame = !!(out_frame->dec_info.FrameType & MFX_FRAMETYPE_IDR);
475 /* update the surface properties */
476 if (avctx->pix_fmt == AV_PIX_FMT_QSV)
477 ((mfxFrameSurface1*)frame->data[3])->Info = outsurf->Info;
482 return bs.DataOffset;
485 int ff_qsv_decode_close(QSVContext *q)
487 QSVFrame *cur = q->work_frames;
490 MFXVideoDECODE_Close(q->session);
492 while (q->async_fifo && av_fifo_size(q->async_fifo)) {
496 av_fifo_generic_read(q->async_fifo, &out_frame, sizeof(out_frame), NULL);
497 av_fifo_generic_read(q->async_fifo, &sync, sizeof(sync), NULL);
503 q->work_frames = cur->next;
504 av_frame_free(&cur->frame);
506 cur = q->work_frames;
509 av_fifo_free(q->async_fifo);
510 q->async_fifo = NULL;
512 av_parser_close(q->parser);
513 avcodec_free_context(&q->avctx_internal);
515 if (q->internal_session)
516 MFXClose(q->internal_session);
518 av_buffer_unref(&q->frames_ctx.hw_frames_ctx);
519 av_buffer_unref(&q->frames_ctx.mids_buf);
524 int ff_qsv_process_data(AVCodecContext *avctx, QSVContext *q,
525 AVFrame *frame, int *got_frame, AVPacket *pkt)
530 const AVPixFmtDescriptor *desc;
532 if (!q->avctx_internal) {
533 q->avctx_internal = avcodec_alloc_context3(NULL);
534 if (!q->avctx_internal)
535 return AVERROR(ENOMEM);
537 q->avctx_internal->codec_id = avctx->codec_id;
539 q->parser = av_parser_init(avctx->codec_id);
541 return AVERROR(ENOMEM);
543 q->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
544 q->orig_pix_fmt = AV_PIX_FMT_NONE;
548 return qsv_decode(avctx, q, frame, got_frame, pkt);
550 /* we assume the packets are already split properly and want
551 * just the codec parameters here */
552 av_parser_parse2(q->parser, q->avctx_internal,
553 &dummy_data, &dummy_size,
554 pkt->data, pkt->size, pkt->pts, pkt->dts,
557 avctx->field_order = q->parser->field_order;
558 /* TODO: flush delayed frames on reinit */
559 if (q->parser->format != q->orig_pix_fmt ||
560 FFALIGN(q->parser->coded_width, 16) != FFALIGN(avctx->coded_width, 16) ||
561 FFALIGN(q->parser->coded_height, 16) != FFALIGN(avctx->coded_height, 16)) {
562 enum AVPixelFormat pix_fmts[3] = { AV_PIX_FMT_QSV,
565 enum AVPixelFormat qsv_format;
566 AVPacket zero_pkt = {0};
568 if (q->buffered_count) {
570 /* decode zero-size pkt to flush the buffered pkt before reinit */
572 return qsv_decode(avctx, q, frame, got_frame, &zero_pkt);
577 qsv_format = ff_qsv_map_pixfmt(q->parser->format, &q->fourcc);
578 if (qsv_format < 0) {
579 av_log(avctx, AV_LOG_ERROR,
580 "Decoding pixel format '%s' is not supported\n",
581 av_get_pix_fmt_name(q->parser->format));
582 ret = AVERROR(ENOSYS);
586 q->orig_pix_fmt = q->parser->format;
587 avctx->pix_fmt = pix_fmts[1] = qsv_format;
588 avctx->width = q->parser->width;
589 avctx->height = q->parser->height;
590 avctx->coded_width = FFALIGN(q->parser->coded_width, 16);
591 avctx->coded_height = FFALIGN(q->parser->coded_height, 16);
592 avctx->level = q->avctx_internal->level;
593 avctx->profile = q->avctx_internal->profile;
595 ret = ff_get_format(avctx, pix_fmts);
599 avctx->pix_fmt = ret;
601 desc = av_pix_fmt_desc_get(avctx->pix_fmt);
605 if (desc->comp[0].depth > 8) {
606 avctx->coded_width = FFALIGN(q->parser->coded_width, 32);
607 avctx->coded_height = FFALIGN(q->parser->coded_height, 32);
610 ret = qsv_decode_init(avctx, q);
615 return qsv_decode(avctx, q, frame, got_frame, pkt);
618 q->orig_pix_fmt = q->parser->format = avctx->pix_fmt = AV_PIX_FMT_NONE;
622 void ff_qsv_decode_flush(AVCodecContext *avctx, QSVContext *q)
624 q->orig_pix_fmt = AV_PIX_FMT_NONE;