]> git.sesse.net Git - ffmpeg/blob - libavcodec/qsvdec.c
Merge commit '5085f25ace1e74846a0de3369bedd0e22d1a1bdc'
[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_session) {
66             MFXClose(q->internal_session);
67             q->internal_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_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_session;
84     } else if (hw_device_ref) {
85         if (q->internal_session) {
86             MFXClose(q->internal_session);
87             q->internal_session = NULL;
88         }
89
90         ret = ff_qsv_init_session_device(avctx, &q->internal_session,
91                                          hw_device_ref, q->load_plugins);
92         if (ret < 0)
93             return ret;
94
95         q->session = q->internal_session;
96     } else {
97         if (!q->internal_session) {
98             ret = ff_qsv_init_internal_session(avctx, &q->internal_session,
99                                                q->load_plugins);
100             if (ret < 0)
101                 return ret;
102         }
103
104         q->session = q->internal_session;
105     }
106
107     /* make sure the decoder is uninitialized */
108     MFXVideoDECODE_Close(q->session);
109
110     return 0;
111 }
112
113 static int qsv_decode_init(AVCodecContext *avctx, QSVContext *q)
114 {
115     const AVPixFmtDescriptor *desc;
116     mfxSession session = NULL;
117     int iopattern = 0;
118     mfxVideoParam param = { 0 };
119     int frame_width  = avctx->coded_width;
120     int frame_height = avctx->coded_height;
121     int ret;
122
123     desc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);
124     if (!desc)
125         return AVERROR_BUG;
126
127     if (!q->async_fifo) {
128         q->async_fifo = av_fifo_alloc((1 + q->async_depth) *
129                                       (sizeof(mfxSyncPoint*) + sizeof(QSVFrame*)));
130         if (!q->async_fifo)
131             return AVERROR(ENOMEM);
132     }
133
134     if (avctx->pix_fmt == AV_PIX_FMT_QSV && avctx->hwaccel_context) {
135         AVQSVContext *user_ctx = avctx->hwaccel_context;
136         session           = user_ctx->session;
137         iopattern         = user_ctx->iopattern;
138         q->ext_buffers    = user_ctx->ext_buffers;
139         q->nb_ext_buffers = user_ctx->nb_ext_buffers;
140     }
141
142     if (avctx->hw_frames_ctx) {
143         AVHWFramesContext    *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
144         AVQSVFramesContext *frames_hwctx = frames_ctx->hwctx;
145
146         if (!iopattern) {
147             if (frames_hwctx->frame_type & MFX_MEMTYPE_OPAQUE_FRAME)
148                 iopattern = MFX_IOPATTERN_OUT_OPAQUE_MEMORY;
149             else if (frames_hwctx->frame_type & MFX_MEMTYPE_VIDEO_MEMORY_DECODER_TARGET)
150                 iopattern = MFX_IOPATTERN_OUT_VIDEO_MEMORY;
151         }
152     }
153
154     if (!iopattern)
155         iopattern = MFX_IOPATTERN_OUT_SYSTEM_MEMORY;
156     q->iopattern = iopattern;
157
158     ret = qsv_init_session(avctx, q, session, avctx->hw_frames_ctx, avctx->hw_device_ctx);
159     if (ret < 0) {
160         av_log(avctx, AV_LOG_ERROR, "Error initializing an MFX session\n");
161         return ret;
162     }
163
164     ret = ff_qsv_codec_id_to_mfx(avctx->codec_id);
165     if (ret < 0)
166         return ret;
167
168     param.mfx.CodecId      = ret;
169     param.mfx.CodecProfile = ff_qsv_profile_to_mfx(avctx->codec_id, avctx->profile);
170     param.mfx.CodecLevel   = avctx->level == FF_LEVEL_UNKNOWN ? MFX_LEVEL_UNKNOWN : avctx->level;
171
172     param.mfx.FrameInfo.BitDepthLuma   = desc->comp[0].depth;
173     param.mfx.FrameInfo.BitDepthChroma = desc->comp[0].depth;
174     param.mfx.FrameInfo.Shift          = desc->comp[0].depth > 8;
175     param.mfx.FrameInfo.FourCC         = q->fourcc;
176     param.mfx.FrameInfo.Width          = frame_width;
177     param.mfx.FrameInfo.Height         = frame_height;
178     param.mfx.FrameInfo.ChromaFormat   = MFX_CHROMAFORMAT_YUV420;
179
180     switch (avctx->field_order) {
181     case AV_FIELD_PROGRESSIVE:
182         param.mfx.FrameInfo.PicStruct = MFX_PICSTRUCT_PROGRESSIVE;
183         break;
184     case AV_FIELD_TT:
185         param.mfx.FrameInfo.PicStruct = MFX_PICSTRUCT_FIELD_TFF;
186         break;
187     case AV_FIELD_BB:
188         param.mfx.FrameInfo.PicStruct = MFX_PICSTRUCT_FIELD_BFF;
189         break;
190     default:
191         param.mfx.FrameInfo.PicStruct = MFX_PICSTRUCT_UNKNOWN;
192         break;
193     }
194
195     param.IOPattern   = q->iopattern;
196     param.AsyncDepth  = q->async_depth;
197     param.ExtParam    = q->ext_buffers;
198     param.NumExtParam = q->nb_ext_buffers;
199
200     ret = MFXVideoDECODE_Init(q->session, &param);
201     if (ret < 0)
202         return ff_qsv_print_error(avctx, ret,
203                                   "Error initializing the MFX video decoder");
204
205     q->frame_info = param.mfx.FrameInfo;
206
207     return 0;
208 }
209
210 static int alloc_frame(AVCodecContext *avctx, QSVContext *q, QSVFrame *frame)
211 {
212     int ret;
213
214     ret = ff_get_buffer(avctx, frame->frame, AV_GET_BUFFER_FLAG_REF);
215     if (ret < 0)
216         return ret;
217
218     if (frame->frame->format == AV_PIX_FMT_QSV) {
219         frame->surface = *(mfxFrameSurface1*)frame->frame->data[3];
220     } else {
221         frame->surface.Info = q->frame_info;
222
223         frame->surface.Data.PitchLow = frame->frame->linesize[0];
224         frame->surface.Data.Y        = frame->frame->data[0];
225         frame->surface.Data.UV       = frame->frame->data[1];
226     }
227
228     if (q->frames_ctx.mids) {
229         ret = ff_qsv_find_surface_idx(&q->frames_ctx, frame);
230         if (ret < 0)
231             return ret;
232
233         frame->surface.Data.MemId = &q->frames_ctx.mids[ret];
234     }
235
236     frame->used = 1;
237
238     return 0;
239 }
240
241 static void qsv_clear_unused_frames(QSVContext *q)
242 {
243     QSVFrame *cur = q->work_frames;
244     while (cur) {
245         if (cur->used && !cur->surface.Data.Locked && !cur->queued) {
246             cur->used = 0;
247             av_frame_unref(cur->frame);
248         }
249         cur = cur->next;
250     }
251 }
252
253 static int get_surface(AVCodecContext *avctx, QSVContext *q, mfxFrameSurface1 **surf)
254 {
255     QSVFrame *frame, **last;
256     int ret;
257
258     qsv_clear_unused_frames(q);
259
260     frame = q->work_frames;
261     last  = &q->work_frames;
262     while (frame) {
263         if (!frame->used) {
264             ret = alloc_frame(avctx, q, frame);
265             if (ret < 0)
266                 return ret;
267             *surf = &frame->surface;
268             return 0;
269         }
270
271         last  = &frame->next;
272         frame = frame->next;
273     }
274
275     frame = av_mallocz(sizeof(*frame));
276     if (!frame)
277         return AVERROR(ENOMEM);
278     frame->frame = av_frame_alloc();
279     if (!frame->frame) {
280         av_freep(&frame);
281         return AVERROR(ENOMEM);
282     }
283     *last = frame;
284
285     ret = alloc_frame(avctx, q, frame);
286     if (ret < 0)
287         return ret;
288
289     *surf = &frame->surface;
290
291     return 0;
292 }
293
294 static QSVFrame *find_frame(QSVContext *q, mfxFrameSurface1 *surf)
295 {
296     QSVFrame *cur = q->work_frames;
297     while (cur) {
298         if (surf == &cur->surface)
299             return cur;
300         cur = cur->next;
301     }
302     return NULL;
303 }
304
305 static int qsv_decode(AVCodecContext *avctx, QSVContext *q,
306                       AVFrame *frame, int *got_frame,
307                       AVPacket *avpkt)
308 {
309     QSVFrame *out_frame;
310     mfxFrameSurface1 *insurf;
311     mfxFrameSurface1 *outsurf;
312     mfxSyncPoint *sync;
313     mfxBitstream bs = { { { 0 } } };
314     int ret;
315
316     if (avpkt->size) {
317         bs.Data       = avpkt->data;
318         bs.DataLength = avpkt->size;
319         bs.MaxLength  = bs.DataLength;
320         bs.TimeStamp  = avpkt->pts;
321     }
322
323     sync = av_mallocz(sizeof(*sync));
324     if (!sync) {
325         av_freep(&sync);
326         return AVERROR(ENOMEM);
327     }
328
329     do {
330         ret = get_surface(avctx, q, &insurf);
331         if (ret < 0) {
332             av_freep(&sync);
333             return ret;
334         }
335
336         ret = MFXVideoDECODE_DecodeFrameAsync(q->session, avpkt->size ? &bs : NULL,
337                                               insurf, &outsurf, sync);
338         if (ret == MFX_WRN_DEVICE_BUSY)
339             av_usleep(500);
340
341     } while (ret == MFX_WRN_DEVICE_BUSY || ret == MFX_ERR_MORE_SURFACE);
342
343     if (ret != MFX_ERR_NONE &&
344         ret != MFX_ERR_MORE_DATA &&
345         ret != MFX_WRN_VIDEO_PARAM_CHANGED &&
346         ret != MFX_ERR_MORE_SURFACE) {
347         av_freep(&sync);
348         return ff_qsv_print_error(avctx, ret,
349                                   "Error during QSV decoding.");
350     }
351
352     /* make sure we do not enter an infinite loop if the SDK
353      * did not consume any data and did not return anything */
354     if (!*sync && !bs.DataOffset) {
355         bs.DataOffset = avpkt->size;
356         ++q->zero_consume_run;
357         if (q->zero_consume_run > 1)
358             ff_qsv_print_warning(avctx, ret, "A decode call did not consume any data");
359     } else {
360         q->zero_consume_run = 0;
361     }
362
363     if (*sync) {
364         QSVFrame *out_frame = find_frame(q, outsurf);
365
366         if (!out_frame) {
367             av_log(avctx, AV_LOG_ERROR,
368                    "The returned surface does not correspond to any frame\n");
369             av_freep(&sync);
370             return AVERROR_BUG;
371         }
372
373         out_frame->queued = 1;
374         av_fifo_generic_write(q->async_fifo, &out_frame, sizeof(out_frame), NULL);
375         av_fifo_generic_write(q->async_fifo, &sync,      sizeof(sync),      NULL);
376     } else {
377         av_freep(&sync);
378     }
379
380     if (!av_fifo_space(q->async_fifo) ||
381         (!avpkt->size && av_fifo_size(q->async_fifo))) {
382         AVFrame *src_frame;
383
384         av_fifo_generic_read(q->async_fifo, &out_frame, sizeof(out_frame), NULL);
385         av_fifo_generic_read(q->async_fifo, &sync,      sizeof(sync),      NULL);
386         out_frame->queued = 0;
387
388         if (avctx->pix_fmt != AV_PIX_FMT_QSV) {
389             do {
390                 ret = MFXVideoCORE_SyncOperation(q->session, *sync, 1000);
391             } while (ret == MFX_WRN_IN_EXECUTION);
392         }
393
394         av_freep(&sync);
395
396         src_frame = out_frame->frame;
397
398         ret = av_frame_ref(frame, src_frame);
399         if (ret < 0)
400             return ret;
401
402         outsurf = &out_frame->surface;
403
404 #if FF_API_PKT_PTS
405 FF_DISABLE_DEPRECATION_WARNINGS
406         frame->pkt_pts = outsurf->Data.TimeStamp;
407 FF_ENABLE_DEPRECATION_WARNINGS
408 #endif
409         frame->pts = outsurf->Data.TimeStamp;
410
411         frame->repeat_pict =
412             outsurf->Info.PicStruct & MFX_PICSTRUCT_FRAME_TRIPLING ? 4 :
413             outsurf->Info.PicStruct & MFX_PICSTRUCT_FRAME_DOUBLING ? 2 :
414             outsurf->Info.PicStruct & MFX_PICSTRUCT_FIELD_REPEATED ? 1 : 0;
415         frame->top_field_first =
416             outsurf->Info.PicStruct & MFX_PICSTRUCT_FIELD_TFF;
417         frame->interlaced_frame =
418             !(outsurf->Info.PicStruct & MFX_PICSTRUCT_PROGRESSIVE);
419
420         /* update the surface properties */
421         if (avctx->pix_fmt == AV_PIX_FMT_QSV)
422             ((mfxFrameSurface1*)frame->data[3])->Info = outsurf->Info;
423
424         *got_frame = 1;
425     }
426
427     return bs.DataOffset;
428 }
429
430 int ff_qsv_decode_close(QSVContext *q)
431 {
432     QSVFrame *cur = q->work_frames;
433
434     if (q->session)
435         MFXVideoDECODE_Close(q->session);
436
437     while (q->async_fifo && av_fifo_size(q->async_fifo)) {
438         QSVFrame *out_frame;
439         mfxSyncPoint *sync;
440
441         av_fifo_generic_read(q->async_fifo, &out_frame, sizeof(out_frame), NULL);
442         av_fifo_generic_read(q->async_fifo, &sync,      sizeof(sync),      NULL);
443
444         av_freep(&sync);
445     }
446
447     while (cur) {
448         q->work_frames = cur->next;
449         av_frame_free(&cur->frame);
450         av_freep(&cur);
451         cur = q->work_frames;
452     }
453
454     av_fifo_free(q->async_fifo);
455     q->async_fifo = NULL;
456
457     av_parser_close(q->parser);
458     avcodec_free_context(&q->avctx_internal);
459
460     if (q->internal_session)
461         MFXClose(q->internal_session);
462
463     av_buffer_unref(&q->frames_ctx.hw_frames_ctx);
464     av_buffer_unref(&q->frames_ctx.mids_buf);
465
466     return 0;
467 }
468
469 int ff_qsv_process_data(AVCodecContext *avctx, QSVContext *q,
470                         AVFrame *frame, int *got_frame, AVPacket *pkt)
471 {
472     uint8_t *dummy_data;
473     int dummy_size;
474     int ret;
475     const AVPixFmtDescriptor *desc;
476
477     if (!q->avctx_internal) {
478         q->avctx_internal = avcodec_alloc_context3(NULL);
479         if (!q->avctx_internal)
480             return AVERROR(ENOMEM);
481
482         q->parser = av_parser_init(avctx->codec_id);
483         if (!q->parser)
484             return AVERROR(ENOMEM);
485
486         q->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
487         q->orig_pix_fmt   = AV_PIX_FMT_NONE;
488     }
489
490     if (!pkt->size)
491         return qsv_decode(avctx, q, frame, got_frame, pkt);
492
493     /* we assume the packets are already split properly and want
494      * just the codec parameters here */
495     av_parser_parse2(q->parser, q->avctx_internal,
496                      &dummy_data, &dummy_size,
497                      pkt->data, pkt->size, pkt->pts, pkt->dts,
498                      pkt->pos);
499
500     /* TODO: flush delayed frames on reinit */
501     if (q->parser->format       != q->orig_pix_fmt    ||
502         FFALIGN(q->parser->coded_width, 16)  != FFALIGN(avctx->coded_width, 16) ||
503         FFALIGN(q->parser->coded_height, 16) != FFALIGN(avctx->coded_height, 16)) {
504         enum AVPixelFormat pix_fmts[3] = { AV_PIX_FMT_QSV,
505                                            AV_PIX_FMT_NONE,
506                                            AV_PIX_FMT_NONE };
507         enum AVPixelFormat qsv_format;
508
509         qsv_format = ff_qsv_map_pixfmt(q->parser->format, &q->fourcc);
510         if (qsv_format < 0) {
511             av_log(avctx, AV_LOG_ERROR,
512                    "Decoding pixel format '%s' is not supported\n",
513                    av_get_pix_fmt_name(q->parser->format));
514             ret = AVERROR(ENOSYS);
515             goto reinit_fail;
516         }
517
518         q->orig_pix_fmt     = q->parser->format;
519         avctx->pix_fmt      = pix_fmts[1] = qsv_format;
520         avctx->width        = q->parser->width;
521         avctx->height       = q->parser->height;
522         avctx->coded_width  = FFALIGN(q->parser->coded_width, 16);
523         avctx->coded_height = FFALIGN(q->parser->coded_height, 16);
524         avctx->field_order  = q->parser->field_order;
525         avctx->level        = q->avctx_internal->level;
526         avctx->profile      = q->avctx_internal->profile;
527
528         ret = ff_get_format(avctx, pix_fmts);
529         if (ret < 0)
530             goto reinit_fail;
531
532         avctx->pix_fmt = ret;
533
534         desc = av_pix_fmt_desc_get(avctx->pix_fmt);
535         if (!desc)
536             goto reinit_fail;
537
538          if (desc->comp[0].depth > 8) {
539             avctx->coded_width =  FFALIGN(q->parser->coded_width, 32);
540             avctx->coded_height = FFALIGN(q->parser->coded_height, 32);
541         }
542
543         ret = qsv_decode_init(avctx, q);
544         if (ret < 0)
545             goto reinit_fail;
546     }
547
548     return qsv_decode(avctx, q, frame, got_frame, pkt);
549
550 reinit_fail:
551     q->orig_pix_fmt = q->parser->format = avctx->pix_fmt = AV_PIX_FMT_NONE;
552     return ret;
553 }
554
555 void ff_qsv_decode_flush(AVCodecContext *avctx, QSVContext *q)
556 {
557     q->orig_pix_fmt = AV_PIX_FMT_NONE;
558 }