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