]> git.sesse.net Git - ffmpeg/blob - libavcodec/qsvdec.c
Merge commit '678f788fea3380e5cbbf75baac5cc0ce07a56a42'
[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/mem.h"
31 #include "libavutil/log.h"
32 #include "libavutil/pixfmt.h"
33 #include "libavutil/time.h"
34
35 #include "avcodec.h"
36 #include "internal.h"
37 #include "qsv.h"
38 #include "qsv_internal.h"
39 #include "qsvdec.h"
40
41 int ff_qsv_map_pixfmt(enum AVPixelFormat format)
42 {
43     switch (format) {
44     case AV_PIX_FMT_YUV420P:
45     case AV_PIX_FMT_YUVJ420P:
46         return AV_PIX_FMT_NV12;
47     default:
48         return AVERROR(ENOSYS);
49     }
50 }
51
52 static int qsv_decode_init(AVCodecContext *avctx, QSVContext *q, AVPacket *avpkt)
53 {
54     mfxVideoParam param = { { 0 } };
55     mfxBitstream bs   = { { { 0 } } };
56     int ret;
57     enum AVPixelFormat pix_fmts[3] = { AV_PIX_FMT_QSV,
58                                        AV_PIX_FMT_NV12,
59                                        AV_PIX_FMT_NONE };
60
61     q->iopattern  = MFX_IOPATTERN_OUT_SYSTEM_MEMORY;
62     if (!q->session) {
63         if (avctx->hwaccel_context) {
64             AVQSVContext *qsv = avctx->hwaccel_context;
65
66             q->session        = qsv->session;
67             q->iopattern      = qsv->iopattern;
68             q->ext_buffers    = qsv->ext_buffers;
69             q->nb_ext_buffers = qsv->nb_ext_buffers;
70         }
71         if (!q->session) {
72             ret = ff_qsv_init_internal_session(avctx, &q->internal_qs,
73                                                q->load_plugins);
74             if (ret < 0)
75                 return ret;
76
77             q->session = q->internal_qs.session;
78         }
79     }
80
81     if (avpkt->size) {
82         bs.Data       = avpkt->data;
83         bs.DataLength = avpkt->size;
84         bs.MaxLength  = bs.DataLength;
85         bs.TimeStamp  = avpkt->pts;
86     } else
87         return AVERROR_INVALIDDATA;
88
89     ret = ff_qsv_codec_id_to_mfx(avctx->codec_id);
90     if (ret < 0) {
91         av_log(avctx, AV_LOG_ERROR, "Unsupported codec_id %08x\n", avctx->codec_id);
92         return ret;
93     }
94
95     param.mfx.CodecId = ret;
96
97     ret = MFXVideoDECODE_DecodeHeader(q->session, &bs, &param);
98     if (MFX_ERR_MORE_DATA==ret) {
99         /* this code means that header not found so we return packet size to skip
100            a current packet
101          */
102         return avpkt->size;
103     } else if (ret < 0) {
104         av_log(avctx, AV_LOG_ERROR, "Decode header error %d\n", ret);
105         return ff_qsv_error(ret);
106     }
107     param.IOPattern   = q->iopattern;
108     param.AsyncDepth  = q->async_depth;
109     param.ExtParam    = q->ext_buffers;
110     param.NumExtParam = q->nb_ext_buffers;
111     param.mfx.FrameInfo.BitDepthLuma   = 8;
112     param.mfx.FrameInfo.BitDepthChroma = 8;
113
114     ret = MFXVideoDECODE_Init(q->session, &param);
115     if (ret < 0) {
116         if (MFX_ERR_INVALID_VIDEO_PARAM==ret) {
117             av_log(avctx, AV_LOG_ERROR,
118                    "Error initializing the MFX video decoder, unsupported video\n");
119         } else {
120             av_log(avctx, AV_LOG_ERROR,
121                    "Error initializing the MFX video decoder %d\n", ret);
122         }
123         return ff_qsv_error(ret);
124     }
125
126     ret = ff_get_format(avctx, pix_fmts);
127     if (ret < 0)
128         return ret;
129
130     avctx->pix_fmt      = ret;
131     avctx->profile      = param.mfx.CodecProfile;
132     avctx->level        = param.mfx.CodecLevel;
133     avctx->coded_width  = param.mfx.FrameInfo.Width;
134     avctx->coded_height = param.mfx.FrameInfo.Height;
135     avctx->width        = param.mfx.FrameInfo.CropW - param.mfx.FrameInfo.CropX;
136     avctx->height       = param.mfx.FrameInfo.CropH - param.mfx.FrameInfo.CropY;
137
138     /* maximum decoder latency should be not exceed max DPB size for h.264 and
139        HEVC which is 16 for both cases.
140        So weare  pre-allocating fifo big enough for 17 elements:
141      */
142     if (!q->async_fifo) {
143         q->async_fifo = av_fifo_alloc((1 + 16) *
144                                       (sizeof(mfxSyncPoint) + sizeof(QSVFrame*)));
145         if (!q->async_fifo)
146             return AVERROR(ENOMEM);
147     }
148
149     if (!q->input_fifo) {
150         q->input_fifo = av_fifo_alloc(1024*16);
151         if (!q->input_fifo)
152             return AVERROR(ENOMEM);
153     }
154
155     if (!q->pkt_fifo) {
156         q->pkt_fifo = av_fifo_alloc( sizeof(AVPacket) * (1 + 16) );
157         if (!q->pkt_fifo)
158             return AVERROR(ENOMEM);
159     }
160     q->engine_ready = 1;
161
162     return 0;
163 }
164
165 static int alloc_frame(AVCodecContext *avctx, QSVFrame *frame)
166 {
167     int ret;
168
169     ret = ff_get_buffer(avctx, frame->frame, AV_GET_BUFFER_FLAG_REF);
170     if (ret < 0)
171         return ret;
172
173     if (frame->frame->format == AV_PIX_FMT_QSV) {
174         frame->surface = (mfxFrameSurface1*)frame->frame->data[3];
175     } else {
176         frame->surface_internal.Info.BitDepthLuma   = 8;
177         frame->surface_internal.Info.BitDepthChroma = 8;
178         frame->surface_internal.Info.FourCC         = MFX_FOURCC_NV12;
179         frame->surface_internal.Info.Width          = avctx->coded_width;
180         frame->surface_internal.Info.Height         = avctx->coded_height;
181         frame->surface_internal.Info.ChromaFormat   = MFX_CHROMAFORMAT_YUV420;
182
183         frame->surface_internal.Data.PitchLow = frame->frame->linesize[0];
184         frame->surface_internal.Data.Y        = frame->frame->data[0];
185         frame->surface_internal.Data.UV       = frame->frame->data[1];
186
187         frame->surface = &frame->surface_internal;
188     }
189
190     return 0;
191 }
192
193 static void qsv_clear_unused_frames(QSVContext *q)
194 {
195     QSVFrame *cur = q->work_frames;
196     while (cur) {
197         if (cur->surface && !cur->surface->Data.Locked && !cur->queued) {
198             cur->surface = NULL;
199             av_frame_unref(cur->frame);
200         }
201         cur = cur->next;
202     }
203 }
204
205 static int get_surface(AVCodecContext *avctx, QSVContext *q, mfxFrameSurface1 **surf)
206 {
207     QSVFrame *frame, **last;
208     int ret;
209
210     qsv_clear_unused_frames(q);
211
212     frame = q->work_frames;
213     last  = &q->work_frames;
214     while (frame) {
215         if (!frame->surface) {
216             ret = alloc_frame(avctx, frame);
217             if (ret < 0)
218                 return ret;
219             *surf = frame->surface;
220             return 0;
221         }
222
223         last  = &frame->next;
224         frame = frame->next;
225     }
226
227     frame = av_mallocz(sizeof(*frame));
228     if (!frame)
229         return AVERROR(ENOMEM);
230     frame->frame = av_frame_alloc();
231     if (!frame->frame) {
232         av_freep(&frame);
233         return AVERROR(ENOMEM);
234     }
235     *last = frame;
236
237     ret = alloc_frame(avctx, frame);
238     if (ret < 0)
239         return ret;
240
241     *surf = frame->surface;
242
243     return 0;
244 }
245
246 static QSVFrame *find_frame(QSVContext *q, mfxFrameSurface1 *surf)
247 {
248     QSVFrame *cur = q->work_frames;
249     while (cur) {
250         if (surf == cur->surface)
251             return cur;
252         cur = cur->next;
253     }
254     return NULL;
255 }
256
257 /*  This function uses for 'smart' releasing of consumed data
258     from the input bitstream fifo.
259     Since the input fifo mapped to mfxBitstream which does not understand
260     a wrapping of data over fifo end, we should also to relocate a possible
261     data rest to fifo begin. If rest of data is absent then we just reset fifo's
262     pointers to initial positions.
263     NOTE the case when fifo does contain unconsumed data is rare and typical
264     amount of such data is 1..4 bytes.
265 */
266 static void qsv_fifo_relocate(AVFifoBuffer *f, int bytes_to_free)
267 {
268     int data_size;
269     int data_rest = 0;
270
271     av_fifo_drain(f, bytes_to_free);
272
273     data_size = av_fifo_size(f);
274     if (data_size > 0) {
275         if (f->buffer!=f->rptr) {
276             if ( (f->end - f->rptr) < data_size) {
277                 data_rest = data_size - (f->end - f->rptr);
278                 data_size-=data_rest;
279                 memmove(f->buffer+data_size, f->buffer, data_rest);
280             }
281             memmove(f->buffer, f->rptr, data_size);
282             data_size+= data_rest;
283         }
284     }
285     f->rptr = f->buffer;
286     f->wptr = f->buffer + data_size;
287     f->wndx = data_size;
288     f->rndx = 0;
289 }
290
291
292 static void close_decoder(QSVContext *q)
293 {
294     QSVFrame *cur;
295
296     if (q->session)
297         MFXVideoDECODE_Close(q->session);
298
299     cur = q->work_frames;
300     while (cur) {
301         q->work_frames = cur->next;
302         av_frame_free(&cur->frame);
303         av_freep(&cur);
304         cur = q->work_frames;
305     }
306
307     q->engine_ready   = 0;
308     q->reinit_pending = 0;
309 }
310
311 static int do_qsv_decode(AVCodecContext *avctx, QSVContext *q,
312                   AVFrame *frame, int *got_frame,
313                   AVPacket *avpkt)
314 {
315     QSVFrame *out_frame;
316     mfxFrameSurface1 *insurf;
317     mfxFrameSurface1 *outsurf;
318     mfxSyncPoint sync;
319     mfxBitstream bs = { { { 0 } } };
320     int ret;
321     int n_out_frames;
322     int buffered = 0;
323     int flush    = !avpkt->size || q->reinit_pending;
324
325     if (!q->engine_ready) {
326         ret = qsv_decode_init(avctx, q, avpkt);
327         if (ret)
328             return ret;
329     }
330
331     if (!flush) {
332         if (av_fifo_size(q->input_fifo)) {
333             /* we have got rest of previous packet into buffer */
334             if (av_fifo_space(q->input_fifo) < avpkt->size) {
335                 ret = av_fifo_grow(q->input_fifo, avpkt->size);
336                 if (ret < 0)
337                     return ret;
338             }
339             av_fifo_generic_write(q->input_fifo, avpkt->data, avpkt->size, NULL);
340             bs.Data       = q->input_fifo->rptr;
341             bs.DataLength = av_fifo_size(q->input_fifo);
342             buffered = 1;
343         } else {
344             bs.Data       = avpkt->data;
345             bs.DataLength = avpkt->size;
346         }
347         bs.MaxLength  = bs.DataLength;
348         bs.TimeStamp  = avpkt->pts;
349     }
350
351     while (1) {
352         ret = get_surface(avctx, q, &insurf);
353         if (ret < 0)
354             return ret;
355         do {
356             ret = MFXVideoDECODE_DecodeFrameAsync(q->session, flush ? NULL : &bs,
357                                                   insurf, &outsurf, &sync);
358             if (ret != MFX_WRN_DEVICE_BUSY)
359                 break;
360             av_usleep(500);
361         } while (1);
362
363         if (MFX_WRN_VIDEO_PARAM_CHANGED==ret) {
364             /* TODO: handle here minor sequence header changing */
365         } else if (MFX_ERR_INCOMPATIBLE_VIDEO_PARAM==ret) {
366             av_fifo_reset(q->input_fifo);
367             flush = q->reinit_pending = 1;
368             continue;
369         }
370
371         if (sync) {
372             QSVFrame *out_frame = find_frame(q, outsurf);
373
374             if (!out_frame) {
375                 av_log(avctx, AV_LOG_ERROR,
376                        "The returned surface does not correspond to any frame\n");
377                 return AVERROR_BUG;
378             }
379
380             out_frame->queued = 1;
381             av_fifo_generic_write(q->async_fifo, &out_frame, sizeof(out_frame), NULL);
382             av_fifo_generic_write(q->async_fifo, &sync,      sizeof(sync),      NULL);
383
384             continue;
385         }
386         if (MFX_ERR_MORE_SURFACE != ret && ret < 0)
387             break;
388     }
389
390     /* make sure we do not enter an infinite loop if the SDK
391      * did not consume any data and did not return anything */
392     if (!sync && !bs.DataOffset && !flush) {
393         av_log(avctx, AV_LOG_WARNING, "A decode call did not consume any data\n");
394         bs.DataOffset = avpkt->size;
395     }
396
397     if (buffered) {
398         qsv_fifo_relocate(q->input_fifo, bs.DataOffset);
399     } else if (bs.DataOffset!=avpkt->size) {
400         /* some data of packet was not consumed. store it to local buffer */
401         av_fifo_generic_write(q->input_fifo, avpkt->data+bs.DataOffset,
402                               avpkt->size - bs.DataOffset, NULL);
403     }
404
405     if (MFX_ERR_MORE_DATA!=ret && ret < 0) {
406         av_log(avctx, AV_LOG_ERROR, "Error %d during QSV decoding.\n", ret);
407         return ff_qsv_error(ret);
408     }
409     n_out_frames = av_fifo_size(q->async_fifo) / (sizeof(out_frame)+sizeof(sync));
410
411     if (n_out_frames > q->async_depth || (flush && n_out_frames) ) {
412         AVFrame *src_frame;
413
414         av_fifo_generic_read(q->async_fifo, &out_frame, sizeof(out_frame), NULL);
415         av_fifo_generic_read(q->async_fifo, &sync,      sizeof(sync),      NULL);
416         out_frame->queued = 0;
417
418         MFXVideoCORE_SyncOperation(q->session, sync, 60000);
419
420         src_frame = out_frame->frame;
421
422         ret = av_frame_ref(frame, src_frame);
423         if (ret < 0)
424             return ret;
425
426         outsurf = out_frame->surface;
427
428         frame->pkt_pts = frame->pts = outsurf->Data.TimeStamp;
429
430         frame->repeat_pict =
431             outsurf->Info.PicStruct & MFX_PICSTRUCT_FRAME_TRIPLING ? 4 :
432             outsurf->Info.PicStruct & MFX_PICSTRUCT_FRAME_DOUBLING ? 2 :
433             outsurf->Info.PicStruct & MFX_PICSTRUCT_FIELD_REPEATED ? 1 : 0;
434         frame->top_field_first =
435             outsurf->Info.PicStruct & MFX_PICSTRUCT_FIELD_TFF;
436         frame->interlaced_frame =
437             !(outsurf->Info.PicStruct & MFX_PICSTRUCT_PROGRESSIVE);
438
439         *got_frame = 1;
440     }
441
442     return avpkt->size;
443 }
444 /*
445  This function inserts a packet at fifo front.
446 */
447 static void qsv_packet_push_front(QSVContext *q, AVPacket *avpkt)
448 {
449     int fifo_size = av_fifo_size(q->pkt_fifo);
450     if (!fifo_size) {
451     /* easy case fifo is empty */
452         av_fifo_generic_write(q->pkt_fifo, avpkt, sizeof(*avpkt), NULL);
453     } else {
454     /* realloc necessary */
455         AVPacket pkt;
456         AVFifoBuffer *fifo = av_fifo_alloc(fifo_size+av_fifo_space(q->pkt_fifo));
457
458         av_fifo_generic_write(fifo, avpkt, sizeof(*avpkt), NULL);
459
460         while (av_fifo_size(q->pkt_fifo)) {
461             av_fifo_generic_read(q->pkt_fifo, &pkt, sizeof(pkt), NULL);
462             av_fifo_generic_write(fifo,       &pkt, sizeof(pkt), NULL);
463         }
464         av_fifo_free(q->pkt_fifo);
465         q->pkt_fifo = fifo;
466     }
467 }
468 int ff_qsv_decode(AVCodecContext *avctx, QSVContext *q,
469                   AVFrame *frame, int *got_frame,
470                   AVPacket *avpkt)
471 {
472     AVPacket pkt_ref = { 0 };
473     int ret = 0;
474
475     if (q->pkt_fifo && av_fifo_size(q->pkt_fifo) >= sizeof(AVPacket)) {
476         /* we already have got some buffered packets. so add new to tail */
477         ret = av_packet_ref(&pkt_ref, avpkt);
478         if (ret < 0)
479             return ret;
480         av_fifo_generic_write(q->pkt_fifo, &pkt_ref, sizeof(pkt_ref), NULL);
481     }
482     if (q->reinit_pending) {
483         ret = do_qsv_decode(avctx, q, frame, got_frame, avpkt);
484
485         if (!*got_frame) {
486             /* Flushing complete, no more frames  */
487             close_decoder(q);
488             //return ff_qsv_decode(avctx, q, frame, got_frame, avpkt);
489         }
490     }
491     if (!q->reinit_pending) {
492         if (q->pkt_fifo && av_fifo_size(q->pkt_fifo) >= sizeof(AVPacket)) {
493             /* process buffered packets */
494             while (!*got_frame && av_fifo_size(q->pkt_fifo) >= sizeof(AVPacket)) {
495                 av_fifo_generic_read(q->pkt_fifo, &pkt_ref, sizeof(pkt_ref), NULL);
496                 ret = do_qsv_decode(avctx, q, frame, got_frame, &pkt_ref);
497                 if (q->reinit_pending) {
498                     /*
499                        A rare case: new reinit pending when buffering existing.
500                        We should to return the pkt_ref back to same place of fifo
501                     */
502                     qsv_packet_push_front(q, &pkt_ref);
503                 } else {
504                     av_packet_unref(&pkt_ref);
505                 }
506            }
507         } else {
508             /* general decoding */
509             ret = do_qsv_decode(avctx, q, frame, got_frame, avpkt);
510             if (q->reinit_pending) {
511                 ret = av_packet_ref(&pkt_ref, avpkt);
512                 if (ret < 0)
513                     return ret;
514                 av_fifo_generic_write(q->pkt_fifo, &pkt_ref, sizeof(pkt_ref), NULL);
515             }
516         }
517     }
518
519     return ret;
520 }
521 /*
522  This function resets decoder and corresponded buffers before seek operation
523 */
524 void ff_qsv_decode_reset(AVCodecContext *avctx, QSVContext *q)
525 {
526     QSVFrame *cur;
527     AVPacket pkt;
528     int ret = 0;
529     mfxVideoParam param = { { 0 } };
530
531     if (q->reinit_pending) {
532         close_decoder(q);
533     } else if (q->engine_ready) {
534         ret = MFXVideoDECODE_GetVideoParam(q->session, &param);
535         if (ret < 0) {
536             av_log(avctx, AV_LOG_ERROR, "MFX decode get param error %d\n", ret);
537         }
538
539         ret = MFXVideoDECODE_Reset(q->session, &param);
540         if (ret < 0) {
541             av_log(avctx, AV_LOG_ERROR, "MFX decode reset error %d\n", ret);
542         }
543
544         /* Free all frames*/
545         cur = q->work_frames;
546         while (cur) {
547             q->work_frames = cur->next;
548             av_frame_free(&cur->frame);
549             av_freep(&cur);
550             cur = q->work_frames;
551         }
552     }
553
554     /* Reset output surfaces */
555     av_fifo_reset(q->async_fifo);
556
557     /* Reset input packets fifo */
558     while (av_fifo_size(q->pkt_fifo)) {
559         av_fifo_generic_read(q->pkt_fifo, &pkt, sizeof(pkt), NULL);
560         av_packet_unref(&pkt);
561     }
562
563     /* Reset input bitstream fifo */
564     av_fifo_reset(q->input_fifo);
565 }
566
567 int ff_qsv_decode_close(QSVContext *q)
568 {
569     close_decoder(q);
570
571     q->session = NULL;
572
573     ff_qsv_close_internal_session(&q->internal_qs);
574
575     av_fifo_free(q->async_fifo);
576     q->async_fifo = NULL;
577
578     av_fifo_free(q->input_fifo);
579     q->input_fifo = NULL;
580
581     av_fifo_free(q->pkt_fifo);
582     q->pkt_fifo = NULL;
583
584     return 0;
585 }