]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_estdif.c
avfilter: add estdif video filter
[ffmpeg] / libavfilter / vf_estdif.c
1 /*
2  * Copyright (c) 2021 Paul B Mahol
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 #include "libavutil/common.h"
22 #include "libavutil/imgutils.h"
23 #include "libavutil/opt.h"
24 #include "libavutil/pixdesc.h"
25 #include "avfilter.h"
26 #include "formats.h"
27 #include "internal.h"
28 #include "video.h"
29
30 typedef struct ESTDIFContext {
31     const AVClass *class;
32
33     int mode;             ///< 0 is frame, 1 is field
34     int parity;           ///< frame field parity
35     int deint;            ///< which frames to deinterlace
36     int rslope;           ///< best edge slope search radius
37     int redge;            ///< best edge match search radius
38     int linesize[4];      ///< bytes of pixel data per line for each plane
39     int planewidth[4];    ///< width of each plane
40     int planeheight[4];   ///< height of each plane
41     int field;            ///< which field are we on, 0 or 1
42     int eof;
43     int depth;
44     int half;
45     int nb_planes;
46     int nb_threads;
47     int64_t pts;
48     AVFrame *prev;
49
50     void (*interpolate)(uint8_t *dst,
51                         const uint8_t *prev_line, const uint8_t *next_line,
52                         const uint8_t *prev2_line, const uint8_t *next2_line,
53                         int x, int width, int rslope, int redge, unsigned half,
54                         int depth, int *K);
55 } ESTDIFContext;
56
57 #define MAX_R 15
58 #define S     (MAX_R * 2 + 1)
59
60 #define OFFSET(x) offsetof(ESTDIFContext, x)
61 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_RUNTIME_PARAM
62 #define CONST(name, help, val, unit) { name, help, 0, AV_OPT_TYPE_CONST, {.i64=val}, 0, 0, FLAGS, unit }
63
64 static const AVOption estdif_options[] = {
65     { "mode", "specify the mode", OFFSET(mode), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, FLAGS, "mode" },
66     CONST("frame", "send one frame for each frame", 0, "mode"),
67     CONST("field", "send one frame for each field", 1, "mode"),
68     { "parity", "specify the assumed picture field parity", OFFSET(parity), AV_OPT_TYPE_INT, {.i64=-1}, -1, 1, FLAGS, "parity" },
69     CONST("tff",  "assume top field first",    0, "parity"),
70     CONST("bff",  "assume bottom field first", 1, "parity"),
71     CONST("auto", "auto detect parity",       -1, "parity"),
72     { "deint",  "specify which frames to deinterlace", OFFSET(deint), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, FLAGS, "deint" },
73     CONST("all",        "deinterlace all frames",                       0, "deint"),
74     CONST("interlaced", "only deinterlace frames marked as interlaced", 1, "deint"),
75     { "rslope", "specify the search radius for edge slope tracing", OFFSET(rslope), AV_OPT_TYPE_INT, {.i64=1}, 1, MAX_R, FLAGS, },
76     { "redge",  "specify the search radius for best edge matching", OFFSET(redge),  AV_OPT_TYPE_INT, {.i64=2}, 0, MAX_R, FLAGS, },
77     { NULL }
78 };
79
80 AVFILTER_DEFINE_CLASS(estdif);
81
82 static int query_formats(AVFilterContext *ctx)
83 {
84     static const enum AVPixelFormat pix_fmts[] = {
85         AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV411P,
86         AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P,
87         AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUV444P,
88         AV_PIX_FMT_YUVJ444P, AV_PIX_FMT_YUVJ440P,
89         AV_PIX_FMT_YUVJ422P, AV_PIX_FMT_YUVJ420P,
90         AV_PIX_FMT_YUVJ411P,
91         AV_PIX_FMT_YUVA420P, AV_PIX_FMT_YUVA422P, AV_PIX_FMT_YUVA444P,
92         AV_PIX_FMT_GBRP, AV_PIX_FMT_GBRAP,
93         AV_PIX_FMT_GRAY8,
94         AV_PIX_FMT_GRAY9, AV_PIX_FMT_GRAY10, AV_PIX_FMT_GRAY12, AV_PIX_FMT_GRAY14, AV_PIX_FMT_GRAY16,
95         AV_PIX_FMT_YUV420P9, AV_PIX_FMT_YUV422P9, AV_PIX_FMT_YUV444P9,
96         AV_PIX_FMT_YUV420P10, AV_PIX_FMT_YUV422P10, AV_PIX_FMT_YUV444P10,
97         AV_PIX_FMT_YUV420P12, AV_PIX_FMT_YUV422P12, AV_PIX_FMT_YUV444P12,
98         AV_PIX_FMT_YUV420P14, AV_PIX_FMT_YUV422P14, AV_PIX_FMT_YUV444P14,
99         AV_PIX_FMT_GBRP9, AV_PIX_FMT_GBRP10, AV_PIX_FMT_GBRP12, AV_PIX_FMT_GBRP14,
100         AV_PIX_FMT_YUVA444P9, AV_PIX_FMT_YUVA444P10, AV_PIX_FMT_YUVA444P12, AV_PIX_FMT_YUVA444P16,
101         AV_PIX_FMT_YUVA422P9, AV_PIX_FMT_YUVA422P10, AV_PIX_FMT_YUVA422P12, AV_PIX_FMT_YUVA422P16,
102         AV_PIX_FMT_YUVA420P9, AV_PIX_FMT_YUVA420P10, AV_PIX_FMT_YUVA420P16,
103         AV_PIX_FMT_GBRAP10,   AV_PIX_FMT_GBRAP12,    AV_PIX_FMT_GBRAP16,
104         AV_PIX_FMT_NONE
105     };
106
107     AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
108     if (!fmts_list)
109         return AVERROR(ENOMEM);
110     return ff_set_common_formats(ctx, fmts_list);
111 }
112
113 static int config_output(AVFilterLink *outlink)
114 {
115     AVFilterContext *ctx = outlink->src;
116     AVFilterLink *inlink = ctx->inputs[0];
117
118     outlink->time_base.num = inlink->time_base.num;
119     outlink->time_base.den = inlink->time_base.den * 2;
120     outlink->frame_rate.num = inlink->frame_rate.num * 2;
121     outlink->frame_rate.den = inlink->frame_rate.den;
122
123     return 0;
124 }
125
126 typedef struct ThreadData {
127     AVFrame *out, *in;
128 } ThreadData;
129
130 #define MIDL(type, ss)                                         \
131 static unsigned midl_##ss(const type *const prev,              \
132                           const type *const next,              \
133                           int end, int x, int k)               \
134 {                                                              \
135     return (prev[av_clip(x + k, 0, end)] +                     \
136             next[av_clip(x - k, 0, end)] + 1) >> 1;            \
137 }
138
139 MIDL(uint8_t, 8)
140 MIDL(uint16_t, 16)
141
142 #define MID4(type, ss)                                         \
143 static unsigned mid4_##ss(const type *const prev,              \
144                           const type *const next,              \
145                           const type *const prev2,             \
146                           const type *const next2,             \
147                           int end, int x, int k, int depth)    \
148 {                                                              \
149     return av_clip_uintp2_c((                                  \
150             9 * (prev[av_clip(x + k, 0, end)] +                \
151                  next[av_clip(x - k, 0, end)]) -               \
152             1 * (prev2[av_clip(x + k*3, 0, end)] +             \
153                  next2[av_clip(x - k*3, 0, end)]) + 8) >> 4,   \
154                  depth);                                       \
155 }
156
157 MID4(uint8_t, 8)
158 MID4(uint16_t, 16)
159
160 #define DIFF(type, ss)                                         \
161 static unsigned diff_##ss(const type *const prev,              \
162                           const type *const next,              \
163                           int end, int x, int k, int j)        \
164 {                                                              \
165     return FFABS(prev[av_clip(x + k + j, 0, end)] -            \
166                  next[av_clip(x - k + j, 0, end)]);            \
167 }
168
169 DIFF(uint8_t, 8)
170 DIFF(uint16_t, 16)
171
172 #define COST(type, ss)                                         \
173 static unsigned cost_##ss(const type *const prev,              \
174                           const type *const next,              \
175                           int end, int x, int k)               \
176 {                                                              \
177     const int m = midl_##ss(prev, next, end, x, k);            \
178     const int p = prev[x];                                     \
179     const int n = next[x];                                     \
180                                                                \
181     return FFABS(p - m) + FFABS(n - m);                        \
182 }
183
184 COST(uint8_t, 8)
185 COST(uint16_t, 16)
186
187 #define INTERPOLATE(type, atype, max, ss)                                      \
188 static void interpolate_##ss(uint8_t *ddst,                                    \
189                              const uint8_t *const pprev_line,                  \
190                              const uint8_t *const nnext_line,                  \
191                              const uint8_t *const pprev2_line,                 \
192                              const uint8_t *const nnext2_line,                 \
193                              int x, int width, int rslope,                     \
194                              int redge, unsigned h, int depth,                 \
195                              int *K)                                           \
196 {                                                                              \
197     type *dst = (type *)ddst;                                                  \
198     const type *const prev_line = (const type *const)pprev_line;               \
199     const type *const prev2_line = (const type *const)pprev2_line;             \
200     const type *const next_line = (const type *const)nnext_line;               \
201     const type *const next2_line = (const type *const)nnext2_line;             \
202     const int end = width - 1;                                                 \
203     const atype f = redge + 2;                                                 \
204     atype sd[S], sD[S], di = 0;                                                \
205     atype dmin = max;                                                          \
206     int k = *K;                                                                \
207                                                                                \
208     for (int i = -rslope; i <= rslope && abs(k) > rslope; i++) {               \
209         atype sum = 0;                                                         \
210                                                                                \
211         for (int j = -redge; j <= redge; j++) {                                \
212             sum += diff_##ss(prev_line,  next_line,  end, x, i, j);            \
213             sum += diff_##ss(prev2_line, prev_line,  end, x, i, j);            \
214             sum += diff_##ss(next_line,  next2_line, end, x, i, j);            \
215         }                                                                      \
216                                                                                \
217         sD[i + rslope]  =     sum;                                             \
218         sD[i + rslope] += f * cost_##ss(prev_line,  next_line,  end, x, i);    \
219         sD[i + rslope] += h * abs(i);                                          \
220                                                                                \
221         dmin = FFMIN(sD[i + rslope], dmin);                                    \
222     }                                                                          \
223                                                                                \
224     for (int i = -rslope; i <= rslope; i++) {                                  \
225         atype sum = 0;                                                         \
226                                                                                \
227         for (int j = -redge; j <= redge; j++) {                                \
228             sum += diff_##ss(prev_line,  next_line,  end, x, k + i, j);        \
229             sum += diff_##ss(prev2_line, prev_line,  end, x, k + i, j);        \
230             sum += diff_##ss(next_line,  next2_line, end, x, k + i, j);        \
231         }                                                                      \
232                                                                                \
233         sd[i + rslope]  =     sum;                                             \
234         sd[i + rslope] += f * cost_##ss(prev_line, next_line, end, x, k + i);  \
235         sd[i + rslope] += h * abs(k + i);                                      \
236                                                                                \
237         dmin = FFMIN(sd[i + rslope], dmin);                                    \
238     }                                                                          \
239                                                                                \
240     for (int i = -rslope; i <= rslope && abs(k) > rslope; i++) {               \
241         if (dmin == sD[i + rslope]) {                                          \
242             di = 1;                                                            \
243             k = i;                                                             \
244             break;                                                             \
245         }                                                                      \
246     }                                                                          \
247                                                                                \
248     for (int i = -rslope; i <= rslope && !di; i++) {                           \
249         if (dmin == sd[i + rslope]) {                                          \
250             k += i;                                                            \
251             break;                                                             \
252         }                                                                      \
253     }                                                                          \
254                                                                                \
255     dst[x] = mid4_##ss(prev_line, next_line, prev2_line, next2_line,           \
256                        end, x, k, depth);                                      \
257                                                                                \
258     *K = k;                                                                    \
259 }
260
261 INTERPOLATE(uint8_t,  unsigned, UINT_MAX, 8)
262 INTERPOLATE(uint16_t, uint64_t, UINT64_MAX, 16)
263
264 static int deinterlace_slice(AVFilterContext *ctx, void *arg,
265                              int jobnr, int nb_jobs)
266 {
267     ESTDIFContext *s = ctx->priv;
268     ThreadData *td = arg;
269     AVFrame *out = td->out;
270     AVFrame *in = td->in;
271     const int rslope = s->rslope;
272     const int redge = s->redge;
273     const int half = s->half;
274     const int depth = s->depth;
275     const int interlaced = in->interlaced_frame;
276     const int tff = (s->field == (s->parity == -1 ? interlaced ? in->top_field_first : 1 :
277                                   s->parity ^ 1));
278
279     for (int plane = 0; plane < s->nb_planes; plane++) {
280         const uint8_t *src_data = in->data[plane];
281         uint8_t *dst_data = out->data[plane];
282         const int linesize = s->linesize[plane];
283         const int width = s->planewidth[plane];
284         const int height = s->planeheight[plane];
285         const int src_linesize = in->linesize[plane];
286         const int dst_linesize = out->linesize[plane];
287         const int start = (height * jobnr) / nb_jobs;
288         const int end = (height * (jobnr+1)) / nb_jobs;
289         const uint8_t *prev_line, *prev2_line, *next_line, *next2_line, *in_line;
290         uint8_t *out_line;
291         int y_out;
292
293         y_out = start + (tff ^ (start & 1));
294
295         in_line  = src_data + (y_out * src_linesize);
296         out_line = dst_data + (y_out * dst_linesize);
297
298         while (y_out < end) {
299             memcpy(out_line, in_line, linesize);
300             y_out += 2;
301             in_line  += src_linesize * 2;
302             out_line += dst_linesize * 2;
303         }
304
305         y_out = start + ((!tff) ^ (start & 1));
306         out_line = dst_data + (y_out * dst_linesize);
307
308         for (int y = y_out; y < end; y += 2) {
309             int y_prev2_in = y - 3;
310             int y_next2_in = y + 3;
311             int y_prev_in = y - 1;
312             int y_next_in = y + 1;
313             int k;
314
315             while (y_prev2_in < 0)
316                 y_prev2_in += 2;
317
318             while (y_next2_in >= height)
319                 y_next2_in -= 2;
320
321             while (y_prev_in < 0)
322                 y_prev_in += 2;
323
324             while (y_next_in >= height)
325                 y_next_in -= 2;
326
327             prev2_line = src_data + (y_prev2_in * src_linesize);
328             next2_line = src_data + (y_next2_in * src_linesize);
329
330             prev_line = src_data + (y_prev_in * src_linesize);
331             next_line = src_data + (y_next_in * src_linesize);
332
333             k = 0;
334
335             for (int x = 0; x < width; x++) {
336                 s->interpolate(out_line,
337                                prev_line, next_line,
338                                prev2_line, next2_line,
339                                x, width, rslope, redge, half, depth, &k);
340             }
341
342             out_line += 2 * dst_linesize;
343         }
344     }
345
346     return 0;
347 }
348
349 static int filter(AVFilterContext *ctx, int is_second, AVFrame *in)
350 {
351     ESTDIFContext *s = ctx->priv;
352     AVFilterLink *outlink = ctx->outputs[0];
353     AVFrame *out;
354     ThreadData td;
355
356     out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
357     if (!out)
358         return AVERROR(ENOMEM);
359     av_frame_copy_props(out, in);
360     out->interlaced_frame = 0;
361     out->pts = s->pts;
362
363     td.out = out; td.in = in;
364     ctx->internal->execute(ctx, deinterlace_slice, &td, NULL,
365                            FFMIN(s->planeheight[1] / 2, s->nb_threads));
366
367     if (s->mode)
368         s->field = !s->field;
369
370     return ff_filter_frame(outlink, out);
371 }
372
373 static int config_input(AVFilterLink *inlink)
374 {
375     AVFilterContext *ctx = inlink->dst;
376     ESTDIFContext *s = ctx->priv;
377     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
378     int ret;
379
380     if ((ret = av_image_fill_linesizes(s->linesize, inlink->format, inlink->w)) < 0)
381         return ret;
382
383     s->planeheight[1] = s->planeheight[2] = AV_CEIL_RSHIFT(inlink->h, desc->log2_chroma_h);
384     s->planeheight[0] = s->planeheight[3] = inlink->h;
385     s->planewidth[1] = s->planewidth[2] = AV_CEIL_RSHIFT(inlink->w, desc->log2_chroma_w);
386     s->planewidth[0] = s->planewidth[3] = inlink->w;
387
388     if (inlink->h < 3) {
389         av_log(ctx, AV_LOG_ERROR, "Video of less than 3 lines is not supported\n");
390         return AVERROR(EINVAL);
391     }
392
393     s->nb_planes = av_pix_fmt_count_planes(inlink->format);
394     s->nb_threads = ff_filter_get_nb_threads(ctx);
395     s->depth = desc->comp[0].depth;
396     s->interpolate = s->depth <= 8 ? interpolate_8 : interpolate_16;
397     s->half = 1 << (s->depth - 1);
398
399     return 0;
400 }
401  static int filter_frame(AVFilterLink *inlink, AVFrame *in)
402 {
403     AVFilterContext *ctx = inlink->dst;
404     ESTDIFContext *s = ctx->priv;
405     int ret;
406
407     if (!s->prev) {
408         s->prev = in;
409         return 0;
410     }
411
412     if ((s->deint && !in->interlaced_frame) || ctx->is_disabled) {
413         s->prev->pts *= 2;
414         ret = ff_filter_frame(ctx->outputs[0], s->prev);
415         s->prev = in;
416         return ret;
417     }
418
419     s->pts = s->prev->pts * 2;
420     ret = filter(ctx, 0, s->prev);
421     if (ret < 0 || s->mode == 0) {
422         av_frame_free(&s->prev);
423         s->prev = in;
424         return ret;
425     }
426
427     s->pts = s->prev->pts + in->pts;
428     ret = filter(ctx, 1, s->prev);
429     av_frame_free(&s->prev);
430     s->prev = in;
431     return ret;
432 }
433
434 static int request_frame(AVFilterLink *link)
435 {
436     AVFilterContext *ctx = link->src;
437     ESTDIFContext *s = ctx->priv;
438     int ret;
439
440     if (s->eof)
441         return AVERROR_EOF;
442
443     ret = ff_request_frame(ctx->inputs[0]);
444
445     if (ret == AVERROR_EOF && s->prev) {
446         AVFrame *next = av_frame_clone(s->prev);
447
448         if (!next)
449             return AVERROR(ENOMEM);
450
451         next->pts = s->prev->pts + av_rescale_q(1, av_inv_q(ctx->outputs[0]->frame_rate),
452                                                 ctx->outputs[0]->time_base);
453         s->eof = 1;
454         ret = filter_frame(ctx->inputs[0], next);
455     } else if (ret < 0) {
456         return ret;
457     }
458
459     return ret;
460 }
461
462 static av_cold void uninit(AVFilterContext *ctx)
463 {
464     ESTDIFContext *s = ctx->priv;
465
466     av_frame_free(&s->prev);
467 }
468
469 static const AVFilterPad estdif_inputs[] = {
470     {
471         .name          = "default",
472         .type          = AVMEDIA_TYPE_VIDEO,
473         .filter_frame  = filter_frame,
474         .config_props  = config_input,
475     },
476     { NULL }
477 };
478
479 static const AVFilterPad estdif_outputs[] = {
480     {
481         .name          = "default",
482         .type          = AVMEDIA_TYPE_VIDEO,
483         .config_props  = config_output,
484         .request_frame = request_frame,
485     },
486     { NULL }
487 };
488
489 AVFilter ff_vf_estdif = {
490     .name          = "estdif",
491     .description   = NULL_IF_CONFIG_SMALL("Apply Edge Slope Tracing deinterlace."),
492     .priv_size     = sizeof(ESTDIFContext),
493     .priv_class    = &estdif_class,
494     .uninit        = uninit,
495     .query_formats = query_formats,
496     .inputs        = estdif_inputs,
497     .outputs       = estdif_outputs,
498     .flags         = AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL | AVFILTER_FLAG_SLICE_THREADS,
499     .process_command = ff_filter_process_command,
500 };