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