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"
37 #include "libavutil/imgutils.h"
43 #include "qsv_internal.h"
46 const AVCodecHWConfigInternal *const ff_qsv_hw_configs[] = {
47 &(const AVCodecHWConfigInternal) {
49 .pix_fmt = AV_PIX_FMT_QSV,
50 .methods = AV_CODEC_HW_CONFIG_METHOD_HW_FRAMES_CTX |
51 AV_CODEC_HW_CONFIG_METHOD_AD_HOC,
52 .device_type = AV_HWDEVICE_TYPE_QSV,
59 static int ff_qsv_get_continuous_buffer(AVCodecContext *avctx, AVFrame *frame, AVBufferPool *pool)
63 ff_decode_frame_props(avctx, frame);
65 frame->width = avctx->width;
66 frame->height = avctx->height;
68 switch (avctx->pix_fmt) {
70 frame->linesize[0] = FFALIGN(avctx->width, 128);
73 frame->linesize[0] = 2 * FFALIGN(avctx->width, 128);
76 av_log(avctx, AV_LOG_ERROR, "Unsupported pixel format.\n");
77 return AVERROR(EINVAL);
80 frame->linesize[1] = frame->linesize[0];
81 frame->buf[0] = av_buffer_pool_get(pool);
83 return AVERROR(ENOMEM);
85 frame->data[0] = frame->buf[0]->data;
86 frame->data[1] = frame->data[0] +
87 frame->linesize[0] * FFALIGN(avctx->height, 64);
89 ret = ff_attach_decode_data(frame);
96 static int qsv_init_session(AVCodecContext *avctx, QSVContext *q, mfxSession session,
97 AVBufferRef *hw_frames_ref, AVBufferRef *hw_device_ref)
101 if (q->gpu_copy == MFX_GPUCOPY_ON &&
102 !(q->iopattern & MFX_IOPATTERN_OUT_SYSTEM_MEMORY)) {
103 av_log(avctx, AV_LOG_WARNING, "GPU-accelerated memory copy "
104 "only works in system memory mode.\n");
105 q->gpu_copy = MFX_GPUCOPY_OFF;
108 q->session = session;
109 } else if (hw_frames_ref) {
110 if (q->internal_qs.session) {
111 MFXClose(q->internal_qs.session);
112 q->internal_qs.session = NULL;
114 av_buffer_unref(&q->frames_ctx.hw_frames_ctx);
116 q->frames_ctx.hw_frames_ctx = av_buffer_ref(hw_frames_ref);
117 if (!q->frames_ctx.hw_frames_ctx)
118 return AVERROR(ENOMEM);
120 ret = ff_qsv_init_session_frames(avctx, &q->internal_qs.session,
121 &q->frames_ctx, q->load_plugins,
122 q->iopattern == MFX_IOPATTERN_OUT_OPAQUE_MEMORY,
125 av_buffer_unref(&q->frames_ctx.hw_frames_ctx);
129 q->session = q->internal_qs.session;
130 } else if (hw_device_ref) {
131 if (q->internal_qs.session) {
132 MFXClose(q->internal_qs.session);
133 q->internal_qs.session = NULL;
136 ret = ff_qsv_init_session_device(avctx, &q->internal_qs.session,
137 hw_device_ref, q->load_plugins, q->gpu_copy);
141 q->session = q->internal_qs.session;
143 if (!q->internal_qs.session) {
144 ret = ff_qsv_init_internal_session(avctx, &q->internal_qs,
145 q->load_plugins, q->gpu_copy);
150 q->session = q->internal_qs.session;
153 /* make sure the decoder is uninitialized */
154 MFXVideoDECODE_Close(q->session);
159 static inline unsigned int qsv_fifo_item_size(void)
161 return sizeof(mfxSyncPoint*) + sizeof(QSVFrame*);
164 static inline unsigned int qsv_fifo_size(const AVFifoBuffer* fifo)
166 return av_fifo_size(fifo) / qsv_fifo_item_size();
169 static int qsv_decode_preinit(AVCodecContext *avctx, QSVContext *q, enum AVPixelFormat pix_fmt, mfxVideoParam *param)
171 mfxSession session = NULL;
174 enum AVPixelFormat pix_fmts[3] = {
175 AV_PIX_FMT_QSV, /* opaque format in case of video memory output */
176 pix_fmt, /* system memory format obtained from bitstream parser */
179 ret = ff_get_format(avctx, pix_fmts);
181 q->orig_pix_fmt = avctx->pix_fmt = AV_PIX_FMT_NONE;
185 if (!q->async_fifo) {
186 q->async_fifo = av_fifo_alloc(q->async_depth * qsv_fifo_item_size());
188 return AVERROR(ENOMEM);
191 if (avctx->pix_fmt == AV_PIX_FMT_QSV && avctx->hwaccel_context) {
192 AVQSVContext *user_ctx = avctx->hwaccel_context;
193 session = user_ctx->session;
194 iopattern = user_ctx->iopattern;
195 q->ext_buffers = user_ctx->ext_buffers;
196 q->nb_ext_buffers = user_ctx->nb_ext_buffers;
199 if (avctx->hw_frames_ctx) {
200 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
201 AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
204 if (frames_hwctx->frame_type & MFX_MEMTYPE_OPAQUE_FRAME)
205 iopattern = MFX_IOPATTERN_OUT_OPAQUE_MEMORY;
206 else if (frames_hwctx->frame_type & MFX_MEMTYPE_VIDEO_MEMORY_DECODER_TARGET)
207 iopattern = MFX_IOPATTERN_OUT_VIDEO_MEMORY;
212 iopattern = MFX_IOPATTERN_OUT_SYSTEM_MEMORY;
213 q->iopattern = iopattern;
215 ff_qsv_print_iopattern(avctx, q->iopattern, "Decoder");
217 ret = qsv_init_session(avctx, q, session, avctx->hw_frames_ctx, avctx->hw_device_ctx);
219 av_log(avctx, AV_LOG_ERROR, "Error initializing an MFX session\n");
223 param->IOPattern = q->iopattern;
224 param->AsyncDepth = q->async_depth;
225 param->ExtParam = q->ext_buffers;
226 param->NumExtParam = q->nb_ext_buffers;
231 static int qsv_decode_init(AVCodecContext *avctx, QSVContext *q, mfxVideoParam *param)
235 avctx->width = param->mfx.FrameInfo.CropW;
236 avctx->height = param->mfx.FrameInfo.CropH;
237 avctx->coded_width = param->mfx.FrameInfo.Width;
238 avctx->coded_height = param->mfx.FrameInfo.Height;
239 avctx->level = param->mfx.CodecLevel;
240 avctx->profile = param->mfx.CodecProfile;
241 avctx->field_order = ff_qsv_map_picstruct(param->mfx.FrameInfo.PicStruct);
242 avctx->pix_fmt = ff_qsv_map_fourcc(param->mfx.FrameInfo.FourCC);
244 ret = MFXVideoDECODE_Init(q->session, param);
246 return ff_qsv_print_error(avctx, ret,
247 "Error initializing the MFX video decoder");
249 q->frame_info = param->mfx.FrameInfo;
251 if (!avctx->hw_frames_ctx)
252 q->pool = av_buffer_pool_init(av_image_get_buffer_size(avctx->pix_fmt,
253 FFALIGN(avctx->width, 128), FFALIGN(avctx->height, 64), 1), av_buffer_allocz);
257 static int qsv_decode_header(AVCodecContext *avctx, QSVContext *q, AVPacket *avpkt, enum AVPixelFormat pix_fmt, mfxVideoParam *param)
261 mfxBitstream bs = { 0 };
264 bs.Data = avpkt->data;
265 bs.DataLength = avpkt->size;
266 bs.MaxLength = bs.DataLength;
267 bs.TimeStamp = avpkt->pts;
268 if (avctx->field_order == AV_FIELD_PROGRESSIVE)
269 bs.DataFlag |= MFX_BITSTREAM_COMPLETE_FRAME;
271 return AVERROR_INVALIDDATA;
275 ret = qsv_decode_preinit(avctx, q, pix_fmt, param);
280 ret = ff_qsv_codec_id_to_mfx(avctx->codec_id);
284 param->mfx.CodecId = ret;
285 ret = MFXVideoDECODE_DecodeHeader(q->session, &bs, param);
286 if (MFX_ERR_MORE_DATA == ret) {
287 return AVERROR(EAGAIN);
290 return ff_qsv_print_error(avctx, ret,
291 "Error decoding stream header");
296 static int alloc_frame(AVCodecContext *avctx, QSVContext *q, QSVFrame *frame)
301 ret = ff_qsv_get_continuous_buffer(avctx, frame->frame, q->pool);
303 ret = ff_get_buffer(avctx, frame->frame, AV_GET_BUFFER_FLAG_REF);
308 if (frame->frame->format == AV_PIX_FMT_QSV) {
309 frame->surface = *(mfxFrameSurface1*)frame->frame->data[3];
311 frame->surface.Info = q->frame_info;
313 frame->surface.Data.PitchLow = frame->frame->linesize[0];
314 frame->surface.Data.Y = frame->frame->data[0];
315 frame->surface.Data.UV = frame->frame->data[1];
318 if (q->frames_ctx.mids) {
319 ret = ff_qsv_find_surface_idx(&q->frames_ctx, frame);
323 frame->surface.Data.MemId = &q->frames_ctx.mids[ret];
325 frame->surface.Data.ExtParam = &frame->ext_param;
326 frame->surface.Data.NumExtParam = 1;
327 frame->ext_param = (mfxExtBuffer*)&frame->dec_info;
328 frame->dec_info.Header.BufferId = MFX_EXTBUFF_DECODED_FRAME_INFO;
329 frame->dec_info.Header.BufferSz = sizeof(frame->dec_info);
336 static void qsv_clear_unused_frames(QSVContext *q)
338 QSVFrame *cur = q->work_frames;
340 if (cur->used && !cur->surface.Data.Locked && !cur->queued) {
342 av_frame_unref(cur->frame);
348 static int get_surface(AVCodecContext *avctx, QSVContext *q, mfxFrameSurface1 **surf)
350 QSVFrame *frame, **last;
353 qsv_clear_unused_frames(q);
355 frame = q->work_frames;
356 last = &q->work_frames;
359 ret = alloc_frame(avctx, q, frame);
362 *surf = &frame->surface;
370 frame = av_mallocz(sizeof(*frame));
372 return AVERROR(ENOMEM);
373 frame->frame = av_frame_alloc();
376 return AVERROR(ENOMEM);
380 ret = alloc_frame(avctx, q, frame);
384 *surf = &frame->surface;
389 static QSVFrame *find_frame(QSVContext *q, mfxFrameSurface1 *surf)
391 QSVFrame *cur = q->work_frames;
393 if (surf == &cur->surface)
400 static int qsv_decode(AVCodecContext *avctx, QSVContext *q,
401 AVFrame *frame, int *got_frame,
405 mfxFrameSurface1 *insurf;
406 mfxFrameSurface1 *outsurf;
408 mfxBitstream bs = { { { 0 } } };
412 bs.Data = avpkt->data;
413 bs.DataLength = avpkt->size;
414 bs.MaxLength = bs.DataLength;
415 bs.TimeStamp = avpkt->pts;
416 if (avctx->field_order == AV_FIELD_PROGRESSIVE)
417 bs.DataFlag |= MFX_BITSTREAM_COMPLETE_FRAME;
420 sync = av_mallocz(sizeof(*sync));
423 return AVERROR(ENOMEM);
427 ret = get_surface(avctx, q, &insurf);
433 ret = MFXVideoDECODE_DecodeFrameAsync(q->session, avpkt->size ? &bs : NULL,
434 insurf, &outsurf, sync);
435 if (ret == MFX_WRN_DEVICE_BUSY)
438 } while (ret == MFX_WRN_DEVICE_BUSY || ret == MFX_ERR_MORE_SURFACE);
440 if (ret != MFX_ERR_NONE &&
441 ret != MFX_ERR_MORE_DATA &&
442 ret != MFX_WRN_VIDEO_PARAM_CHANGED &&
443 ret != MFX_ERR_MORE_SURFACE) {
445 return ff_qsv_print_error(avctx, ret,
446 "Error during QSV decoding.");
449 /* make sure we do not enter an infinite loop if the SDK
450 * did not consume any data and did not return anything */
451 if (!*sync && !bs.DataOffset) {
452 bs.DataOffset = avpkt->size;
453 ++q->zero_consume_run;
454 if (q->zero_consume_run > 1)
455 ff_qsv_print_warning(avctx, ret, "A decode call did not consume any data");
456 } else if (!*sync && bs.DataOffset) {
459 q->zero_consume_run = 0;
463 QSVFrame *out_frame = find_frame(q, outsurf);
466 av_log(avctx, AV_LOG_ERROR,
467 "The returned surface does not correspond to any frame\n");
472 out_frame->queued = 1;
473 av_fifo_generic_write(q->async_fifo, &out_frame, sizeof(out_frame), NULL);
474 av_fifo_generic_write(q->async_fifo, &sync, sizeof(sync), NULL);
479 if ((qsv_fifo_size(q->async_fifo) >= q->async_depth) ||
480 (!avpkt->size && av_fifo_size(q->async_fifo))) {
483 av_fifo_generic_read(q->async_fifo, &out_frame, sizeof(out_frame), NULL);
484 av_fifo_generic_read(q->async_fifo, &sync, sizeof(sync), NULL);
485 out_frame->queued = 0;
487 if (avctx->pix_fmt != AV_PIX_FMT_QSV) {
489 ret = MFXVideoCORE_SyncOperation(q->session, *sync, 1000);
490 } while (ret == MFX_WRN_IN_EXECUTION);
495 src_frame = out_frame->frame;
497 ret = av_frame_ref(frame, src_frame);
501 outsurf = &out_frame->surface;
504 FF_DISABLE_DEPRECATION_WARNINGS
505 frame->pkt_pts = outsurf->Data.TimeStamp;
506 FF_ENABLE_DEPRECATION_WARNINGS
508 frame->pts = outsurf->Data.TimeStamp;
511 outsurf->Info.PicStruct & MFX_PICSTRUCT_FRAME_TRIPLING ? 4 :
512 outsurf->Info.PicStruct & MFX_PICSTRUCT_FRAME_DOUBLING ? 2 :
513 outsurf->Info.PicStruct & MFX_PICSTRUCT_FIELD_REPEATED ? 1 : 0;
514 frame->top_field_first =
515 outsurf->Info.PicStruct & MFX_PICSTRUCT_FIELD_TFF;
516 frame->interlaced_frame =
517 !(outsurf->Info.PicStruct & MFX_PICSTRUCT_PROGRESSIVE);
518 frame->pict_type = ff_qsv_map_pictype(out_frame->dec_info.FrameType);
519 //Key frame is IDR frame is only suitable for H264. For HEVC, IRAPs are key frames.
520 if (avctx->codec_id == AV_CODEC_ID_H264)
521 frame->key_frame = !!(out_frame->dec_info.FrameType & MFX_FRAMETYPE_IDR);
523 /* update the surface properties */
524 if (avctx->pix_fmt == AV_PIX_FMT_QSV)
525 ((mfxFrameSurface1*)frame->data[3])->Info = outsurf->Info;
530 return bs.DataOffset;
533 int ff_qsv_decode_close(QSVContext *q)
535 QSVFrame *cur = q->work_frames;
538 MFXVideoDECODE_Close(q->session);
540 while (q->async_fifo && av_fifo_size(q->async_fifo)) {
544 av_fifo_generic_read(q->async_fifo, &out_frame, sizeof(out_frame), NULL);
545 av_fifo_generic_read(q->async_fifo, &sync, sizeof(sync), NULL);
551 q->work_frames = cur->next;
552 av_frame_free(&cur->frame);
554 cur = q->work_frames;
557 av_fifo_free(q->async_fifo);
558 q->async_fifo = NULL;
560 ff_qsv_close_internal_session(&q->internal_qs);
562 av_buffer_unref(&q->frames_ctx.hw_frames_ctx);
563 av_buffer_unref(&q->frames_ctx.mids_buf);
564 av_buffer_pool_uninit(&q->pool);
569 int ff_qsv_process_data(AVCodecContext *avctx, QSVContext *q,
570 AVFrame *frame, int *got_frame, AVPacket *pkt)
573 mfxVideoParam param = { 0 };
574 enum AVPixelFormat pix_fmt = AV_PIX_FMT_NV12;
577 return qsv_decode(avctx, q, frame, got_frame, pkt);
579 /* TODO: flush delayed frames on reinit */
581 // sw_pix_fmt, coded_width/height should be set for ff_get_format(),
582 // assume sw_pix_fmt is NV12 and coded_width/height to be 1280x720,
583 // the assumption may be not corret but will be updated after header decoded if not true.
584 if (q->orig_pix_fmt != AV_PIX_FMT_NONE)
585 pix_fmt = q->orig_pix_fmt;
586 if (!avctx->coded_width)
587 avctx->coded_width = 1280;
588 if (!avctx->coded_height)
589 avctx->coded_height = 720;
591 ret = qsv_decode_header(avctx, q, pkt, pix_fmt, ¶m);
593 if (ret >= 0 && (q->orig_pix_fmt != ff_qsv_map_fourcc(param.mfx.FrameInfo.FourCC) ||
594 avctx->coded_width != param.mfx.FrameInfo.Width ||
595 avctx->coded_height != param.mfx.FrameInfo.Height)) {
596 AVPacket zero_pkt = {0};
598 if (q->buffered_count) {
600 /* decode zero-size pkt to flush the buffered pkt before reinit */
602 return qsv_decode(avctx, q, frame, got_frame, &zero_pkt);
606 q->orig_pix_fmt = avctx->pix_fmt = pix_fmt = ff_qsv_map_fourcc(param.mfx.FrameInfo.FourCC);
608 avctx->coded_width = param.mfx.FrameInfo.Width;
609 avctx->coded_height = param.mfx.FrameInfo.Height;
611 ret = qsv_decode_preinit(avctx, q, pix_fmt, ¶m);
617 if (!q->initialized) {
618 ret = qsv_decode_init(avctx, q, ¶m);
624 return qsv_decode(avctx, q, frame, got_frame, pkt);
627 q->orig_pix_fmt = avctx->pix_fmt = AV_PIX_FMT_NONE;
631 void ff_qsv_decode_flush(AVCodecContext *avctx, QSVContext *q)
633 q->orig_pix_fmt = AV_PIX_FMT_NONE;