]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_mix.c
avfilter/vf_mix: clip output pixel values
[ffmpeg] / libavfilter / vf_mix.c
1 /*
2  * Copyright (c) 2017 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/avstring.h"
22 #include "libavutil/imgutils.h"
23 #include "libavutil/intreadwrite.h"
24 #include "libavutil/opt.h"
25 #include "libavutil/pixdesc.h"
26
27 #include "avfilter.h"
28 #include "formats.h"
29 #include "internal.h"
30 #include "framesync.h"
31 #include "video.h"
32
33 typedef struct MixContext {
34     const AVClass *class;
35     const AVPixFmtDescriptor *desc;
36     char *weights_str;
37     int nb_inputs;
38     int duration;
39     float *weights;
40     float scale;
41     float wfactor;
42
43     int tmix;
44     int nb_frames;
45
46     int depth;
47     int max;
48     int nb_planes;
49     int linesize[4];
50     int height[4];
51
52     AVFrame **frames;
53     FFFrameSync fs;
54 } MixContext;
55
56 static int query_formats(AVFilterContext *ctx)
57 {
58     AVFilterFormats *pix_fmts = NULL;
59     int fmt, ret;
60
61     for (fmt = 0; av_pix_fmt_desc_get(fmt); fmt++) {
62         const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(fmt);
63         if (!(desc->flags & AV_PIX_FMT_FLAG_PAL ||
64               desc->flags & AV_PIX_FMT_FLAG_HWACCEL ||
65               desc->flags & AV_PIX_FMT_FLAG_BITSTREAM) &&
66             (ret = ff_add_format(&pix_fmts, fmt)) < 0)
67             return ret;
68     }
69
70     return ff_set_common_formats(ctx, pix_fmts);
71 }
72
73 static av_cold int init(AVFilterContext *ctx)
74 {
75     MixContext *s = ctx->priv;
76     char *p, *arg, *saveptr = NULL;
77     int i, ret;
78
79     s->tmix = !strcmp(ctx->filter->name, "tmix");
80
81     s->frames = av_calloc(s->nb_inputs, sizeof(*s->frames));
82     if (!s->frames)
83         return AVERROR(ENOMEM);
84
85     s->weights = av_calloc(s->nb_inputs, sizeof(*s->weights));
86     if (!s->weights)
87         return AVERROR(ENOMEM);
88
89     if (!s->tmix) {
90         for (i = 0; i < s->nb_inputs; i++) {
91             AVFilterPad pad = { 0 };
92
93             pad.type = AVMEDIA_TYPE_VIDEO;
94             pad.name = av_asprintf("input%d", i);
95             if (!pad.name)
96                 return AVERROR(ENOMEM);
97
98             if ((ret = ff_insert_inpad(ctx, i, &pad)) < 0) {
99                 av_freep(&pad.name);
100                 return ret;
101             }
102         }
103     }
104
105     p = s->weights_str;
106     for (i = 0; i < s->nb_inputs; i++) {
107         if (!(arg = av_strtok(p, " ", &saveptr)))
108             break;
109
110         p = NULL;
111         sscanf(arg, "%f", &s->weights[i]);
112         s->wfactor += s->weights[i];
113     }
114     if (s->scale == 0) {
115         s->wfactor = 1 / s->wfactor;
116     } else {
117         s->wfactor = s->scale;
118     }
119
120     return 0;
121 }
122
123 static void mix_frames(MixContext *s, AVFrame **in, AVFrame *out)
124 {
125     int i, p, x, y;
126
127     if (s->depth <= 8) {
128         for (p = 0; p < s->nb_planes; p++) {
129             uint8_t *dst = out->data[p];
130
131             for (y = 0; y < s->height[p]; y++) {
132                 for (x = 0; x < s->linesize[p]; x++) {
133                     int val = 0;
134
135                     for (i = 0; i < s->nb_inputs; i++) {
136                         uint8_t src = in[i]->data[p][y * s->linesize[p] + x];
137
138                         val += src * s->weights[i];
139                     }
140
141                     dst[x] = av_clip_uint8(val * s->wfactor);
142                 }
143
144                 dst += out->linesize[p];
145             }
146         }
147     } else {
148         for (p = 0; p < s->nb_planes; p++) {
149             uint16_t *dst = (uint16_t *)out->data[p];
150
151             for (y = 0; y < s->height[p]; y++) {
152                 for (x = 0; x < s->linesize[p] / 2; x++) {
153                     int val = 0;
154
155                     for (i = 0; i < s->nb_inputs; i++) {
156                         uint16_t src = AV_RN16(in[i]->data[p] + y * s->linesize[p] + x * 2);
157
158                         val += src * s->weights[i];
159                     }
160
161                     dst[x] = av_clip(val * s->wfactor, 0, s->max);
162                 }
163
164                 dst += out->linesize[p] / 2;
165             }
166         }
167     }
168 }
169
170 static int process_frame(FFFrameSync *fs)
171 {
172     AVFilterContext *ctx = fs->parent;
173     AVFilterLink *outlink = ctx->outputs[0];
174     MixContext *s = fs->opaque;
175     AVFrame **in = s->frames;
176     AVFrame *out;
177     int i, ret;
178
179     for (i = 0; i < s->nb_inputs; i++) {
180         if ((ret = ff_framesync_get_frame(&s->fs, i, &in[i], 0)) < 0)
181             return ret;
182     }
183
184     out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
185     if (!out)
186         return AVERROR(ENOMEM);
187     out->pts = av_rescale_q(s->fs.pts, s->fs.time_base, outlink->time_base);
188
189     mix_frames(s, in, out);
190
191     return ff_filter_frame(outlink, out);
192 }
193
194 static int config_output(AVFilterLink *outlink)
195 {
196     AVFilterContext *ctx = outlink->src;
197     MixContext *s = ctx->priv;
198     AVRational time_base = ctx->inputs[0]->time_base;
199     AVRational frame_rate = ctx->inputs[0]->frame_rate;
200     AVFilterLink *inlink = ctx->inputs[0];
201     int height = ctx->inputs[0]->h;
202     int width = ctx->inputs[0]->w;
203     FFFrameSyncIn *in;
204     int i, ret;
205
206     if (!s->tmix) {
207         for (i = 1; i < s->nb_inputs; i++) {
208             if (ctx->inputs[i]->h != height || ctx->inputs[i]->w != width) {
209                 av_log(ctx, AV_LOG_ERROR, "Input %d size (%dx%d) does not match input %d size (%dx%d).\n", i, ctx->inputs[i]->w, ctx->inputs[i]->h, 0, width, height);
210                 return AVERROR(EINVAL);
211             }
212         }
213     }
214
215     s->desc = av_pix_fmt_desc_get(outlink->format);
216     if (!s->desc)
217         return AVERROR_BUG;
218     s->nb_planes = av_pix_fmt_count_planes(outlink->format);
219     s->depth = s->desc->comp[0].depth;
220     s->max = (1 << s->depth) - 1;
221
222     if ((ret = av_image_fill_linesizes(s->linesize, inlink->format, inlink->w)) < 0)
223         return ret;
224
225     s->height[1] = s->height[2] = AV_CEIL_RSHIFT(inlink->h, s->desc->log2_chroma_h);
226     s->height[0] = s->height[3] = inlink->h;
227
228     if (s->tmix)
229         return 0;
230
231     outlink->w          = width;
232     outlink->h          = height;
233     outlink->time_base  = time_base;
234     outlink->frame_rate = frame_rate;
235
236     if ((ret = ff_framesync_init(&s->fs, ctx, s->nb_inputs)) < 0)
237         return ret;
238
239     in = s->fs.in;
240     s->fs.opaque = s;
241     s->fs.on_event = process_frame;
242
243     for (i = 0; i < s->nb_inputs; i++) {
244         AVFilterLink *inlink = ctx->inputs[i];
245
246         in[i].time_base = inlink->time_base;
247         in[i].sync   = 1;
248         in[i].before = EXT_STOP;
249         in[i].after  = (s->duration == 1 || (s->duration == 2 && i == 0)) ? EXT_STOP : EXT_INFINITY;
250     }
251
252     return ff_framesync_configure(&s->fs);
253 }
254
255 static av_cold void uninit(AVFilterContext *ctx)
256 {
257     MixContext *s = ctx->priv;
258     int i;
259
260     ff_framesync_uninit(&s->fs);
261     av_freep(&s->weights);
262
263     if (!s->tmix) {
264         for (i = 0; i < ctx->nb_inputs; i++)
265             av_freep(&ctx->input_pads[i].name);
266     } else {
267         for (i = 0; i < s->nb_frames; i++)
268             av_frame_free(&s->frames[i]);
269     }
270     av_freep(&s->frames);
271 }
272
273 static int activate(AVFilterContext *ctx)
274 {
275     MixContext *s = ctx->priv;
276     return ff_framesync_activate(&s->fs);
277 }
278
279 #define OFFSET(x) offsetof(MixContext, x)
280 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_FILTERING_PARAM
281
282 static const AVOption mix_options[] = {
283     { "inputs", "set number of inputs", OFFSET(nb_inputs), AV_OPT_TYPE_INT, {.i64=2}, 2, INT_MAX, .flags = FLAGS },
284     { "weights", "set weight for each input", OFFSET(weights_str), AV_OPT_TYPE_STRING, {.str="1 1"}, 0, 0, .flags = FLAGS },
285     { "scale", "set scale", OFFSET(scale), AV_OPT_TYPE_FLOAT, {.dbl=0}, 0, INT16_MAX, .flags = FLAGS },
286     { "duration", "how to determine end of stream", OFFSET(duration), AV_OPT_TYPE_INT, {.i64=0}, 0, 2, .flags = FLAGS, "duration" },
287         { "longest",  "Duration of longest input",  0, AV_OPT_TYPE_CONST, {.i64=0}, 0, 0, FLAGS, "duration" },
288         { "shortest", "Duration of shortest input", 0, AV_OPT_TYPE_CONST, {.i64=1}, 0, 0, FLAGS, "duration" },
289         { "first",    "Duration of first input",    0, AV_OPT_TYPE_CONST, {.i64=2}, 0, 0, FLAGS, "duration" },
290     { NULL },
291 };
292
293 static const AVFilterPad outputs[] = {
294     {
295         .name          = "default",
296         .type          = AVMEDIA_TYPE_VIDEO,
297         .config_props  = config_output,
298     },
299     { NULL }
300 };
301
302 #if CONFIG_MIX_FILTER
303 AVFILTER_DEFINE_CLASS(mix);
304
305 AVFilter ff_vf_mix = {
306     .name          = "mix",
307     .description   = NULL_IF_CONFIG_SMALL("Mix video inputs."),
308     .priv_size     = sizeof(MixContext),
309     .priv_class    = &mix_class,
310     .query_formats = query_formats,
311     .outputs       = outputs,
312     .init          = init,
313     .uninit        = uninit,
314     .activate      = activate,
315     .flags         = AVFILTER_FLAG_DYNAMIC_INPUTS,
316 };
317
318 #endif /* CONFIG_MIX_FILTER */
319
320 #if CONFIG_TMIX_FILTER
321 static int tmix_filter_frame(AVFilterLink *inlink, AVFrame *in)
322 {
323     AVFilterContext *ctx = inlink->dst;
324     AVFilterLink *outlink = ctx->outputs[0];
325     MixContext *s = ctx->priv;
326     AVFrame *out;
327
328     if (s->nb_frames < s->nb_inputs) {
329         s->frames[s->nb_frames] = in;
330         s->nb_frames++;
331         return 0;
332     } else {
333         av_frame_free(&s->frames[0]);
334         memmove(&s->frames[0], &s->frames[1], sizeof(*s->frames) * (s->nb_inputs - 1));
335         s->frames[s->nb_inputs - 1] = in;
336     }
337
338     out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
339     if (!out)
340         return AVERROR(ENOMEM);
341     out->pts = s->frames[0]->pts;
342
343     mix_frames(s, s->frames, out);
344
345     return ff_filter_frame(outlink, out);
346 }
347
348 static const AVOption tmix_options[] = {
349     { "frames", "set number of successive frames to mix", OFFSET(nb_inputs), AV_OPT_TYPE_INT, {.i64=3}, 2, 128, .flags = FLAGS },
350     { "weights", "set weight for each frame", OFFSET(weights_str), AV_OPT_TYPE_STRING, {.str="1 1 1"}, 0, 0, .flags = FLAGS },
351     { "scale", "set scale", OFFSET(scale), AV_OPT_TYPE_FLOAT, {.dbl=0}, 0, INT16_MAX, .flags = FLAGS },
352     { NULL },
353 };
354
355 static const AVFilterPad inputs[] = {
356     {
357         .name          = "default",
358         .type          = AVMEDIA_TYPE_VIDEO,
359         .filter_frame  = tmix_filter_frame,
360     },
361     { NULL }
362 };
363
364 AVFILTER_DEFINE_CLASS(tmix);
365
366 AVFilter ff_vf_tmix = {
367     .name          = "tmix",
368     .description   = NULL_IF_CONFIG_SMALL("Mix successive video frames."),
369     .priv_size     = sizeof(MixContext),
370     .priv_class    = &tmix_class,
371     .query_formats = query_formats,
372     .outputs       = outputs,
373     .inputs        = inputs,
374     .init          = init,
375     .uninit        = uninit,
376 };
377
378 #endif /* CONFIG_TMIX_FILTER */