]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_decimate.c
Merge commit '9d4da474f5f40b019cb4cb931c8499deee586174'
[ffmpeg] / libavfilter / vf_decimate.c
1 /*
2  * Copyright (c) 2003 Rich Felker
3  * Copyright (c) 2012 Stefano Sabatini
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2 of the License, or
10  * (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License along
18  * with FFmpeg; if not, write to the Free Software Foundation, Inc.,
19  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20  */
21
22 /**
23  * @file decimate filter, ported from libmpcodecs/vf_decimate.c by
24  * Rich Felker.
25  */
26
27 #include "libavutil/opt.h"
28 #include "libavutil/pixdesc.h"
29 #include "libavutil/timestamp.h"
30 #include "libavcodec/dsputil.h"
31 #include "avfilter.h"
32 #include "internal.h"
33 #include "formats.h"
34 #include "video.h"
35
36 typedef struct {
37     const AVClass *class;
38     int lo, hi;                    ///< lower and higher threshold number of differences
39                                    ///< values for 8x8 blocks
40
41     float frac;                    ///< threshold of changed pixels over the total fraction
42
43     int max_drop_count;            ///< if positive: maximum number of sequential frames to drop
44                                    ///< if negative: minimum number of frames between two drops
45
46     int drop_count;                ///< if positive: number of frames sequentially dropped
47                                    ///< if negative: number of sequential frames which were not dropped
48
49     int hsub, vsub;                ///< chroma subsampling values
50     AVFilterBufferRef *ref;        ///< reference picture
51     DSPContext dspctx;             ///< context providing optimized diff routines
52     AVCodecContext *avctx;         ///< codec context required for the DSPContext
53 } DecimateContext;
54
55 #define OFFSET(x) offsetof(DecimateContext, x)
56 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
57
58 static const AVOption decimate_options[] = {
59     { "max",  "set the maximum number of consecutive dropped frames (positive), or the minimum interval between dropped frames (negative)",
60       OFFSET(max_drop_count), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX, FLAGS },
61     { "hi",   "set high dropping threshold", OFFSET(hi), AV_OPT_TYPE_INT, {.i64=64*12}, INT_MIN, INT_MAX, FLAGS },
62     { "lo",   "set low dropping threshold", OFFSET(lo), AV_OPT_TYPE_INT, {.i64=64*5}, INT_MIN, INT_MAX, FLAGS },
63     { "frac", "set fraction dropping threshold",  OFFSET(frac), AV_OPT_TYPE_FLOAT, {.dbl=0.33}, 0, 1, FLAGS },
64     { NULL }
65 };
66
67 AVFILTER_DEFINE_CLASS(decimate);
68
69 /**
70  * Return 1 if the two planes are different, 0 otherwise.
71  */
72 static int diff_planes(AVFilterContext *ctx,
73                        uint8_t *cur, uint8_t *ref, int linesize,
74                        int w, int h)
75 {
76     DecimateContext *decimate = ctx->priv;
77     DSPContext *dspctx = &decimate->dspctx;
78
79     int x, y;
80     int d, c = 0;
81     int t = (w/16)*(h/16)*decimate->frac;
82     int16_t block[8*8];
83
84     /* compute difference for blocks of 8x8 bytes */
85     for (y = 0; y < h-7; y += 4) {
86         for (x = 8; x < w-7; x += 4) {
87             dspctx->diff_pixels(block,
88                                 cur+x+y*linesize,
89                                 ref+x+y*linesize, linesize);
90             d = dspctx->sum_abs_dctelem(block);
91             if (d > decimate->hi)
92                 return 1;
93             if (d > decimate->lo) {
94                 c++;
95                 if (c > t)
96                     return 1;
97             }
98         }
99     }
100     return 0;
101 }
102
103 /**
104  * Tell if the frame should be decimated, for example if it is no much
105  * different with respect to the reference frame ref.
106  */
107 static int decimate_frame(AVFilterContext *ctx,
108                           AVFilterBufferRef *cur, AVFilterBufferRef *ref)
109 {
110     DecimateContext *decimate = ctx->priv;
111     int plane;
112
113     if (decimate->max_drop_count > 0 &&
114         decimate->drop_count >= decimate->max_drop_count)
115         return 0;
116     if (decimate->max_drop_count < 0 &&
117         (decimate->drop_count-1) > decimate->max_drop_count)
118         return 0;
119
120     for (plane = 0; ref->data[plane] && ref->linesize[plane]; plane++) {
121         int vsub = plane == 1 || plane == 2 ? decimate->vsub : 0;
122         int hsub = plane == 1 || plane == 2 ? decimate->hsub : 0;
123         if (diff_planes(ctx,
124                         cur->data[plane], ref->data[plane], ref->linesize[plane],
125                         ref->video->w>>hsub, ref->video->h>>vsub))
126             return 0;
127     }
128
129     return 1;
130 }
131
132 static av_cold int init(AVFilterContext *ctx, const char *args)
133 {
134     DecimateContext *decimate = ctx->priv;
135     static const char *shorthand[] = { "max", "hi", "lo", "frac", NULL };
136     int ret;
137
138     decimate->class = &decimate_class;
139     av_opt_set_defaults(decimate);
140
141     if ((ret = av_opt_set_from_string(decimate, args, shorthand, "=", ":")) < 0)
142         return ret;
143
144     av_log(ctx, AV_LOG_VERBOSE, "max_drop_count:%d hi:%d lo:%d frac:%f\n",
145            decimate->max_drop_count, decimate->hi, decimate->lo, decimate->frac);
146
147     decimate->avctx = avcodec_alloc_context3(NULL);
148     if (!decimate->avctx)
149         return AVERROR(ENOMEM);
150     dsputil_init(&decimate->dspctx, decimate->avctx);
151
152     return 0;
153 }
154
155 static av_cold void uninit(AVFilterContext *ctx)
156 {
157     DecimateContext *decimate = ctx->priv;
158     avfilter_unref_bufferp(&decimate->ref);
159     avcodec_close(decimate->avctx);
160     av_opt_free(decimate);
161     av_freep(&decimate->avctx);
162 }
163
164 static int query_formats(AVFilterContext *ctx)
165 {
166     static const enum AVPixelFormat pix_fmts[] = {
167         AV_PIX_FMT_YUV444P,      AV_PIX_FMT_YUV422P,
168         AV_PIX_FMT_YUV420P,      AV_PIX_FMT_YUV411P,
169         AV_PIX_FMT_YUV410P,      AV_PIX_FMT_YUV440P,
170         AV_PIX_FMT_YUVJ444P,     AV_PIX_FMT_YUVJ422P,
171         AV_PIX_FMT_YUVJ420P,     AV_PIX_FMT_YUVJ440P,
172         AV_PIX_FMT_YUVA420P,
173         AV_PIX_FMT_NONE
174     };
175
176     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
177
178     return 0;
179 }
180
181 static int config_input(AVFilterLink *inlink)
182 {
183     AVFilterContext *ctx = inlink->dst;
184     DecimateContext *decimate = ctx->priv;
185     const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(inlink->format);
186     decimate->hsub = pix_desc->log2_chroma_w;
187     decimate->vsub = pix_desc->log2_chroma_h;
188
189     return 0;
190 }
191
192 static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *cur)
193 {
194     DecimateContext *decimate = inlink->dst->priv;
195     AVFilterLink *outlink = inlink->dst->outputs[0];
196     int ret;
197
198     if (decimate->ref && decimate_frame(inlink->dst, cur, decimate->ref)) {
199         decimate->drop_count = FFMAX(1, decimate->drop_count+1);
200     } else {
201         avfilter_unref_buffer(decimate->ref);
202         decimate->ref = cur;
203         decimate->drop_count = FFMIN(-1, decimate->drop_count-1);
204
205         if (ret = ff_filter_frame(outlink, avfilter_ref_buffer(cur, ~AV_PERM_WRITE)) < 0)
206             return ret;
207     }
208
209     av_log(inlink->dst, AV_LOG_DEBUG,
210            "%s pts:%s pts_time:%s drop_count:%d\n",
211            decimate->drop_count > 0 ? "drop" : "keep",
212            av_ts2str(cur->pts), av_ts2timestr(cur->pts, &inlink->time_base),
213            decimate->drop_count);
214
215     if (decimate->drop_count > 0)
216         avfilter_unref_buffer(cur);
217
218     return 0;
219 }
220
221 static int request_frame(AVFilterLink *outlink)
222 {
223     DecimateContext *decimate = outlink->src->priv;
224     AVFilterLink *inlink = outlink->src->inputs[0];
225     int ret;
226
227     do {
228         ret = ff_request_frame(inlink);
229     } while (decimate->drop_count > 0 && ret >= 0);
230
231     return ret;
232 }
233
234 static const AVFilterPad decimate_inputs[] = {
235     {
236         .name             = "default",
237         .type             = AVMEDIA_TYPE_VIDEO,
238         .get_video_buffer = ff_null_get_video_buffer,
239         .config_props     = config_input,
240         .filter_frame     = filter_frame,
241         .min_perms        = AV_PERM_READ | AV_PERM_PRESERVE,
242     },
243     { NULL }
244 };
245
246 static const AVFilterPad decimate_outputs[] = {
247     {
248         .name          = "default",
249         .type          = AVMEDIA_TYPE_VIDEO,
250         .request_frame = request_frame,
251     },
252     { NULL }
253 };
254
255 AVFilter avfilter_vf_decimate = {
256     .name        = "decimate",
257     .description = NULL_IF_CONFIG_SMALL("Remove near-duplicate frames."),
258     .init        = init,
259     .uninit      = uninit,
260
261     .priv_size = sizeof(DecimateContext),
262     .query_formats = query_formats,
263     .inputs        = decimate_inputs,
264     .outputs       = decimate_outputs,
265     .priv_class    = &decimate_class,
266 };