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