]> git.sesse.net Git - ffmpeg/blob - libavcodec/qsvdec.c
lavc: export the timestamps when decoding in AVFrame.pts
[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/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 = avctx->profile;
148     param.mfx.CodecLevel   = 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     param.IOPattern   = q->iopattern;
159     param.AsyncDepth  = q->async_depth;
160     param.ExtParam    = q->ext_buffers;
161     param.NumExtParam = q->nb_ext_buffers;
162
163     ret = MFXVideoDECODE_Init(q->session, &param);
164     if (ret < 0) {
165         av_log(avctx, AV_LOG_ERROR, "Error initializing the MFX video decoder\n");
166         return ff_qsv_error(ret);
167     }
168
169     return 0;
170 }
171
172 static int alloc_frame(AVCodecContext *avctx, QSVFrame *frame)
173 {
174     int ret;
175
176     ret = ff_get_buffer(avctx, frame->frame, AV_GET_BUFFER_FLAG_REF);
177     if (ret < 0)
178         return ret;
179
180     if (frame->frame->format == AV_PIX_FMT_QSV) {
181         frame->surface = (mfxFrameSurface1*)frame->frame->data[3];
182     } else {
183         frame->surface_internal.Info.BitDepthLuma   = 8;
184         frame->surface_internal.Info.BitDepthChroma = 8;
185         frame->surface_internal.Info.FourCC         = MFX_FOURCC_NV12;
186         frame->surface_internal.Info.Width          = avctx->coded_width;
187         frame->surface_internal.Info.Height         = avctx->coded_height;
188         frame->surface_internal.Info.ChromaFormat   = MFX_CHROMAFORMAT_YUV420;
189
190         frame->surface_internal.Data.PitchLow = frame->frame->linesize[0];
191         frame->surface_internal.Data.Y        = frame->frame->data[0];
192         frame->surface_internal.Data.UV       = frame->frame->data[1];
193
194         frame->surface = &frame->surface_internal;
195     }
196
197     return 0;
198 }
199
200 static void qsv_clear_unused_frames(QSVContext *q)
201 {
202     QSVFrame *cur = q->work_frames;
203     while (cur) {
204         if (cur->surface && !cur->surface->Data.Locked && !cur->queued) {
205             cur->surface = NULL;
206             av_frame_unref(cur->frame);
207         }
208         cur = cur->next;
209     }
210 }
211
212 static int get_surface(AVCodecContext *avctx, QSVContext *q, mfxFrameSurface1 **surf)
213 {
214     QSVFrame *frame, **last;
215     int ret;
216
217     qsv_clear_unused_frames(q);
218
219     frame = q->work_frames;
220     last  = &q->work_frames;
221     while (frame) {
222         if (!frame->surface) {
223             ret = alloc_frame(avctx, frame);
224             if (ret < 0)
225                 return ret;
226             *surf = frame->surface;
227             return 0;
228         }
229
230         last  = &frame->next;
231         frame = frame->next;
232     }
233
234     frame = av_mallocz(sizeof(*frame));
235     if (!frame)
236         return AVERROR(ENOMEM);
237     frame->frame = av_frame_alloc();
238     if (!frame->frame) {
239         av_freep(&frame);
240         return AVERROR(ENOMEM);
241     }
242     *last = frame;
243
244     ret = alloc_frame(avctx, frame);
245     if (ret < 0)
246         return ret;
247
248     *surf = frame->surface;
249
250     return 0;
251 }
252
253 static QSVFrame *find_frame(QSVContext *q, mfxFrameSurface1 *surf)
254 {
255     QSVFrame *cur = q->work_frames;
256     while (cur) {
257         if (surf == cur->surface)
258             return cur;
259         cur = cur->next;
260     }
261     return NULL;
262 }
263
264 static int qsv_decode(AVCodecContext *avctx, QSVContext *q,
265                       AVFrame *frame, int *got_frame,
266                       AVPacket *avpkt)
267 {
268     QSVFrame *out_frame;
269     mfxFrameSurface1 *insurf;
270     mfxFrameSurface1 *outsurf;
271     mfxSyncPoint *sync;
272     mfxBitstream bs = { { { 0 } } };
273     int ret;
274
275     if (avpkt->size) {
276         bs.Data       = avpkt->data;
277         bs.DataLength = avpkt->size;
278         bs.MaxLength  = bs.DataLength;
279         bs.TimeStamp  = avpkt->pts;
280     }
281
282     sync = av_mallocz(sizeof(*sync));
283     if (!sync) {
284         av_freep(&sync);
285         return AVERROR(ENOMEM);
286     }
287
288     do {
289         ret = get_surface(avctx, q, &insurf);
290         if (ret < 0)
291             return ret;
292
293         ret = MFXVideoDECODE_DecodeFrameAsync(q->session, avpkt->size ? &bs : NULL,
294                                               insurf, &outsurf, sync);
295         if (ret == MFX_WRN_DEVICE_BUSY)
296             av_usleep(1);
297
298     } while (ret == MFX_WRN_DEVICE_BUSY || ret == MFX_ERR_MORE_SURFACE);
299
300     if (ret != MFX_ERR_NONE &&
301         ret != MFX_ERR_MORE_DATA &&
302         ret != MFX_WRN_VIDEO_PARAM_CHANGED &&
303         ret != MFX_ERR_MORE_SURFACE) {
304         av_log(avctx, AV_LOG_ERROR, "Error during QSV decoding.\n");
305         av_freep(&sync);
306         return ff_qsv_error(ret);
307     }
308
309     /* make sure we do not enter an infinite loop if the SDK
310      * did not consume any data and did not return anything */
311     if (!*sync && !bs.DataOffset) {
312         av_log(avctx, AV_LOG_WARNING, "A decode call did not consume any data\n");
313         bs.DataOffset = avpkt->size;
314     }
315
316     if (*sync) {
317         QSVFrame *out_frame = find_frame(q, outsurf);
318
319         if (!out_frame) {
320             av_log(avctx, AV_LOG_ERROR,
321                    "The returned surface does not correspond to any frame\n");
322             av_freep(&sync);
323             return AVERROR_BUG;
324         }
325
326         out_frame->queued = 1;
327         av_fifo_generic_write(q->async_fifo, &out_frame, sizeof(out_frame), NULL);
328         av_fifo_generic_write(q->async_fifo, &sync,      sizeof(sync),      NULL);
329     } else {
330         av_freep(&sync);
331     }
332
333     if (!av_fifo_space(q->async_fifo) ||
334         (!avpkt->size && av_fifo_size(q->async_fifo))) {
335         AVFrame *src_frame;
336
337         av_fifo_generic_read(q->async_fifo, &out_frame, sizeof(out_frame), NULL);
338         av_fifo_generic_read(q->async_fifo, &sync,      sizeof(sync),      NULL);
339         out_frame->queued = 0;
340
341         do {
342             ret = MFXVideoCORE_SyncOperation(q->session, *sync, 1000);
343         } while (ret == MFX_WRN_IN_EXECUTION);
344
345         av_freep(&sync);
346
347         src_frame = out_frame->frame;
348
349         ret = av_frame_ref(frame, src_frame);
350         if (ret < 0)
351             return ret;
352
353         outsurf = out_frame->surface;
354
355 #if FF_API_PKT_PTS
356 FF_DISABLE_DEPRECATION_WARNINGS
357         frame->pkt_pts = outsurf->Data.TimeStamp;
358 FF_ENABLE_DEPRECATION_WARNINGS
359 #endif
360         frame->pts = outsurf->Data.TimeStamp;
361
362         frame->repeat_pict =
363             outsurf->Info.PicStruct & MFX_PICSTRUCT_FRAME_TRIPLING ? 4 :
364             outsurf->Info.PicStruct & MFX_PICSTRUCT_FRAME_DOUBLING ? 2 :
365             outsurf->Info.PicStruct & MFX_PICSTRUCT_FIELD_REPEATED ? 1 : 0;
366         frame->top_field_first =
367             outsurf->Info.PicStruct & MFX_PICSTRUCT_FIELD_TFF;
368         frame->interlaced_frame =
369             !(outsurf->Info.PicStruct & MFX_PICSTRUCT_PROGRESSIVE);
370
371         *got_frame = 1;
372     }
373
374     return bs.DataOffset;
375 }
376
377 int ff_qsv_decode_close(QSVContext *q)
378 {
379     QSVFrame *cur = q->work_frames;
380
381     if (q->session)
382         MFXVideoDECODE_Close(q->session);
383
384     while (q->async_fifo && av_fifo_size(q->async_fifo)) {
385         QSVFrame *out_frame;
386         mfxSyncPoint *sync;
387
388         av_fifo_generic_read(q->async_fifo, &out_frame, sizeof(out_frame), NULL);
389         av_fifo_generic_read(q->async_fifo, &sync,      sizeof(sync),      NULL);
390
391         av_freep(&sync);
392     }
393
394     while (cur) {
395         q->work_frames = cur->next;
396         av_frame_free(&cur->frame);
397         av_freep(&cur);
398         cur = q->work_frames;
399     }
400
401     av_fifo_free(q->async_fifo);
402     q->async_fifo = NULL;
403
404     av_parser_close(q->parser);
405     avcodec_free_context(&q->avctx_internal);
406
407     if (q->internal_session)
408         MFXClose(q->internal_session);
409
410     av_buffer_unref(&q->frames_ctx.hw_frames_ctx);
411     av_freep(&q->frames_ctx.mids);
412     q->frames_ctx.nb_mids = 0;
413
414     return 0;
415 }
416
417 int ff_qsv_process_data(AVCodecContext *avctx, QSVContext *q,
418                         AVFrame *frame, int *got_frame, AVPacket *pkt)
419 {
420     uint8_t *dummy_data;
421     int dummy_size;
422     int ret;
423
424     if (!q->avctx_internal) {
425         q->avctx_internal = avcodec_alloc_context3(NULL);
426         if (!q->avctx_internal)
427             return AVERROR(ENOMEM);
428
429         if (avctx->extradata) {
430             q->avctx_internal->extradata = av_mallocz(avctx->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);
431             if (!q->avctx_internal->extradata)
432                 return AVERROR(ENOMEM);
433
434             memcpy(q->avctx_internal->extradata, avctx->extradata,
435                    avctx->extradata_size);
436             q->avctx_internal->extradata_size = avctx->extradata_size;
437         }
438
439         q->parser = av_parser_init(avctx->codec_id);
440         if (!q->parser)
441             return AVERROR(ENOMEM);
442
443         q->parser->flags |= PARSER_FLAG_COMPLETE_FRAMES;
444         q->orig_pix_fmt   = AV_PIX_FMT_NONE;
445     }
446
447     if (!pkt->size)
448         return qsv_decode(avctx, q, frame, got_frame, pkt);
449
450     /* we assume the packets are already split properly and want
451      * just the codec parameters here */
452     av_parser_parse2(q->parser, q->avctx_internal,
453                      &dummy_data, &dummy_size,
454                      pkt->data, pkt->size, pkt->pts, pkt->dts,
455                      pkt->pos);
456
457     /* TODO: flush delayed frames on reinit */
458     if (q->parser->format       != q->orig_pix_fmt    ||
459         q->parser->coded_width  != avctx->coded_width ||
460         q->parser->coded_height != avctx->coded_height) {
461         enum AVPixelFormat pix_fmts[3] = { AV_PIX_FMT_QSV,
462                                            AV_PIX_FMT_NONE,
463                                            AV_PIX_FMT_NONE };
464         enum AVPixelFormat qsv_format;
465
466         qsv_format = ff_qsv_map_pixfmt(q->parser->format);
467         if (qsv_format < 0) {
468             av_log(avctx, AV_LOG_ERROR,
469                    "Only 8-bit YUV420 streams are supported.\n");
470             ret = AVERROR(ENOSYS);
471             goto reinit_fail;
472         }
473
474         q->orig_pix_fmt     = q->parser->format;
475         avctx->pix_fmt      = pix_fmts[1] = qsv_format;
476         avctx->width        = q->parser->width;
477         avctx->height       = q->parser->height;
478         avctx->coded_width  = q->parser->coded_width;
479         avctx->coded_height = q->parser->coded_height;
480         avctx->level        = q->avctx_internal->level;
481         avctx->profile      = q->avctx_internal->profile;
482
483         ret = ff_get_format(avctx, pix_fmts);
484         if (ret < 0)
485             goto reinit_fail;
486
487         avctx->pix_fmt = ret;
488
489         ret = qsv_decode_init(avctx, q);
490         if (ret < 0)
491             goto reinit_fail;
492     }
493
494     return qsv_decode(avctx, q, frame, got_frame, pkt);
495
496 reinit_fail:
497     q->orig_pix_fmt = q->parser->format = avctx->pix_fmt = AV_PIX_FMT_NONE;
498     return ret;
499 }
500
501 void ff_qsv_decode_flush(AVCodecContext *avctx, QSVContext *q)
502 {
503     q->orig_pix_fmt = AV_PIX_FMT_NONE;
504 }