]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_ssim.c
Merge commit '42bc768e5240ec01237ad2eb7c69b917158de258'
[ffmpeg] / libavfilter / vf_ssim.c
1 /*
2  * Copyright (c) 2003-2013 Loren Merritt
3  * Copyright (c) 2015 Paul B Mahol
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (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 GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /* Computes the Structural Similarity Metric between two video streams.
23  * original algorithm:
24  * Z. Wang, A. C. Bovik, H. R. Sheikh and E. P. Simoncelli,
25  *   "Image quality assessment: From error visibility to structural similarity,"
26  *   IEEE Transactions on Image Processing, vol. 13, no. 4, pp. 600-612, Apr. 2004.
27  *
28  * To improve speed, this implementation uses the standard approximation of
29  * overlapped 8x8 block sums, rather than the original gaussian weights.
30  */
31
32 /*
33  * @file
34  * Caculate the SSIM between two input videos.
35  */
36
37 #include "libavutil/opt.h"
38 #include "libavutil/pixdesc.h"
39 #include "avfilter.h"
40 #include "dualinput.h"
41 #include "drawutils.h"
42 #include "formats.h"
43 #include "internal.h"
44 #include "video.h"
45
46 typedef struct SSIMContext {
47     const AVClass *class;
48     FFDualInputContext dinput;
49     FILE *stats_file;
50     char *stats_file_str;
51     int nb_components;
52     uint64_t nb_frames;
53     double ssim[4];
54     char comps[4];
55     int *coefs;
56     uint8_t rgba_map[4];
57     int planewidth[4];
58     int planeheight[4];
59     int *temp;
60 } SSIMContext;
61
62 #define OFFSET(x) offsetof(SSIMContext, x)
63 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
64
65 static const AVOption ssim_options[] = {
66     {"stats_file", "Set file where to store per-frame difference information", OFFSET(stats_file_str), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, FLAGS },
67     {"f",          "Set file where to store per-frame difference information", OFFSET(stats_file_str), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, FLAGS },
68     { NULL }
69 };
70
71 AVFILTER_DEFINE_CLASS(ssim);
72
73 static int rgb_coefs[4]  = { 1, 1, 1, 3};
74 static int yuv_coefs[4]  = { 4, 1, 1, 6};
75 static int gray_coefs[4] = { 1, 0, 0, 1};
76
77 static void set_meta(AVDictionary **metadata, const char *key, char comp, float d)
78 {
79     char value[128];
80     snprintf(value, sizeof(value), "%0.2f", d);
81     if (comp) {
82         char key2[128];
83         snprintf(key2, sizeof(key2), "%s%c", key, comp);
84         av_dict_set(metadata, key2, value, 0);
85     } else {
86         av_dict_set(metadata, key, value, 0);
87     }
88 }
89
90 static void ssim_4x4x2_core(const uint8_t *main, int main_stride,
91                             const uint8_t *ref, int ref_stride,
92                             int sums[2][4])
93 {
94     int x, y, z;
95
96     for (z = 0; z < 2; z++) {
97         uint32_t s1 = 0, s2 = 0, ss = 0, s12 = 0;
98
99         for (y = 0; y < 4; y++) {
100             for (x = 0; x < 4; x++) {
101                 int a = main[x + y * main_stride];
102                 int b = ref[x + y * ref_stride];
103
104                 s1  += a;
105                 s2  += b;
106                 ss  += a*a;
107                 ss  += b*b;
108                 s12 += a*b;
109             }
110         }
111
112         sums[z][0] = s1;
113         sums[z][1] = s2;
114         sums[z][2] = ss;
115         sums[z][3] = s12;
116         main += 4;
117         ref += 4;
118     }
119 }
120
121 static float ssim_end1(int s1, int s2, int ss, int s12)
122 {
123     static const int ssim_c1 = (int)(.01*.01*255*255*64 + .5);
124     static const int ssim_c2 = (int)(.03*.03*255*255*64*63 + .5);
125
126     int fs1 = s1;
127     int fs2 = s2;
128     int fss = ss;
129     int fs12 = s12;
130     int vars = fss * 64 - fs1 * fs1 - fs2 * fs2;
131     int covar = fs12 * 64 - fs1 * fs2;
132
133     return (float)(2 * fs1 * fs2 + ssim_c1) * (float)(2 * covar + ssim_c2)
134          / ((float)(fs1 * fs1 + fs2 * fs2 + ssim_c1) * (float)(vars + ssim_c2));
135 }
136
137 static float ssim_end4(int sum0[5][4], int sum1[5][4], int width)
138 {
139     float ssim = 0.0;
140     int i;
141
142     for( i = 0; i < width; i++ )
143         ssim += ssim_end1(sum0[i][0] + sum0[i + 1][0] + sum1[i][0] + sum1[i + 1][0],
144                           sum0[i][1] + sum0[i + 1][1] + sum1[i][1] + sum1[i + 1][1],
145                           sum0[i][2] + sum0[i + 1][2] + sum1[i][2] + sum1[i + 1][2],
146                           sum0[i][3] + sum0[i + 1][3] + sum1[i][3] + sum1[i + 1][3]);
147     return ssim;
148 }
149
150 static float ssim_plane(uint8_t *main, int main_stride,
151                         uint8_t *ref, int ref_stride,
152                         int width, int height, void *temp)
153 {
154     int z = 0;
155     int x, y;
156     float ssim = 0.0;
157     int (*sum0)[4] = temp;
158     int (*sum1)[4] = sum0 + (width >> 2) + 3;
159
160     width >>= 2;
161     height >>= 2;
162
163     for (y = 1; y < height; y++) {
164         for (; z <= y; z++) {
165             FFSWAP(void*, sum0, sum1);
166             for (x = 0; x < width; x+=2)
167                 ssim_4x4x2_core(&main[4 * (x + z * main_stride)], main_stride,
168                                 &ref[4 * (x + z * ref_stride)], ref_stride,
169                                 &sum0[x]);
170         }
171
172         for (x = 0; x < width - 1; x += 4)
173             ssim += ssim_end4(sum0 + x, sum1 + x, FFMIN(4, width - x - 1));
174     }
175
176     return ssim / ((height - 1) * (width - 1));
177 }
178
179 static double ssim_db(double ssim, double weight)
180 {
181     return 10 * (log(weight) / log(10) - log(weight - ssim) / log(10));
182 }
183
184 static AVFrame *do_ssim(AVFilterContext *ctx, AVFrame *main,
185                         const AVFrame *ref)
186 {
187     AVDictionary **metadata = avpriv_frame_get_metadatap(main);
188     SSIMContext *s = ctx->priv;
189     float c[4], ssimv;
190     int i;
191
192     s->nb_frames++;
193
194     for (i = 0; i < s->nb_components; i++)
195         c[i] = ssim_plane(main->data[i], main->linesize[i],
196                           ref->data[i], ref->linesize[i],
197                           s->planewidth[i], s->planeheight[i], s->temp);
198
199     ssimv = (c[0] * s->coefs[0] + c[1] * s->coefs[1] + c[2] * s->coefs[2]) / s->coefs[3];
200
201     for (i = 0; i < s->nb_components; i++)
202         set_meta(metadata, "lavfi.ssim.", s->comps[i], c[i]);
203
204     set_meta(metadata, "lavfi.ssim.All", 0, ssimv);
205     set_meta(metadata, "lavfi.ssim.dB", 0, ssim_db(c[0] * s->coefs[0] + c[1] * s->coefs[1] + c[2] * s->coefs[2], s->coefs[3]));
206
207     if (s->stats_file) {
208         fprintf(s->stats_file, "n:%"PRId64" ", s->nb_frames);
209
210         for (i = 0; i < s->nb_components; i++)
211             fprintf(s->stats_file, "%c:%f ", s->comps[i], c[i]);
212
213         fprintf(s->stats_file, "All:%f (%f)\n", ssimv, ssim_db(c[0] * s->coefs[0] + c[1] * s->coefs[1] + c[2] * s->coefs[2], s->coefs[3]));
214     }
215
216     s->ssim[0] += c[0];
217     s->ssim[1] += c[1];
218     s->ssim[2] += c[2];
219
220     return main;
221 }
222
223 static av_cold int init(AVFilterContext *ctx)
224 {
225     SSIMContext *s = ctx->priv;
226
227     if (s->stats_file_str) {
228         s->stats_file = fopen(s->stats_file_str, "w");
229         if (!s->stats_file) {
230             int err = AVERROR(errno);
231             char buf[128];
232             av_strerror(err, buf, sizeof(buf));
233             av_log(ctx, AV_LOG_ERROR, "Could not open stats file %s: %s\n",
234                    s->stats_file_str, buf);
235             return err;
236         }
237     }
238
239     s->dinput.process = do_ssim;
240     s->dinput.shortest = 1;
241     s->dinput.repeatlast = 0;
242     return 0;
243 }
244
245 static int query_formats(AVFilterContext *ctx)
246 {
247     static const enum AVPixelFormat pix_fmts[] = {
248         AV_PIX_FMT_GRAY8,
249         AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P,
250         AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUV411P, AV_PIX_FMT_YUV410P,
251         AV_PIX_FMT_YUVJ411P, AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P,
252         AV_PIX_FMT_YUVJ440P, AV_PIX_FMT_YUVJ444P,
253         AV_PIX_FMT_GBRP,
254         AV_PIX_FMT_NONE
255     };
256
257     AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
258     if (!fmts_list)
259         return AVERROR(ENOMEM);
260     return ff_set_common_formats(ctx, fmts_list);
261 }
262
263 static int config_input_ref(AVFilterLink *inlink)
264 {
265     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
266     AVFilterContext *ctx  = inlink->dst;
267     SSIMContext *s = ctx->priv;
268     int is_rgb;
269
270     s->nb_components = desc->nb_components;
271
272     if (ctx->inputs[0]->w != ctx->inputs[1]->w ||
273         ctx->inputs[0]->h != ctx->inputs[1]->h) {
274         av_log(ctx, AV_LOG_ERROR, "Width and height of input videos must be same.\n");
275         return AVERROR(EINVAL);
276     }
277     if (ctx->inputs[0]->format != ctx->inputs[1]->format) {
278         av_log(ctx, AV_LOG_ERROR, "Inputs must be of same pixel format.\n");
279         return AVERROR(EINVAL);
280     }
281
282     is_rgb = ff_fill_rgba_map(s->rgba_map, inlink->format) >= 0;
283     s->comps[0] = is_rgb ? 'R' : 'Y';
284     s->comps[1] = is_rgb ? 'G' : 'U';
285     s->comps[2] = is_rgb ? 'B' : 'V';
286     s->comps[3] = 'A';
287
288     if (is_rgb) {
289         s->coefs = rgb_coefs;
290     } else if (s->nb_components == 1) {
291         s->coefs = gray_coefs;
292     } else {
293         s->coefs = yuv_coefs;
294     }
295
296     s->planeheight[1] = s->planeheight[2] = FF_CEIL_RSHIFT(inlink->h, desc->log2_chroma_h);
297     s->planeheight[0] = s->planeheight[3] = inlink->h;
298     s->planewidth[1]  = s->planewidth[2]  = FF_CEIL_RSHIFT(inlink->w, desc->log2_chroma_w);
299     s->planewidth[0]  = s->planewidth[3]  = inlink->w;
300
301     s->temp = av_malloc((2 * inlink->w + 12) * sizeof(*s->temp));
302     if (!s->temp)
303         return AVERROR(ENOMEM);
304
305     return 0;
306 }
307
308 static int config_output(AVFilterLink *outlink)
309 {
310     AVFilterContext *ctx = outlink->src;
311     SSIMContext *s = ctx->priv;
312     AVFilterLink *mainlink = ctx->inputs[0];
313     int ret;
314
315     outlink->w = mainlink->w;
316     outlink->h = mainlink->h;
317     outlink->time_base = mainlink->time_base;
318     outlink->sample_aspect_ratio = mainlink->sample_aspect_ratio;
319     outlink->frame_rate = mainlink->frame_rate;
320
321     if ((ret = ff_dualinput_init(ctx, &s->dinput)) < 0)
322         return ret;
323
324     return 0;
325 }
326
327 static int filter_frame(AVFilterLink *inlink, AVFrame *buf)
328 {
329     SSIMContext *s = inlink->dst->priv;
330     return ff_dualinput_filter_frame(&s->dinput, inlink, buf);
331 }
332
333 static int request_frame(AVFilterLink *outlink)
334 {
335     SSIMContext *s = outlink->src->priv;
336     return ff_dualinput_request_frame(&s->dinput, outlink);
337 }
338
339 static av_cold void uninit(AVFilterContext *ctx)
340 {
341     SSIMContext *s = ctx->priv;
342
343     if (s->nb_frames > 0) {
344         if (s->nb_components == 3) {
345             av_log(ctx, AV_LOG_INFO, "SSIM %c:%f %c:%f %c:%f All:%f (%f)\n",
346                s->comps[0], s->ssim[0] / s->nb_frames,
347                s->comps[1], s->ssim[1] / s->nb_frames,
348                s->comps[2], s->ssim[2] / s->nb_frames,
349                (s->ssim[0] * 4 + s->ssim[1] + s->ssim[2]) / (s->nb_frames * 6),
350                ssim_db(s->ssim[0] * 4 + s->ssim[1] + s->ssim[2], s->nb_frames * 6));
351         } else if (s->nb_components == 1) {
352             av_log(ctx, AV_LOG_INFO, "SSIM All:%f (%f)\n",
353                s->ssim[0] / s->nb_frames, ssim_db(s->ssim[0], s->nb_frames));
354         }
355     }
356
357     ff_dualinput_uninit(&s->dinput);
358
359     if (s->stats_file)
360         fclose(s->stats_file);
361
362     av_freep(&s->temp);
363 }
364
365 static const AVFilterPad ssim_inputs[] = {
366     {
367         .name         = "main",
368         .type         = AVMEDIA_TYPE_VIDEO,
369         .filter_frame = filter_frame,
370     },{
371         .name         = "reference",
372         .type         = AVMEDIA_TYPE_VIDEO,
373         .filter_frame = filter_frame,
374         .config_props = config_input_ref,
375     },
376     { NULL }
377 };
378
379 static const AVFilterPad ssim_outputs[] = {
380     {
381         .name          = "default",
382         .type          = AVMEDIA_TYPE_VIDEO,
383         .config_props  = config_output,
384         .request_frame = request_frame,
385     },
386     { NULL }
387 };
388
389 AVFilter ff_vf_ssim = {
390     .name          = "ssim",
391     .description   = NULL_IF_CONFIG_SMALL("Calculate the SSIM between two video streams."),
392     .init          = init,
393     .uninit        = uninit,
394     .query_formats = query_formats,
395     .priv_size     = sizeof(SSIMContext),
396     .priv_class    = &ssim_class,
397     .inputs        = ssim_inputs,
398     .outputs       = ssim_outputs,
399 };