]> git.sesse.net Git - ffmpeg/blob - libavcodec/qsvdec.c
5263bf5971fba7fbfe4f539a071526b3a18bcd13
[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 Libav.
8  *
9  * Libav 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  * Libav 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 Libav; 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_init_session(AVCodecContext *avctx, QSVContext *q, mfxSession session)
53 {
54     if (!session) {
55         if (!q->internal_session) {
56             int ret = ff_qsv_init_internal_session(avctx, &q->internal_session, NULL);
57             if (ret < 0)
58                 return ret;
59         }
60
61         q->session = q->internal_session;
62     } else {
63         q->session = session;
64     }
65
66     /* make sure the decoder is uninitialized */
67     MFXVideoDECODE_Close(q->session);
68
69     return 0;
70 }
71
72 int ff_qsv_decode_init(AVCodecContext *avctx, QSVContext *q, mfxSession session)
73 {
74     mfxVideoParam param = { { 0 } };
75     int ret;
76
77     if (!q->async_fifo) {
78         q->async_fifo = av_fifo_alloc((1 + q->async_depth) *
79                                       (sizeof(mfxSyncPoint) + sizeof(QSVFrame*)));
80         if (!q->async_fifo)
81             return AVERROR(ENOMEM);
82     }
83
84     ret = qsv_init_session(avctx, q, session);
85     if (ret < 0) {
86         av_log(avctx, AV_LOG_ERROR, "Error initializing an MFX session\n");
87         return ret;
88     }
89
90
91     ret = ff_qsv_codec_id_to_mfx(avctx->codec_id);
92     if (ret < 0)
93         return ret;
94
95     param.mfx.CodecId      = ret;
96     param.mfx.CodecProfile = avctx->profile;
97     param.mfx.CodecLevel   = avctx->level;
98
99     param.mfx.FrameInfo.BitDepthLuma   = 8;
100     param.mfx.FrameInfo.BitDepthChroma = 8;
101     param.mfx.FrameInfo.Shift          = 0;
102     param.mfx.FrameInfo.FourCC         = MFX_FOURCC_NV12;
103     param.mfx.FrameInfo.Width          = avctx->coded_width;
104     param.mfx.FrameInfo.Height         = avctx->coded_height;
105     param.mfx.FrameInfo.ChromaFormat   = MFX_CHROMAFORMAT_YUV420;
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
112     ret = MFXVideoDECODE_Init(q->session, &param);
113     if (ret < 0) {
114         av_log(avctx, AV_LOG_ERROR, "Error initializing the MFX video decoder\n");
115         return ff_qsv_error(ret);
116     }
117
118     return 0;
119 }
120
121 static int alloc_frame(AVCodecContext *avctx, QSVFrame *frame)
122 {
123     int ret;
124
125     ret = ff_get_buffer(avctx, frame->frame, AV_GET_BUFFER_FLAG_REF);
126     if (ret < 0)
127         return ret;
128
129     if (frame->frame->format == AV_PIX_FMT_QSV) {
130         frame->surface = (mfxFrameSurface1*)frame->frame->data[3];
131     } else {
132         frame->surface_internal.Info.BitDepthLuma   = 8;
133         frame->surface_internal.Info.BitDepthChroma = 8;
134         frame->surface_internal.Info.FourCC         = MFX_FOURCC_NV12;
135         frame->surface_internal.Info.Width          = avctx->coded_width;
136         frame->surface_internal.Info.Height         = avctx->coded_height;
137         frame->surface_internal.Info.ChromaFormat   = MFX_CHROMAFORMAT_YUV420;
138
139         frame->surface_internal.Data.PitchLow = frame->frame->linesize[0];
140         frame->surface_internal.Data.Y        = frame->frame->data[0];
141         frame->surface_internal.Data.UV       = frame->frame->data[1];
142
143         frame->surface = &frame->surface_internal;
144     }
145
146     return 0;
147 }
148
149 static void qsv_clear_unused_frames(QSVContext *q)
150 {
151     QSVFrame *cur = q->work_frames;
152     while (cur) {
153         if (cur->surface && !cur->surface->Data.Locked && !cur->queued) {
154             cur->surface = NULL;
155             av_frame_unref(cur->frame);
156         }
157         cur = cur->next;
158     }
159 }
160
161 static int get_surface(AVCodecContext *avctx, QSVContext *q, mfxFrameSurface1 **surf)
162 {
163     QSVFrame *frame, **last;
164     int ret;
165
166     qsv_clear_unused_frames(q);
167
168     frame = q->work_frames;
169     last  = &q->work_frames;
170     while (frame) {
171         if (!frame->surface) {
172             ret = alloc_frame(avctx, frame);
173             if (ret < 0)
174                 return ret;
175             *surf = frame->surface;
176             return 0;
177         }
178
179         last  = &frame->next;
180         frame = frame->next;
181     }
182
183     frame = av_mallocz(sizeof(*frame));
184     if (!frame)
185         return AVERROR(ENOMEM);
186     frame->frame = av_frame_alloc();
187     if (!frame->frame) {
188         av_freep(&frame);
189         return AVERROR(ENOMEM);
190     }
191     *last = frame;
192
193     ret = alloc_frame(avctx, frame);
194     if (ret < 0)
195         return ret;
196
197     *surf = frame->surface;
198
199     return 0;
200 }
201
202 static QSVFrame *find_frame(QSVContext *q, mfxFrameSurface1 *surf)
203 {
204     QSVFrame *cur = q->work_frames;
205     while (cur) {
206         if (surf == cur->surface)
207             return cur;
208         cur = cur->next;
209     }
210     return NULL;
211 }
212
213 static int qsv_decode(AVCodecContext *avctx, QSVContext *q,
214                       AVFrame *frame, int *got_frame,
215                       AVPacket *avpkt)
216 {
217     QSVFrame *out_frame;
218     mfxFrameSurface1 *insurf;
219     mfxFrameSurface1 *outsurf;
220     mfxSyncPoint sync;
221     mfxBitstream bs = { { { 0 } } };
222     int ret;
223
224     if (avpkt->size) {
225         bs.Data       = avpkt->data;
226         bs.DataLength = avpkt->size;
227         bs.MaxLength  = bs.DataLength;
228         bs.TimeStamp  = avpkt->pts;
229     }
230
231     do {
232         ret = get_surface(avctx, q, &insurf);
233         if (ret < 0)
234             return ret;
235
236         ret = MFXVideoDECODE_DecodeFrameAsync(q->session, avpkt->size ? &bs : NULL,
237                                               insurf, &outsurf, &sync);
238         if (ret == MFX_WRN_DEVICE_BUSY)
239             av_usleep(1);
240
241     } while (ret == MFX_WRN_DEVICE_BUSY || ret == MFX_ERR_MORE_SURFACE);
242
243     if (ret != MFX_ERR_NONE &&
244         ret != MFX_ERR_MORE_DATA &&
245         ret != MFX_WRN_VIDEO_PARAM_CHANGED &&
246         ret != MFX_ERR_MORE_SURFACE) {
247         av_log(avctx, AV_LOG_ERROR, "Error during QSV decoding.\n");
248         return ff_qsv_error(ret);
249     }
250
251     /* make sure we do not enter an infinite loop if the SDK
252      * did not consume any data and did not return anything */
253     if (!sync && !bs.DataOffset) {
254         av_log(avctx, AV_LOG_WARNING, "A decode call did not consume any data\n");
255         bs.DataOffset = avpkt->size;
256     }
257
258     if (sync) {
259         QSVFrame *out_frame = find_frame(q, outsurf);
260
261         if (!out_frame) {
262             av_log(avctx, AV_LOG_ERROR,
263                    "The returned surface does not correspond to any frame\n");
264             return AVERROR_BUG;
265         }
266
267         out_frame->queued = 1;
268         av_fifo_generic_write(q->async_fifo, &out_frame, sizeof(out_frame), NULL);
269         av_fifo_generic_write(q->async_fifo, &sync,      sizeof(sync),      NULL);
270     }
271
272     if (!av_fifo_space(q->async_fifo) ||
273         (!avpkt->size && av_fifo_size(q->async_fifo))) {
274         AVFrame *src_frame;
275
276         av_fifo_generic_read(q->async_fifo, &out_frame, sizeof(out_frame), NULL);
277         av_fifo_generic_read(q->async_fifo, &sync,      sizeof(sync),      NULL);
278         out_frame->queued = 0;
279
280         MFXVideoCORE_SyncOperation(q->session, sync, 60000);
281
282         src_frame = out_frame->frame;
283
284         ret = av_frame_ref(frame, src_frame);
285         if (ret < 0)
286             return ret;
287
288         outsurf = out_frame->surface;
289
290         frame->pkt_pts = frame->pts = outsurf->Data.TimeStamp;
291
292         frame->repeat_pict =
293             outsurf->Info.PicStruct & MFX_PICSTRUCT_FRAME_TRIPLING ? 4 :
294             outsurf->Info.PicStruct & MFX_PICSTRUCT_FRAME_DOUBLING ? 2 :
295             outsurf->Info.PicStruct & MFX_PICSTRUCT_FIELD_REPEATED ? 1 : 0;
296         frame->top_field_first =
297             outsurf->Info.PicStruct & MFX_PICSTRUCT_FIELD_TFF;
298         frame->interlaced_frame =
299             !(outsurf->Info.PicStruct & MFX_PICSTRUCT_PROGRESSIVE);
300
301         *got_frame = 1;
302     }
303
304     return bs.DataOffset;
305 }
306
307 int ff_qsv_decode_close(QSVContext *q)
308 {
309     QSVFrame *cur = q->work_frames;
310
311     while (cur) {
312         q->work_frames = cur->next;
313         av_frame_free(&cur->frame);
314         av_freep(&cur);
315         cur = q->work_frames;
316     }
317
318     av_fifo_free(q->async_fifo);
319     q->async_fifo = NULL;
320
321     av_parser_close(q->parser);
322     avcodec_free_context(&q->avctx_internal);
323
324     if (q->internal_session)
325         MFXClose(q->internal_session);
326
327     return 0;
328 }
329
330 int ff_qsv_process_data(AVCodecContext *avctx, QSVContext *q,
331                         AVFrame *frame, int *got_frame, AVPacket *pkt)
332 {
333     uint8_t *dummy_data;
334     int dummy_size;
335     int ret;
336
337     if (!q->avctx_internal) {
338         q->avctx_internal = avcodec_alloc_context3(NULL);
339         if (!q->avctx_internal)
340             return AVERROR(ENOMEM);
341
342         if (avctx->extradata) {
343             q->avctx_internal->extradata = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
344             if (!q->avctx_internal->extradata)
345                 return AVERROR(ENOMEM);
346
347             memcpy(q->avctx_internal->extradata, avctx->extradata,
348                    avctx->extradata_size);
349             q->avctx_internal->extradata_size = avctx->extradata_size;
350         }
351
352         q->parser = av_parser_init(avctx->codec_id);
353         if (!q->parser)
354             return AVERROR(ENOMEM);
355
356         q->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
357         q->orig_pix_fmt   = AV_PIX_FMT_NONE;
358     }
359
360     if (!pkt->size)
361         return qsv_decode(avctx, q, frame, got_frame, pkt);
362
363     /* we assume the packets are already split properly and want
364      * just the codec parameters here */
365     av_parser_parse2(q->parser, q->avctx_internal,
366                      &dummy_data, &dummy_size,
367                      pkt->data, pkt->size, pkt->pts, pkt->dts,
368                      pkt->pos);
369
370     /* TODO: flush delayed frames on reinit */
371     if (q->parser->format       != q->orig_pix_fmt    ||
372         q->parser->coded_width  != avctx->coded_width ||
373         q->parser->coded_height != avctx->coded_height) {
374         mfxSession session = NULL;
375
376         enum AVPixelFormat pix_fmts[3] = { AV_PIX_FMT_QSV,
377                                            AV_PIX_FMT_NONE,
378                                            AV_PIX_FMT_NONE };
379         enum AVPixelFormat qsv_format;
380
381         qsv_format = ff_qsv_map_pixfmt(q->parser->format);
382         if (qsv_format < 0) {
383             av_log(avctx, AV_LOG_ERROR,
384                    "Only 8-bit YUV420 streams are supported.\n");
385             ret = AVERROR(ENOSYS);
386             goto reinit_fail;
387         }
388
389         q->orig_pix_fmt     = q->parser->format;
390         avctx->pix_fmt      = pix_fmts[1] = qsv_format;
391         avctx->width        = q->parser->width;
392         avctx->height       = q->parser->height;
393         avctx->coded_width  = q->parser->coded_width;
394         avctx->coded_height = q->parser->coded_height;
395         avctx->level        = q->avctx_internal->level;
396         avctx->profile      = q->avctx_internal->profile;
397
398         ret = ff_get_format(avctx, pix_fmts);
399         if (ret < 0)
400             goto reinit_fail;
401
402         avctx->pix_fmt = ret;
403
404         if (avctx->hwaccel_context) {
405             AVQSVContext *user_ctx = avctx->hwaccel_context;
406             session           = user_ctx->session;
407             q->iopattern      = user_ctx->iopattern;
408             q->ext_buffers    = user_ctx->ext_buffers;
409             q->nb_ext_buffers = user_ctx->nb_ext_buffers;
410         }
411
412         ret = ff_qsv_decode_init(avctx, q, session);
413         if (ret < 0)
414             goto reinit_fail;
415     }
416
417     return qsv_decode(avctx, q, frame, got_frame, pkt);
418
419 reinit_fail:
420     q->orig_pix_fmt = q->parser->format = avctx->pix_fmt = AV_PIX_FMT_NONE;
421     return ret;
422 }
423
424 void ff_qsv_decode_flush(AVCodecContext *avctx, QSVContext *q)
425 {
426     q->orig_pix_fmt = AV_PIX_FMT_NONE;
427 }