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