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_preinit(AVCodecContext *avctx, QSVContext *q, enum AVPixelFormat pix_fmt, mfxVideoParam *param)
152 mfxSession session = NULL;
155 enum AVPixelFormat pix_fmts[3] = {
156 AV_PIX_FMT_QSV, /* opaque format in case of video memory output */
157 pix_fmt, /* system memory format obtained from bitstream parser */
160 ret = ff_get_format(avctx, pix_fmts);
162 q->orig_pix_fmt = avctx->pix_fmt = AV_PIX_FMT_NONE;
166 if (!q->async_fifo) {
167 q->async_fifo = av_fifo_alloc(q->async_depth * qsv_fifo_item_size());
169 return AVERROR(ENOMEM);
172 if (avctx->pix_fmt == AV_PIX_FMT_QSV && avctx->hwaccel_context) {
173 AVQSVContext *user_ctx = avctx->hwaccel_context;
174 session = user_ctx->session;
175 iopattern = user_ctx->iopattern;
176 q->ext_buffers = user_ctx->ext_buffers;
177 q->nb_ext_buffers = user_ctx->nb_ext_buffers;
180 if (avctx->hw_frames_ctx) {
181 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
182 AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
185 if (frames_hwctx->frame_type & MFX_MEMTYPE_OPAQUE_FRAME)
186 iopattern = MFX_IOPATTERN_OUT_OPAQUE_MEMORY;
187 else if (frames_hwctx->frame_type & MFX_MEMTYPE_VIDEO_MEMORY_DECODER_TARGET)
188 iopattern = MFX_IOPATTERN_OUT_VIDEO_MEMORY;
193 iopattern = MFX_IOPATTERN_OUT_SYSTEM_MEMORY;
194 q->iopattern = iopattern;
196 ret = qsv_init_session(avctx, q, session, avctx->hw_frames_ctx, avctx->hw_device_ctx);
198 av_log(avctx, AV_LOG_ERROR, "Error initializing an MFX session\n");
202 param->IOPattern = q->iopattern;
203 param->AsyncDepth = q->async_depth;
204 param->ExtParam = q->ext_buffers;
205 param->NumExtParam = q->nb_ext_buffers;
210 static int qsv_decode_init(AVCodecContext *avctx, QSVContext *q, mfxVideoParam *param)
214 avctx->width = param->mfx.FrameInfo.CropW;
215 avctx->height = param->mfx.FrameInfo.CropH;
216 avctx->coded_width = param->mfx.FrameInfo.Width;
217 avctx->coded_height = param->mfx.FrameInfo.Height;
218 avctx->level = param->mfx.CodecLevel;
219 avctx->profile = param->mfx.CodecProfile;
220 avctx->field_order = ff_qsv_map_picstruct(param->mfx.FrameInfo.PicStruct);
221 avctx->pix_fmt = ff_qsv_map_fourcc(param->mfx.FrameInfo.FourCC);
223 ret = MFXVideoDECODE_Init(q->session, param);
225 return ff_qsv_print_error(avctx, ret,
226 "Error initializing the MFX video decoder");
228 q->frame_info = param->mfx.FrameInfo;
233 static int qsv_decode_header(AVCodecContext *avctx, QSVContext *q, AVPacket *avpkt, enum AVPixelFormat pix_fmt, mfxVideoParam *param)
237 mfxBitstream bs = { 0 };
240 bs.Data = avpkt->data;
241 bs.DataLength = avpkt->size;
242 bs.MaxLength = bs.DataLength;
243 bs.TimeStamp = avpkt->pts;
244 if (avctx->field_order == AV_FIELD_PROGRESSIVE)
245 bs.DataFlag |= MFX_BITSTREAM_COMPLETE_FRAME;
247 return AVERROR_INVALIDDATA;
251 ret = qsv_decode_preinit(avctx, q, pix_fmt, param);
256 ret = ff_qsv_codec_id_to_mfx(avctx->codec_id);
260 param->mfx.CodecId = ret;
261 ret = MFXVideoDECODE_DecodeHeader(q->session, &bs, param);
262 if (MFX_ERR_MORE_DATA == ret) {
263 return AVERROR(EAGAIN);
266 return ff_qsv_print_error(avctx, ret,
267 "Error decoding stream header");
272 static int alloc_frame(AVCodecContext *avctx, QSVContext *q, QSVFrame *frame)
276 ret = ff_get_buffer(avctx, frame->frame, AV_GET_BUFFER_FLAG_REF);
280 if (frame->frame->format == AV_PIX_FMT_QSV) {
281 frame->surface = *(mfxFrameSurface1*)frame->frame->data[3];
283 frame->surface.Info = q->frame_info;
285 frame->surface.Data.PitchLow = frame->frame->linesize[0];
286 frame->surface.Data.Y = frame->frame->data[0];
287 frame->surface.Data.UV = frame->frame->data[1];
290 if (q->frames_ctx.mids) {
291 ret = ff_qsv_find_surface_idx(&q->frames_ctx, frame);
295 frame->surface.Data.MemId = &q->frames_ctx.mids[ret];
297 frame->surface.Data.ExtParam = &frame->ext_param;
298 frame->surface.Data.NumExtParam = 1;
299 frame->ext_param = (mfxExtBuffer*)&frame->dec_info;
300 frame->dec_info.Header.BufferId = MFX_EXTBUFF_DECODED_FRAME_INFO;
301 frame->dec_info.Header.BufferSz = sizeof(frame->dec_info);
308 static void qsv_clear_unused_frames(QSVContext *q)
310 QSVFrame *cur = q->work_frames;
312 if (cur->used && !cur->surface.Data.Locked && !cur->queued) {
314 av_frame_unref(cur->frame);
320 static int get_surface(AVCodecContext *avctx, QSVContext *q, mfxFrameSurface1 **surf)
322 QSVFrame *frame, **last;
325 qsv_clear_unused_frames(q);
327 frame = q->work_frames;
328 last = &q->work_frames;
331 ret = alloc_frame(avctx, q, frame);
334 *surf = &frame->surface;
342 frame = av_mallocz(sizeof(*frame));
344 return AVERROR(ENOMEM);
345 frame->frame = av_frame_alloc();
348 return AVERROR(ENOMEM);
352 ret = alloc_frame(avctx, q, frame);
356 *surf = &frame->surface;
361 static QSVFrame *find_frame(QSVContext *q, mfxFrameSurface1 *surf)
363 QSVFrame *cur = q->work_frames;
365 if (surf == &cur->surface)
372 static int qsv_decode(AVCodecContext *avctx, QSVContext *q,
373 AVFrame *frame, int *got_frame,
377 mfxFrameSurface1 *insurf;
378 mfxFrameSurface1 *outsurf;
380 mfxBitstream bs = { { { 0 } } };
384 bs.Data = avpkt->data;
385 bs.DataLength = avpkt->size;
386 bs.MaxLength = bs.DataLength;
387 bs.TimeStamp = avpkt->pts;
388 if (avctx->field_order == AV_FIELD_PROGRESSIVE)
389 bs.DataFlag |= MFX_BITSTREAM_COMPLETE_FRAME;
392 sync = av_mallocz(sizeof(*sync));
395 return AVERROR(ENOMEM);
399 ret = get_surface(avctx, q, &insurf);
405 ret = MFXVideoDECODE_DecodeFrameAsync(q->session, avpkt->size ? &bs : NULL,
406 insurf, &outsurf, sync);
407 if (ret == MFX_WRN_DEVICE_BUSY)
410 } while (ret == MFX_WRN_DEVICE_BUSY || ret == MFX_ERR_MORE_SURFACE);
412 if (ret != MFX_ERR_NONE &&
413 ret != MFX_ERR_MORE_DATA &&
414 ret != MFX_WRN_VIDEO_PARAM_CHANGED &&
415 ret != MFX_ERR_MORE_SURFACE) {
417 return ff_qsv_print_error(avctx, ret,
418 "Error during QSV decoding.");
421 /* make sure we do not enter an infinite loop if the SDK
422 * did not consume any data and did not return anything */
423 if (!*sync && !bs.DataOffset) {
424 bs.DataOffset = avpkt->size;
425 ++q->zero_consume_run;
426 if (q->zero_consume_run > 1)
427 ff_qsv_print_warning(avctx, ret, "A decode call did not consume any data");
428 } else if (!*sync && bs.DataOffset) {
431 q->zero_consume_run = 0;
435 QSVFrame *out_frame = find_frame(q, outsurf);
438 av_log(avctx, AV_LOG_ERROR,
439 "The returned surface does not correspond to any frame\n");
444 out_frame->queued = 1;
445 av_fifo_generic_write(q->async_fifo, &out_frame, sizeof(out_frame), NULL);
446 av_fifo_generic_write(q->async_fifo, &sync, sizeof(sync), NULL);
451 if ((qsv_fifo_size(q->async_fifo) >= q->async_depth) ||
452 (!avpkt->size && av_fifo_size(q->async_fifo))) {
455 av_fifo_generic_read(q->async_fifo, &out_frame, sizeof(out_frame), NULL);
456 av_fifo_generic_read(q->async_fifo, &sync, sizeof(sync), NULL);
457 out_frame->queued = 0;
459 if (avctx->pix_fmt != AV_PIX_FMT_QSV) {
461 ret = MFXVideoCORE_SyncOperation(q->session, *sync, 1000);
462 } while (ret == MFX_WRN_IN_EXECUTION);
467 src_frame = out_frame->frame;
469 ret = av_frame_ref(frame, src_frame);
473 outsurf = &out_frame->surface;
476 FF_DISABLE_DEPRECATION_WARNINGS
477 frame->pkt_pts = outsurf->Data.TimeStamp;
478 FF_ENABLE_DEPRECATION_WARNINGS
480 frame->pts = outsurf->Data.TimeStamp;
483 outsurf->Info.PicStruct & MFX_PICSTRUCT_FRAME_TRIPLING ? 4 :
484 outsurf->Info.PicStruct & MFX_PICSTRUCT_FRAME_DOUBLING ? 2 :
485 outsurf->Info.PicStruct & MFX_PICSTRUCT_FIELD_REPEATED ? 1 : 0;
486 frame->top_field_first =
487 outsurf->Info.PicStruct & MFX_PICSTRUCT_FIELD_TFF;
488 frame->interlaced_frame =
489 !(outsurf->Info.PicStruct & MFX_PICSTRUCT_PROGRESSIVE);
490 frame->pict_type = ff_qsv_map_pictype(out_frame->dec_info.FrameType);
491 //Key frame is IDR frame is only suitable for H264. For HEVC, IRAPs are key frames.
492 if (avctx->codec_id == AV_CODEC_ID_H264)
493 frame->key_frame = !!(out_frame->dec_info.FrameType & MFX_FRAMETYPE_IDR);
495 /* update the surface properties */
496 if (avctx->pix_fmt == AV_PIX_FMT_QSV)
497 ((mfxFrameSurface1*)frame->data[3])->Info = outsurf->Info;
502 return bs.DataOffset;
505 int ff_qsv_decode_close(QSVContext *q)
507 QSVFrame *cur = q->work_frames;
510 MFXVideoDECODE_Close(q->session);
512 while (q->async_fifo && av_fifo_size(q->async_fifo)) {
516 av_fifo_generic_read(q->async_fifo, &out_frame, sizeof(out_frame), NULL);
517 av_fifo_generic_read(q->async_fifo, &sync, sizeof(sync), NULL);
523 q->work_frames = cur->next;
524 av_frame_free(&cur->frame);
526 cur = q->work_frames;
529 av_fifo_free(q->async_fifo);
530 q->async_fifo = NULL;
532 if (q->internal_session)
533 MFXClose(q->internal_session);
535 av_buffer_unref(&q->frames_ctx.hw_frames_ctx);
536 av_buffer_unref(&q->frames_ctx.mids_buf);
541 int ff_qsv_process_data(AVCodecContext *avctx, QSVContext *q,
542 AVFrame *frame, int *got_frame, AVPacket *pkt)
545 mfxVideoParam param = { 0 };
546 enum AVPixelFormat pix_fmt = AV_PIX_FMT_NV12;
549 return qsv_decode(avctx, q, frame, got_frame, pkt);
551 /* TODO: flush delayed frames on reinit */
553 // sw_pix_fmt, coded_width/height should be set for ff_get_format(),
554 // assume sw_pix_fmt is NV12 and coded_width/height to be 1280x720,
555 // the assumption may be not corret but will be updated after header decoded if not true.
556 if (q->orig_pix_fmt != AV_PIX_FMT_NONE)
557 pix_fmt = q->orig_pix_fmt;
558 if (!avctx->coded_width)
559 avctx->coded_width = 1280;
560 if (!avctx->coded_height)
561 avctx->coded_height = 720;
563 ret = qsv_decode_header(avctx, q, pkt, pix_fmt, ¶m);
565 if (ret >= 0 && (q->orig_pix_fmt != ff_qsv_map_fourcc(param.mfx.FrameInfo.FourCC) ||
566 avctx->coded_width != param.mfx.FrameInfo.Width ||
567 avctx->coded_height != param.mfx.FrameInfo.Height)) {
568 AVPacket zero_pkt = {0};
570 if (q->buffered_count) {
572 /* decode zero-size pkt to flush the buffered pkt before reinit */
574 return qsv_decode(avctx, q, frame, got_frame, &zero_pkt);
578 q->orig_pix_fmt = avctx->pix_fmt = pix_fmt = ff_qsv_map_fourcc(param.mfx.FrameInfo.FourCC);
580 avctx->coded_width = param.mfx.FrameInfo.Width;
581 avctx->coded_height = param.mfx.FrameInfo.Height;
583 ret = qsv_decode_preinit(avctx, q, pix_fmt, ¶m);
589 if (!q->initialized) {
590 ret = qsv_decode_init(avctx, q, ¶m);
596 return qsv_decode(avctx, q, frame, got_frame, pkt);
599 q->orig_pix_fmt = avctx->pix_fmt = AV_PIX_FMT_NONE;
603 void ff_qsv_decode_flush(AVCodecContext *avctx, QSVContext *q)
605 q->orig_pix_fmt = AV_PIX_FMT_NONE;