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