]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_deinterlace_qsv.c
Merge commit 'a2fc8dbae85339d1b418d296f2982b6c04c53c57'
[ffmpeg] / libavfilter / vf_deinterlace_qsv.c
1 /*
2  * This file is part of FFmpeg.
3  *
4  * FFmpeg is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2.1 of the License, or (at your option) any later version.
8  *
9  * FFmpeg is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with FFmpeg; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17  */
18
19 /**
20  * @file
21  * deinterlace video filter - QSV
22  */
23
24 #include <mfx/mfxvideo.h>
25
26 #include <stdio.h>
27 #include <string.h>
28
29 #include "libavutil/avstring.h"
30 #include "libavutil/common.h"
31 #include "libavutil/hwcontext.h"
32 #include "libavutil/hwcontext_qsv.h"
33 #include "libavutil/internal.h"
34 #include "libavutil/mathematics.h"
35 #include "libavutil/opt.h"
36 #include "libavutil/pixdesc.h"
37 #include "libavutil/time.h"
38
39 #include "avfilter.h"
40 #include "formats.h"
41 #include "internal.h"
42 #include "video.h"
43
44 enum {
45     QSVDEINT_MORE_OUTPUT = 1,
46     QSVDEINT_MORE_INPUT,
47 };
48
49 typedef struct QSVFrame {
50     AVFrame *frame;
51     mfxFrameSurface1 surface;
52     int used;
53
54     struct QSVFrame *next;
55 } QSVFrame;
56
57 typedef struct QSVDeintContext {
58     const AVClass *class;
59
60     AVBufferRef *hw_frames_ctx;
61     /* a clone of the main session, used internally for deinterlacing */
62     mfxSession   session;
63
64     mfxMemId *mem_ids;
65     int    nb_mem_ids;
66
67     mfxFrameSurface1 **surface_ptrs;
68     int             nb_surface_ptrs;
69
70     mfxExtOpaqueSurfaceAlloc opaque_alloc;
71     mfxExtVPPDeinterlacing   deint_conf;
72     mfxExtBuffer            *ext_buffers[2];
73     int                      num_ext_buffers;
74
75     QSVFrame *work_frames;
76
77     int64_t last_pts;
78
79     int eof;
80
81     /* option for Deinterlacing algorithm to be used */
82     int mode;
83 } QSVDeintContext;
84
85 static void qsvdeint_uninit(AVFilterContext *ctx)
86 {
87     QSVDeintContext *s = ctx->priv;
88     QSVFrame *cur;
89
90     if (s->session) {
91         MFXClose(s->session);
92         s->session = NULL;
93     }
94     av_buffer_unref(&s->hw_frames_ctx);
95
96     cur = s->work_frames;
97     while (cur) {
98         s->work_frames = cur->next;
99         av_frame_free(&cur->frame);
100         av_freep(&cur);
101         cur = s->work_frames;
102     }
103
104     av_freep(&s->mem_ids);
105     s->nb_mem_ids = 0;
106
107     av_freep(&s->surface_ptrs);
108     s->nb_surface_ptrs = 0;
109 }
110
111 static int qsvdeint_query_formats(AVFilterContext *ctx)
112 {
113     static const enum AVPixelFormat pixel_formats[] = {
114         AV_PIX_FMT_QSV, AV_PIX_FMT_NONE,
115     };
116     AVFilterFormats *pix_fmts  = ff_make_format_list(pixel_formats);
117     int ret;
118
119     if ((ret = ff_set_common_formats(ctx, pix_fmts)) < 0)
120         return ret;
121
122     return 0;
123 }
124
125 static mfxStatus frame_alloc(mfxHDL pthis, mfxFrameAllocRequest *req,
126                              mfxFrameAllocResponse *resp)
127 {
128     AVFilterContext *ctx = pthis;
129     QSVDeintContext   *s = ctx->priv;
130
131     if (!(req->Type & MFX_MEMTYPE_VIDEO_MEMORY_PROCESSOR_TARGET) ||
132         !(req->Type & (MFX_MEMTYPE_FROM_VPPIN | MFX_MEMTYPE_FROM_VPPOUT)) ||
133         !(req->Type & MFX_MEMTYPE_EXTERNAL_FRAME))
134         return MFX_ERR_UNSUPPORTED;
135
136     resp->mids           = s->mem_ids;
137     resp->NumFrameActual = s->nb_mem_ids;
138
139     return MFX_ERR_NONE;
140 }
141
142 static mfxStatus frame_free(mfxHDL pthis, mfxFrameAllocResponse *resp)
143 {
144     return MFX_ERR_NONE;
145 }
146
147 static mfxStatus frame_lock(mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr)
148 {
149     return MFX_ERR_UNSUPPORTED;
150 }
151
152 static mfxStatus frame_unlock(mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr)
153 {
154     return MFX_ERR_UNSUPPORTED;
155 }
156
157 static mfxStatus frame_get_hdl(mfxHDL pthis, mfxMemId mid, mfxHDL *hdl)
158 {
159     *hdl = mid;
160     return MFX_ERR_NONE;
161 }
162
163 static const mfxHandleType handle_types[] = {
164     MFX_HANDLE_VA_DISPLAY,
165     MFX_HANDLE_D3D9_DEVICE_MANAGER,
166     MFX_HANDLE_D3D11_DEVICE,
167 };
168
169 static int init_out_session(AVFilterContext *ctx)
170 {
171
172     QSVDeintContext                  *s = ctx->priv;
173     AVHWFramesContext    *hw_frames_ctx = (AVHWFramesContext*)s->hw_frames_ctx->data;
174     AVQSVFramesContext *hw_frames_hwctx = hw_frames_ctx->hwctx;
175     AVQSVDeviceContext    *device_hwctx = hw_frames_ctx->device_ctx->hwctx;
176
177     int opaque = !!(hw_frames_hwctx->frame_type & MFX_MEMTYPE_OPAQUE_FRAME);
178
179     mfxHDL handle = NULL;
180     mfxHandleType handle_type;
181     mfxVersion ver;
182     mfxIMPL impl;
183     mfxVideoParam par;
184     mfxStatus err;
185     int i;
186
187     /* extract the properties of the "master" session given to us */
188     err = MFXQueryIMPL(device_hwctx->session, &impl);
189     if (err == MFX_ERR_NONE)
190         err = MFXQueryVersion(device_hwctx->session, &ver);
191     if (err != MFX_ERR_NONE) {
192         av_log(ctx, AV_LOG_ERROR, "Error querying the session attributes\n");
193         return AVERROR_UNKNOWN;
194     }
195
196     for (i = 0; i < FF_ARRAY_ELEMS(handle_types); i++) {
197         err = MFXVideoCORE_GetHandle(device_hwctx->session, handle_types[i], &handle);
198         if (err == MFX_ERR_NONE) {
199             handle_type = handle_types[i];
200             break;
201         }
202     }
203
204     /* create a "slave" session with those same properties, to be used for
205      * actual deinterlacing */
206     err = MFXInit(impl, &ver, &s->session);
207     if (err != MFX_ERR_NONE) {
208         av_log(ctx, AV_LOG_ERROR, "Error initializing a session for deinterlacing\n");
209         return AVERROR_UNKNOWN;
210     }
211
212     if (handle) {
213         err = MFXVideoCORE_SetHandle(s->session, handle_type, handle);
214         if (err != MFX_ERR_NONE)
215             return AVERROR_UNKNOWN;
216     }
217
218     memset(&par, 0, sizeof(par));
219
220     s->deint_conf.Header.BufferId = MFX_EXTBUFF_VPP_DEINTERLACING;
221     s->deint_conf.Header.BufferSz = sizeof(s->deint_conf);
222     s->deint_conf.Mode = s->mode;
223
224     s->ext_buffers[s->num_ext_buffers++] = (mfxExtBuffer *)&s->deint_conf;
225
226     if (opaque) {
227         s->surface_ptrs = av_mallocz_array(hw_frames_hwctx->nb_surfaces,
228                                            sizeof(*s->surface_ptrs));
229         if (!s->surface_ptrs)
230             return AVERROR(ENOMEM);
231         for (i = 0; i < hw_frames_hwctx->nb_surfaces; i++)
232             s->surface_ptrs[i] = hw_frames_hwctx->surfaces + i;
233         s->nb_surface_ptrs = hw_frames_hwctx->nb_surfaces;
234
235         s->opaque_alloc.In.Surfaces   = s->surface_ptrs;
236         s->opaque_alloc.In.NumSurface = s->nb_surface_ptrs;
237         s->opaque_alloc.In.Type       = hw_frames_hwctx->frame_type;
238
239         s->opaque_alloc.Out = s->opaque_alloc.In;
240
241         s->opaque_alloc.Header.BufferId = MFX_EXTBUFF_OPAQUE_SURFACE_ALLOCATION;
242         s->opaque_alloc.Header.BufferSz = sizeof(s->opaque_alloc);
243
244         s->ext_buffers[s->num_ext_buffers++] = (mfxExtBuffer *)&s->opaque_alloc;
245
246         par.IOPattern = MFX_IOPATTERN_IN_OPAQUE_MEMORY | MFX_IOPATTERN_OUT_OPAQUE_MEMORY;
247     } else {
248         mfxFrameAllocator frame_allocator = {
249             .pthis  = ctx,
250             .Alloc  = frame_alloc,
251             .Lock   = frame_lock,
252             .Unlock = frame_unlock,
253             .GetHDL = frame_get_hdl,
254             .Free   = frame_free,
255         };
256
257         s->mem_ids = av_mallocz_array(hw_frames_hwctx->nb_surfaces,
258                                       sizeof(*s->mem_ids));
259         if (!s->mem_ids)
260             return AVERROR(ENOMEM);
261         for (i = 0; i < hw_frames_hwctx->nb_surfaces; i++)
262             s->mem_ids[i] = hw_frames_hwctx->surfaces[i].Data.MemId;
263         s->nb_mem_ids = hw_frames_hwctx->nb_surfaces;
264
265         err = MFXVideoCORE_SetFrameAllocator(s->session, &frame_allocator);
266         if (err != MFX_ERR_NONE)
267             return AVERROR_UNKNOWN;
268
269         par.IOPattern = MFX_IOPATTERN_IN_VIDEO_MEMORY | MFX_IOPATTERN_OUT_VIDEO_MEMORY;
270     }
271
272     par.ExtParam    = s->ext_buffers;
273     par.NumExtParam = s->num_ext_buffers;
274
275     par.AsyncDepth = 1;    // TODO async
276
277     par.vpp.In = hw_frames_hwctx->surfaces[0].Info;
278
279     par.vpp.In.CropW = ctx->inputs[0]->w;
280     par.vpp.In.CropH = ctx->inputs[0]->h;
281
282     if (ctx->inputs[0]->frame_rate.num) {
283         par.vpp.In.FrameRateExtN = ctx->inputs[0]->frame_rate.num;
284         par.vpp.In.FrameRateExtD = ctx->inputs[0]->frame_rate.den;
285     } else {
286         par.vpp.In.FrameRateExtN = ctx->inputs[0]->time_base.num;
287         par.vpp.In.FrameRateExtD = ctx->inputs[0]->time_base.den;
288     }
289
290     par.vpp.Out = par.vpp.In;
291
292     if (ctx->outputs[0]->frame_rate.num) {
293         par.vpp.Out.FrameRateExtN = ctx->outputs[0]->frame_rate.num;
294         par.vpp.Out.FrameRateExtD = ctx->outputs[0]->frame_rate.den;
295     } else {
296         par.vpp.Out.FrameRateExtN = ctx->outputs[0]->time_base.num;
297         par.vpp.Out.FrameRateExtD = ctx->outputs[0]->time_base.den;
298     }
299
300     err = MFXVideoVPP_Init(s->session, &par);
301     if (err != MFX_ERR_NONE) {
302         av_log(ctx, AV_LOG_ERROR, "Error opening the VPP for deinterlacing: %d\n", err);
303         return AVERROR_UNKNOWN;
304     }
305
306     return 0;
307 }
308
309 static int qsvdeint_config_props(AVFilterLink *outlink)
310 {
311     AVFilterContext *ctx = outlink->src;
312     AVFilterLink *inlink = ctx->inputs[0];
313     QSVDeintContext  *s = ctx->priv;
314     int ret;
315
316     qsvdeint_uninit(ctx);
317
318     s->last_pts = AV_NOPTS_VALUE;
319     outlink->frame_rate = av_mul_q(inlink->frame_rate,
320                                    (AVRational){ 2, 1 });
321     outlink->time_base  = av_mul_q(inlink->time_base,
322                                    (AVRational){ 1, 2 });
323
324     /* check that we have a hw context */
325     if (!inlink->hw_frames_ctx) {
326         av_log(ctx, AV_LOG_ERROR, "No hw context provided on input\n");
327         return AVERROR(EINVAL);
328     }
329
330     s->hw_frames_ctx = av_buffer_ref(inlink->hw_frames_ctx);
331     if (!s->hw_frames_ctx)
332         return AVERROR(ENOMEM);
333
334     av_buffer_unref(&outlink->hw_frames_ctx);
335     outlink->hw_frames_ctx = av_buffer_ref(inlink->hw_frames_ctx);
336     if (!outlink->hw_frames_ctx) {
337         qsvdeint_uninit(ctx);
338         return AVERROR(ENOMEM);
339     }
340
341     ret = init_out_session(ctx);
342     if (ret < 0)
343         return ret;
344
345
346     return 0;
347 }
348
349 static void clear_unused_frames(QSVDeintContext *s)
350 {
351     QSVFrame *cur = s->work_frames;
352     while (cur) {
353         if (!cur->surface.Data.Locked) {
354             av_frame_free(&cur->frame);
355             cur->used = 0;
356         }
357         cur = cur->next;
358     }
359 }
360
361 static int get_free_frame(QSVDeintContext *s, QSVFrame **f)
362 {
363     QSVFrame *frame, **last;
364
365     clear_unused_frames(s);
366
367     frame = s->work_frames;
368     last  = &s->work_frames;
369     while (frame) {
370         if (!frame->used) {
371             *f = frame;
372             return 0;
373         }
374
375         last  = &frame->next;
376         frame = frame->next;
377     }
378
379     frame = av_mallocz(sizeof(*frame));
380     if (!frame)
381         return AVERROR(ENOMEM);
382     *last = frame;
383     *f    = frame;
384
385     return 0;
386 }
387
388 static int submit_frame(AVFilterContext *ctx, AVFrame *frame,
389                         mfxFrameSurface1 **surface)
390 {
391     QSVDeintContext *s = ctx->priv;
392     QSVFrame *qf;
393     int ret;
394
395     ret = get_free_frame(s, &qf);
396     if (ret < 0)
397         return ret;
398
399     qf->frame = frame;
400
401     qf->surface = *(mfxFrameSurface1*)qf->frame->data[3];
402
403     qf->surface.Data.Locked = 0;
404     qf->surface.Info.CropW  = qf->frame->width;
405     qf->surface.Info.CropH  = qf->frame->height;
406
407     qf->surface.Info.PicStruct = !qf->frame->interlaced_frame ? MFX_PICSTRUCT_PROGRESSIVE :
408                                  (qf->frame->top_field_first ? MFX_PICSTRUCT_FIELD_TFF :
409                                                            MFX_PICSTRUCT_FIELD_BFF);
410     if (qf->frame->repeat_pict == 1)
411         qf->surface.Info.PicStruct |= MFX_PICSTRUCT_FIELD_REPEATED;
412     else if (qf->frame->repeat_pict == 2)
413         qf->surface.Info.PicStruct |= MFX_PICSTRUCT_FRAME_DOUBLING;
414     else if (qf->frame->repeat_pict == 4)
415         qf->surface.Info.PicStruct |= MFX_PICSTRUCT_FRAME_TRIPLING;
416
417     if (ctx->inputs[0]->frame_rate.num) {
418         qf->surface.Info.FrameRateExtN = ctx->inputs[0]->frame_rate.num;
419         qf->surface.Info.FrameRateExtD = ctx->inputs[0]->frame_rate.den;
420     } else {
421         qf->surface.Info.FrameRateExtN = ctx->inputs[0]->time_base.num;
422         qf->surface.Info.FrameRateExtD = ctx->inputs[0]->time_base.den;
423     }
424
425     qf->surface.Data.TimeStamp = av_rescale_q(qf->frame->pts,
426                                               ctx->inputs[0]->time_base,
427                                               (AVRational){1, 90000});
428
429     *surface = &qf->surface;
430     qf->used = 1;
431
432     return 0;
433 }
434
435 static int process_frame(AVFilterContext *ctx, const AVFrame *in,
436                          mfxFrameSurface1 *surf_in)
437 {
438     QSVDeintContext    *s = ctx->priv;
439     AVFilterLink  *inlink = ctx->inputs[0];
440     AVFilterLink *outlink = ctx->outputs[0];
441
442     AVFrame *out;
443     mfxFrameSurface1 *surf_out;
444     mfxSyncPoint sync = NULL;
445     mfxStatus err;
446     int ret, again = 0;
447
448     out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
449     if (!out) {
450         ret = AVERROR(ENOMEM);
451         goto fail;
452     }
453
454     surf_out = (mfxFrameSurface1*)out->data[3];
455     surf_out->Info.CropW     = outlink->w;
456     surf_out->Info.CropH     = outlink->h;
457     surf_out->Info.PicStruct = MFX_PICSTRUCT_PROGRESSIVE;
458
459     do {
460         err = MFXVideoVPP_RunFrameVPPAsync(s->session, surf_in, surf_out,
461                                            NULL, &sync);
462         if (err == MFX_WRN_DEVICE_BUSY)
463             av_usleep(1);
464     } while (err == MFX_WRN_DEVICE_BUSY);
465
466     if (err == MFX_ERR_MORE_DATA) {
467         av_frame_free(&out);
468         return QSVDEINT_MORE_INPUT;
469     }
470
471     if ((err < 0 && err != MFX_ERR_MORE_SURFACE) || !sync) {
472         av_log(ctx, AV_LOG_ERROR, "Error during deinterlacing: %d\n", err);
473         ret = AVERROR_UNKNOWN;
474         goto fail;
475     }
476     if (err == MFX_ERR_MORE_SURFACE)
477         again = 1;
478
479     do {
480         err = MFXVideoCORE_SyncOperation(s->session, sync, 1000);
481     } while (err == MFX_WRN_IN_EXECUTION);
482     if (err < 0) {
483         av_log(ctx, AV_LOG_ERROR, "Error synchronizing the operation: %d\n", err);
484         ret = AVERROR_UNKNOWN;
485         goto fail;
486     }
487
488     ret = av_frame_copy_props(out, in);
489     if (ret < 0)
490         goto fail;
491
492     out->width            = outlink->w;
493     out->height           = outlink->h;
494     out->interlaced_frame = 0;
495
496     out->pts = av_rescale_q(out->pts, inlink->time_base, outlink->time_base);
497     if (out->pts == s->last_pts)
498         out->pts++;
499     s->last_pts = out->pts;
500
501     ret = ff_filter_frame(outlink, out);
502     if (ret < 0)
503         return ret;
504
505     return again ? QSVDEINT_MORE_OUTPUT : 0;
506 fail:
507     av_frame_free(&out);
508     return ret;
509 }
510
511 static int qsvdeint_filter_frame(AVFilterLink *link, AVFrame *in)
512 {
513     AVFilterContext *ctx = link->dst;
514
515     mfxFrameSurface1 *surf_in;
516     int ret;
517
518     ret = submit_frame(ctx, in, &surf_in);
519     if (ret < 0) {
520         av_frame_free(&in);
521         return ret;
522     }
523
524     do {
525         ret = process_frame(ctx, in, surf_in);
526         if (ret < 0)
527             return ret;
528     } while (ret == QSVDEINT_MORE_OUTPUT);
529
530     return 0;
531 }
532
533 static int qsvdeint_request_frame(AVFilterLink *outlink)
534 {
535     AVFilterContext *ctx = outlink->src;
536
537     return ff_request_frame(ctx->inputs[0]);
538 }
539
540 #define OFFSET(x) offsetof(QSVDeintContext, x)
541 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
542 static const AVOption options[] = {
543     { "mode", "set deinterlace mode", OFFSET(mode),   AV_OPT_TYPE_INT, {.i64 = MFX_DEINTERLACING_ADVANCED}, MFX_DEINTERLACING_BOB, MFX_DEINTERLACING_ADVANCED, FLAGS, "mode"},
544     { "bob",   "bob algorithm",                  0, AV_OPT_TYPE_CONST,      {.i64 = MFX_DEINTERLACING_BOB}, MFX_DEINTERLACING_BOB, MFX_DEINTERLACING_ADVANCED, FLAGS, "mode"},
545     { "advanced", "Motion adaptive algorithm",   0, AV_OPT_TYPE_CONST, {.i64 = MFX_DEINTERLACING_ADVANCED}, MFX_DEINTERLACING_BOB, MFX_DEINTERLACING_ADVANCED, FLAGS, "mode"},
546     { NULL },
547 };
548
549 static const AVClass qsvdeint_class = {
550     .class_name = "deinterlace_qsv",
551     .item_name  = av_default_item_name,
552     .option     = options,
553     .version    = LIBAVUTIL_VERSION_INT,
554 };
555
556 static const AVFilterPad qsvdeint_inputs[] = {
557     {
558         .name         = "default",
559         .type         = AVMEDIA_TYPE_VIDEO,
560         .filter_frame = qsvdeint_filter_frame,
561     },
562     { NULL }
563 };
564
565 static const AVFilterPad qsvdeint_outputs[] = {
566     {
567         .name          = "default",
568         .type          = AVMEDIA_TYPE_VIDEO,
569         .config_props  = qsvdeint_config_props,
570         .request_frame = qsvdeint_request_frame,
571     },
572     { NULL }
573 };
574
575 AVFilter ff_vf_deinterlace_qsv = {
576     .name      = "deinterlace_qsv",
577     .description = NULL_IF_CONFIG_SMALL("QuickSync video deinterlacing"),
578
579     .uninit        = qsvdeint_uninit,
580     .query_formats = qsvdeint_query_formats,
581
582     .priv_size = sizeof(QSVDeintContext),
583     .priv_class = &qsvdeint_class,
584
585     .inputs    = qsvdeint_inputs,
586     .outputs   = qsvdeint_outputs,
587
588     .flags_internal = FF_FILTER_FLAG_HWFRAME_AWARE,
589 };