]> git.sesse.net Git - ffmpeg/blob - libavcodec/qsvdec.c
lavc/qsv: add memory type message
[ffmpeg] / libavcodec / qsvdec.c
1 /*
2  * Intel MediaSDK QSV codec-independent code
3  *
4  * copyright (c) 2013 Luca Barbato
5  * copyright (c) 2015 Anton Khirnov <anton@khirnov.net>
6  *
7  * This file is part of FFmpeg.
8  *
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.
13  *
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.
18  *
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
22  */
23
24 #include <string.h>
25 #include <sys/types.h>
26
27 #include <mfx/mfxvideo.h>
28
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
38 #include "avcodec.h"
39 #include "internal.h"
40 #include "qsv.h"
41 #include "qsv_internal.h"
42 #include "qsvdec.h"
43
44 const AVCodecHWConfigInternal *ff_qsv_hw_configs[] = {
45     &(const AVCodecHWConfigInternal) {
46         .public = {
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,
51         },
52         .hwaccel = NULL,
53     },
54     NULL
55 };
56
57 static int qsv_init_session(AVCodecContext *avctx, QSVContext *q, mfxSession session,
58                             AVBufferRef *hw_frames_ref, AVBufferRef *hw_device_ref)
59 {
60     int ret;
61
62     if (session) {
63         q->session = session;
64     } else if (hw_frames_ref) {
65         if (q->internal_qs.session) {
66             MFXClose(q->internal_qs.session);
67             q->internal_qs.session = NULL;
68         }
69         av_buffer_unref(&q->frames_ctx.hw_frames_ctx);
70
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);
74
75         ret = ff_qsv_init_session_frames(avctx, &q->internal_qs.session,
76                                          &q->frames_ctx, q->load_plugins,
77                                          q->iopattern == MFX_IOPATTERN_OUT_OPAQUE_MEMORY);
78         if (ret < 0) {
79             av_buffer_unref(&q->frames_ctx.hw_frames_ctx);
80             return ret;
81         }
82
83         q->session = q->internal_qs.session;
84     } else if (hw_device_ref) {
85         if (q->internal_qs.session) {
86             MFXClose(q->internal_qs.session);
87             q->internal_qs.session = NULL;
88         }
89
90         ret = ff_qsv_init_session_device(avctx, &q->internal_qs.session,
91                                          hw_device_ref, q->load_plugins);
92         if (ret < 0)
93             return ret;
94
95         q->session = q->internal_qs.session;
96     } else {
97         if (!q->internal_qs.session) {
98             ret = ff_qsv_init_internal_session(avctx, &q->internal_qs,
99                                                q->load_plugins);
100             if (ret < 0)
101                 return ret;
102         }
103
104         q->session = q->internal_qs.session;
105     }
106
107     /* make sure the decoder is uninitialized */
108     MFXVideoDECODE_Close(q->session);
109
110     return 0;
111 }
112
113 static inline unsigned int qsv_fifo_item_size(void)
114 {
115     return sizeof(mfxSyncPoint*) + sizeof(QSVFrame*);
116 }
117
118 static inline unsigned int qsv_fifo_size(const AVFifoBuffer* fifo)
119 {
120     return av_fifo_size(fifo) / qsv_fifo_item_size();
121 }
122
123 static int check_dec_param(AVCodecContext *avctx, QSVContext *q, mfxVideoParam *param_in)
124 {
125     mfxVideoParam param_out = { .mfx.CodecId = param_in->mfx.CodecId };
126     mfxStatus ret;
127
128 #define CHECK_MATCH(x) \
129     do { \
130       if (param_out.mfx.x != param_in->mfx.x) {   \
131           av_log(avctx, AV_LOG_WARNING, "Required "#x" %d is unsupported\n", \
132           param_in->mfx.x); \
133       } \
134     } while (0)
135
136     ret = MFXVideoDECODE_Query(q->session, param_in, &param_out);
137
138     if (ret < 0) {
139         CHECK_MATCH(CodecId);
140         CHECK_MATCH(CodecProfile);
141         CHECK_MATCH(CodecLevel);
142         CHECK_MATCH(FrameInfo.Width);
143         CHECK_MATCH(FrameInfo.Height);
144 #undef CHECK_MATCH
145         return 0;
146     }
147     return 1;
148 }
149
150 static int qsv_decode_preinit(AVCodecContext *avctx, QSVContext *q, enum AVPixelFormat pix_fmt, mfxVideoParam *param)
151 {
152     mfxSession session = NULL;
153     int iopattern = 0;
154     int ret;
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 */
158         AV_PIX_FMT_NONE };
159
160     ret = ff_get_format(avctx, pix_fmts);
161     if (ret < 0) {
162         q->orig_pix_fmt = avctx->pix_fmt = AV_PIX_FMT_NONE;
163         return ret;
164     }
165
166     if (!q->async_fifo) {
167         q->async_fifo = av_fifo_alloc(q->async_depth * qsv_fifo_item_size());
168         if (!q->async_fifo)
169             return AVERROR(ENOMEM);
170     }
171
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;
178     }
179
180     if (avctx->hw_frames_ctx) {
181         AVHWFramesContext    *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
182         AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
183
184         if (!iopattern) {
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;
189         }
190     }
191
192     if (!iopattern)
193         iopattern = MFX_IOPATTERN_OUT_SYSTEM_MEMORY;
194     q->iopattern = iopattern;
195
196     ff_qsv_print_iopattern(avctx, q->iopattern, "Decoder");
197
198     ret = qsv_init_session(avctx, q, session, avctx->hw_frames_ctx, avctx->hw_device_ctx);
199     if (ret < 0) {
200         av_log(avctx, AV_LOG_ERROR, "Error initializing an MFX session\n");
201         return ret;
202     }
203
204     param->IOPattern   = q->iopattern;
205     param->AsyncDepth  = q->async_depth;
206     param->ExtParam    = q->ext_buffers;
207     param->NumExtParam = q->nb_ext_buffers;
208
209     return 0;
210  }
211
212 static int qsv_decode_init(AVCodecContext *avctx, QSVContext *q, mfxVideoParam *param)
213 {
214     int ret;
215
216     avctx->width        = param->mfx.FrameInfo.CropW;
217     avctx->height       = param->mfx.FrameInfo.CropH;
218     avctx->coded_width  = param->mfx.FrameInfo.Width;
219     avctx->coded_height = param->mfx.FrameInfo.Height;
220     avctx->level        = param->mfx.CodecLevel;
221     avctx->profile      = param->mfx.CodecProfile;
222     avctx->field_order  = ff_qsv_map_picstruct(param->mfx.FrameInfo.PicStruct);
223     avctx->pix_fmt      = ff_qsv_map_fourcc(param->mfx.FrameInfo.FourCC);
224
225     ret = MFXVideoDECODE_Init(q->session, param);
226     if (ret < 0)
227         return ff_qsv_print_error(avctx, ret,
228                                   "Error initializing the MFX video decoder");
229
230     q->frame_info = param->mfx.FrameInfo;
231
232     return 0;
233 }
234
235 static int qsv_decode_header(AVCodecContext *avctx, QSVContext *q, AVPacket *avpkt, enum AVPixelFormat pix_fmt, mfxVideoParam *param)
236 {
237     int ret;
238
239     mfxBitstream bs = { 0 };
240
241     if (avpkt->size) {
242         bs.Data       = avpkt->data;
243         bs.DataLength = avpkt->size;
244         bs.MaxLength  = bs.DataLength;
245         bs.TimeStamp  = avpkt->pts;
246         if (avctx->field_order == AV_FIELD_PROGRESSIVE)
247             bs.DataFlag   |= MFX_BITSTREAM_COMPLETE_FRAME;
248     } else
249         return AVERROR_INVALIDDATA;
250
251
252     if(!q->session) {
253         ret = qsv_decode_preinit(avctx, q, pix_fmt, param);
254         if (ret < 0)
255             return ret;
256     }
257
258     ret = ff_qsv_codec_id_to_mfx(avctx->codec_id);
259     if (ret < 0)
260         return ret;
261
262     param->mfx.CodecId = ret;
263     ret = MFXVideoDECODE_DecodeHeader(q->session, &bs, param);
264     if (MFX_ERR_MORE_DATA == ret) {
265        return AVERROR(EAGAIN);
266     }
267     if (ret < 0)
268         return ff_qsv_print_error(avctx, ret,
269                 "Error decoding stream header");
270
271     return 0;
272 }
273
274 static int alloc_frame(AVCodecContext *avctx, QSVContext *q, QSVFrame *frame)
275 {
276     int ret;
277
278     ret = ff_get_buffer(avctx, frame->frame, AV_GET_BUFFER_FLAG_REF);
279     if (ret < 0)
280         return ret;
281
282     if (frame->frame->format == AV_PIX_FMT_QSV) {
283         frame->surface = *(mfxFrameSurface1*)frame->frame->data[3];
284     } else {
285         frame->surface.Info = q->frame_info;
286
287         frame->surface.Data.PitchLow = frame->frame->linesize[0];
288         frame->surface.Data.Y        = frame->frame->data[0];
289         frame->surface.Data.UV       = frame->frame->data[1];
290     }
291
292     if (q->frames_ctx.mids) {
293         ret = ff_qsv_find_surface_idx(&q->frames_ctx, frame);
294         if (ret < 0)
295             return ret;
296
297         frame->surface.Data.MemId = &q->frames_ctx.mids[ret];
298     }
299     frame->surface.Data.ExtParam    = &frame->ext_param;
300     frame->surface.Data.NumExtParam = 1;
301     frame->ext_param                = (mfxExtBuffer*)&frame->dec_info;
302     frame->dec_info.Header.BufferId = MFX_EXTBUFF_DECODED_FRAME_INFO;
303     frame->dec_info.Header.BufferSz = sizeof(frame->dec_info);
304
305     frame->used = 1;
306
307     return 0;
308 }
309
310 static void qsv_clear_unused_frames(QSVContext *q)
311 {
312     QSVFrame *cur = q->work_frames;
313     while (cur) {
314         if (cur->used && !cur->surface.Data.Locked && !cur->queued) {
315             cur->used = 0;
316             av_frame_unref(cur->frame);
317         }
318         cur = cur->next;
319     }
320 }
321
322 static int get_surface(AVCodecContext *avctx, QSVContext *q, mfxFrameSurface1 **surf)
323 {
324     QSVFrame *frame, **last;
325     int ret;
326
327     qsv_clear_unused_frames(q);
328
329     frame = q->work_frames;
330     last  = &q->work_frames;
331     while (frame) {
332         if (!frame->used) {
333             ret = alloc_frame(avctx, q, frame);
334             if (ret < 0)
335                 return ret;
336             *surf = &frame->surface;
337             return 0;
338         }
339
340         last  = &frame->next;
341         frame = frame->next;
342     }
343
344     frame = av_mallocz(sizeof(*frame));
345     if (!frame)
346         return AVERROR(ENOMEM);
347     frame->frame = av_frame_alloc();
348     if (!frame->frame) {
349         av_freep(&frame);
350         return AVERROR(ENOMEM);
351     }
352     *last = frame;
353
354     ret = alloc_frame(avctx, q, frame);
355     if (ret < 0)
356         return ret;
357
358     *surf = &frame->surface;
359
360     return 0;
361 }
362
363 static QSVFrame *find_frame(QSVContext *q, mfxFrameSurface1 *surf)
364 {
365     QSVFrame *cur = q->work_frames;
366     while (cur) {
367         if (surf == &cur->surface)
368             return cur;
369         cur = cur->next;
370     }
371     return NULL;
372 }
373
374 static int qsv_decode(AVCodecContext *avctx, QSVContext *q,
375                       AVFrame *frame, int *got_frame,
376                       AVPacket *avpkt)
377 {
378     QSVFrame *out_frame;
379     mfxFrameSurface1 *insurf;
380     mfxFrameSurface1 *outsurf;
381     mfxSyncPoint *sync;
382     mfxBitstream bs = { { { 0 } } };
383     int ret;
384
385     if (avpkt->size) {
386         bs.Data       = avpkt->data;
387         bs.DataLength = avpkt->size;
388         bs.MaxLength  = bs.DataLength;
389         bs.TimeStamp  = avpkt->pts;
390         if (avctx->field_order == AV_FIELD_PROGRESSIVE)
391             bs.DataFlag   |= MFX_BITSTREAM_COMPLETE_FRAME;
392     }
393
394     sync = av_mallocz(sizeof(*sync));
395     if (!sync) {
396         av_freep(&sync);
397         return AVERROR(ENOMEM);
398     }
399
400     do {
401         ret = get_surface(avctx, q, &insurf);
402         if (ret < 0) {
403             av_freep(&sync);
404             return ret;
405         }
406
407         ret = MFXVideoDECODE_DecodeFrameAsync(q->session, avpkt->size ? &bs : NULL,
408                                               insurf, &outsurf, sync);
409         if (ret == MFX_WRN_DEVICE_BUSY)
410             av_usleep(500);
411
412     } while (ret == MFX_WRN_DEVICE_BUSY || ret == MFX_ERR_MORE_SURFACE);
413
414     if (ret != MFX_ERR_NONE &&
415         ret != MFX_ERR_MORE_DATA &&
416         ret != MFX_WRN_VIDEO_PARAM_CHANGED &&
417         ret != MFX_ERR_MORE_SURFACE) {
418         av_freep(&sync);
419         return ff_qsv_print_error(avctx, ret,
420                                   "Error during QSV decoding.");
421     }
422
423     /* make sure we do not enter an infinite loop if the SDK
424      * did not consume any data and did not return anything */
425     if (!*sync && !bs.DataOffset) {
426         bs.DataOffset = avpkt->size;
427         ++q->zero_consume_run;
428         if (q->zero_consume_run > 1)
429             ff_qsv_print_warning(avctx, ret, "A decode call did not consume any data");
430     } else if (!*sync && bs.DataOffset) {
431         ++q->buffered_count;
432     } else {
433         q->zero_consume_run = 0;
434     }
435
436     if (*sync) {
437         QSVFrame *out_frame = find_frame(q, outsurf);
438
439         if (!out_frame) {
440             av_log(avctx, AV_LOG_ERROR,
441                    "The returned surface does not correspond to any frame\n");
442             av_freep(&sync);
443             return AVERROR_BUG;
444         }
445
446         out_frame->queued = 1;
447         av_fifo_generic_write(q->async_fifo, &out_frame, sizeof(out_frame), NULL);
448         av_fifo_generic_write(q->async_fifo, &sync,      sizeof(sync),      NULL);
449     } else {
450         av_freep(&sync);
451     }
452
453     if ((qsv_fifo_size(q->async_fifo) >= q->async_depth) ||
454         (!avpkt->size && av_fifo_size(q->async_fifo))) {
455         AVFrame *src_frame;
456
457         av_fifo_generic_read(q->async_fifo, &out_frame, sizeof(out_frame), NULL);
458         av_fifo_generic_read(q->async_fifo, &sync,      sizeof(sync),      NULL);
459         out_frame->queued = 0;
460
461         if (avctx->pix_fmt != AV_PIX_FMT_QSV) {
462             do {
463                 ret = MFXVideoCORE_SyncOperation(q->session, *sync, 1000);
464             } while (ret == MFX_WRN_IN_EXECUTION);
465         }
466
467         av_freep(&sync);
468
469         src_frame = out_frame->frame;
470
471         ret = av_frame_ref(frame, src_frame);
472         if (ret < 0)
473             return ret;
474
475         outsurf = &out_frame->surface;
476
477 #if FF_API_PKT_PTS
478 FF_DISABLE_DEPRECATION_WARNINGS
479         frame->pkt_pts = outsurf->Data.TimeStamp;
480 FF_ENABLE_DEPRECATION_WARNINGS
481 #endif
482         frame->pts = outsurf->Data.TimeStamp;
483
484         frame->repeat_pict =
485             outsurf->Info.PicStruct & MFX_PICSTRUCT_FRAME_TRIPLING ? 4 :
486             outsurf->Info.PicStruct & MFX_PICSTRUCT_FRAME_DOUBLING ? 2 :
487             outsurf->Info.PicStruct & MFX_PICSTRUCT_FIELD_REPEATED ? 1 : 0;
488         frame->top_field_first =
489             outsurf->Info.PicStruct & MFX_PICSTRUCT_FIELD_TFF;
490         frame->interlaced_frame =
491             !(outsurf->Info.PicStruct & MFX_PICSTRUCT_PROGRESSIVE);
492         frame->pict_type = ff_qsv_map_pictype(out_frame->dec_info.FrameType);
493         //Key frame is IDR frame is only suitable for H264. For HEVC, IRAPs are key frames.
494         if (avctx->codec_id == AV_CODEC_ID_H264)
495             frame->key_frame = !!(out_frame->dec_info.FrameType & MFX_FRAMETYPE_IDR);
496
497         /* update the surface properties */
498         if (avctx->pix_fmt == AV_PIX_FMT_QSV)
499             ((mfxFrameSurface1*)frame->data[3])->Info = outsurf->Info;
500
501         *got_frame = 1;
502     }
503
504     return bs.DataOffset;
505 }
506
507 int ff_qsv_decode_close(QSVContext *q)
508 {
509     QSVFrame *cur = q->work_frames;
510
511     if (q->session)
512         MFXVideoDECODE_Close(q->session);
513
514     while (q->async_fifo && av_fifo_size(q->async_fifo)) {
515         QSVFrame *out_frame;
516         mfxSyncPoint *sync;
517
518         av_fifo_generic_read(q->async_fifo, &out_frame, sizeof(out_frame), NULL);
519         av_fifo_generic_read(q->async_fifo, &sync,      sizeof(sync),      NULL);
520
521         av_freep(&sync);
522     }
523
524     while (cur) {
525         q->work_frames = cur->next;
526         av_frame_free(&cur->frame);
527         av_freep(&cur);
528         cur = q->work_frames;
529     }
530
531     av_fifo_free(q->async_fifo);
532     q->async_fifo = NULL;
533
534     ff_qsv_close_internal_session(&q->internal_qs);
535
536     av_buffer_unref(&q->frames_ctx.hw_frames_ctx);
537     av_buffer_unref(&q->frames_ctx.mids_buf);
538
539     return 0;
540 }
541
542 int ff_qsv_process_data(AVCodecContext *avctx, QSVContext *q,
543                         AVFrame *frame, int *got_frame, AVPacket *pkt)
544 {
545     int ret;
546     mfxVideoParam param = { 0 };
547     enum AVPixelFormat pix_fmt = AV_PIX_FMT_NV12;
548
549     if (!pkt->size)
550         return qsv_decode(avctx, q, frame, got_frame, pkt);
551
552     /* TODO: flush delayed frames on reinit */
553
554     // sw_pix_fmt, coded_width/height should be set for ff_get_format(),
555     // assume sw_pix_fmt is NV12 and coded_width/height to be 1280x720,
556     // the assumption may be not corret but will be updated after header decoded if not true.
557     if (q->orig_pix_fmt != AV_PIX_FMT_NONE)
558         pix_fmt = q->orig_pix_fmt;
559     if (!avctx->coded_width)
560         avctx->coded_width = 1280;
561     if (!avctx->coded_height)
562         avctx->coded_height = 720;
563
564     ret = qsv_decode_header(avctx, q, pkt, pix_fmt, &param);
565
566     if (ret >= 0 && (q->orig_pix_fmt != ff_qsv_map_fourcc(param.mfx.FrameInfo.FourCC) ||
567         avctx->coded_width  != param.mfx.FrameInfo.Width ||
568         avctx->coded_height != param.mfx.FrameInfo.Height)) {
569         AVPacket zero_pkt = {0};
570
571         if (q->buffered_count) {
572             q->reinit_flag = 1;
573             /* decode zero-size pkt to flush the buffered pkt before reinit */
574             q->buffered_count--;
575             return qsv_decode(avctx, q, frame, got_frame, &zero_pkt);
576         }
577         q->reinit_flag = 0;
578
579         q->orig_pix_fmt = avctx->pix_fmt = pix_fmt = ff_qsv_map_fourcc(param.mfx.FrameInfo.FourCC);
580
581         avctx->coded_width  = param.mfx.FrameInfo.Width;
582         avctx->coded_height = param.mfx.FrameInfo.Height;
583
584         ret = qsv_decode_preinit(avctx, q, pix_fmt, &param);
585         if (ret < 0)
586             goto reinit_fail;
587         q->initialized = 0;
588     }
589
590     if (!q->initialized) {
591         ret = qsv_decode_init(avctx, q, &param);
592         if (ret < 0)
593             goto reinit_fail;
594         q->initialized = 1;
595     }
596
597     return qsv_decode(avctx, q, frame, got_frame, pkt);
598
599 reinit_fail:
600     q->orig_pix_fmt = avctx->pix_fmt = AV_PIX_FMT_NONE;
601     return ret;
602 }
603
604 void ff_qsv_decode_flush(AVCodecContext *avctx, QSVContext *q)
605 {
606     q->orig_pix_fmt = AV_PIX_FMT_NONE;
607     q->initialized = 0;
608 }