2 * Copyright (c) 2003-2013 Loren Merritt
3 * Copyright (c) 2015 Paul B Mahol
5 * This file is part of FFmpeg.
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.
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.
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
22 /* Computes the Structural Similarity Metric between two video streams.
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.
28 * To improve speed, this implementation uses the standard approximation of
29 * overlapped 8x8 block sums, rather than the original gaussian weights.
34 * Caculate the SSIM between two input videos.
37 #include "libavutil/avstring.h"
38 #include "libavutil/opt.h"
39 #include "libavutil/pixdesc.h"
41 #include "drawutils.h"
43 #include "framesync.h"
48 typedef struct SSIMContext {
56 double ssim[4], ssim_total;
64 double (*ssim_plane)(SSIMDSPContext *dsp,
65 uint8_t *main, int main_stride,
66 uint8_t *ref, int ref_stride,
67 int width, int height, void *temp,
72 #define OFFSET(x) offsetof(SSIMContext, x)
73 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
75 static const AVOption ssim_options[] = {
76 {"stats_file", "Set file where to store per-frame difference information", OFFSET(stats_file_str), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, FLAGS },
77 {"f", "Set file where to store per-frame difference information", OFFSET(stats_file_str), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, FLAGS },
81 FRAMESYNC_DEFINE_CLASS(ssim, SSIMContext, fs);
83 static void set_meta(AVDictionary **metadata, const char *key, char comp, float d)
86 snprintf(value, sizeof(value), "%0.2f", d);
89 snprintf(key2, sizeof(key2), "%s%c", key, comp);
90 av_dict_set(metadata, key2, value, 0);
92 av_dict_set(metadata, key, value, 0);
96 static void ssim_4x4xn_16bit(const uint8_t *main8, ptrdiff_t main_stride,
97 const uint8_t *ref8, ptrdiff_t ref_stride,
98 int64_t (*sums)[4], int width)
100 const uint16_t *main16 = (const uint16_t *)main8;
101 const uint16_t *ref16 = (const uint16_t *)ref8;
107 for (z = 0; z < width; z++) {
108 uint64_t s1 = 0, s2 = 0, ss = 0, s12 = 0;
110 for (y = 0; y < 4; y++) {
111 for (x = 0; x < 4; x++) {
112 unsigned a = main16[x + y * main_stride];
113 unsigned b = ref16[x + y * ref_stride];
132 static void ssim_4x4xn_8bit(const uint8_t *main, ptrdiff_t main_stride,
133 const uint8_t *ref, ptrdiff_t ref_stride,
134 int (*sums)[4], int width)
138 for (z = 0; z < width; z++) {
139 uint32_t s1 = 0, s2 = 0, ss = 0, s12 = 0;
141 for (y = 0; y < 4; y++) {
142 for (x = 0; x < 4; x++) {
143 int a = main[x + y * main_stride];
144 int b = ref[x + y * ref_stride];
163 static float ssim_end1x(int64_t s1, int64_t s2, int64_t ss, int64_t s12, int max)
165 int64_t ssim_c1 = (int64_t)(.01*.01*max*max*64 + .5);
166 int64_t ssim_c2 = (int64_t)(.03*.03*max*max*64*63 + .5);
172 int64_t vars = fss * 64 - fs1 * fs1 - fs2 * fs2;
173 int64_t covar = fs12 * 64 - fs1 * fs2;
175 return (float)(2 * fs1 * fs2 + ssim_c1) * (float)(2 * covar + ssim_c2)
176 / ((float)(fs1 * fs1 + fs2 * fs2 + ssim_c1) * (float)(vars + ssim_c2));
179 static float ssim_end1(int s1, int s2, int ss, int s12)
181 static const int ssim_c1 = (int)(.01*.01*255*255*64 + .5);
182 static const int ssim_c2 = (int)(.03*.03*255*255*64*63 + .5);
188 int vars = fss * 64 - fs1 * fs1 - fs2 * fs2;
189 int covar = fs12 * 64 - fs1 * fs2;
191 return (float)(2 * fs1 * fs2 + ssim_c1) * (float)(2 * covar + ssim_c2)
192 / ((float)(fs1 * fs1 + fs2 * fs2 + ssim_c1) * (float)(vars + ssim_c2));
195 static float ssim_endn_16bit(const int64_t (*sum0)[4], const int64_t (*sum1)[4], int width, int max)
200 for (i = 0; i < width; i++)
201 ssim += ssim_end1x(sum0[i][0] + sum0[i + 1][0] + sum1[i][0] + sum1[i + 1][0],
202 sum0[i][1] + sum0[i + 1][1] + sum1[i][1] + sum1[i + 1][1],
203 sum0[i][2] + sum0[i + 1][2] + sum1[i][2] + sum1[i + 1][2],
204 sum0[i][3] + sum0[i + 1][3] + sum1[i][3] + sum1[i + 1][3],
209 static double ssim_endn_8bit(const int (*sum0)[4], const int (*sum1)[4], int width)
214 for (i = 0; i < width; i++)
215 ssim += ssim_end1(sum0[i][0] + sum0[i + 1][0] + sum1[i][0] + sum1[i + 1][0],
216 sum0[i][1] + sum0[i + 1][1] + sum1[i][1] + sum1[i + 1][1],
217 sum0[i][2] + sum0[i + 1][2] + sum1[i][2] + sum1[i + 1][2],
218 sum0[i][3] + sum0[i + 1][3] + sum1[i][3] + sum1[i + 1][3]);
222 #define SUM_LEN(w) (((w) >> 2) + 3)
224 static double ssim_plane_16bit(SSIMDSPContext *dsp,
225 uint8_t *main, int main_stride,
226 uint8_t *ref, int ref_stride,
227 int width, int height, void *temp,
232 int64_t (*sum0)[4] = temp;
233 int64_t (*sum1)[4] = sum0 + SUM_LEN(width);
238 for (y = 1; y < height; y++) {
239 for (; z <= y; z++) {
240 FFSWAP(void*, sum0, sum1);
241 ssim_4x4xn_16bit(&main[4 * z * main_stride], main_stride,
242 &ref[4 * z * ref_stride], ref_stride,
246 ssim += ssim_endn_16bit((const int64_t (*)[4])sum0, (const int64_t (*)[4])sum1, width - 1, max);
249 return ssim / ((height - 1) * (width - 1));
252 static double ssim_plane(SSIMDSPContext *dsp,
253 uint8_t *main, int main_stride,
254 uint8_t *ref, int ref_stride,
255 int width, int height, void *temp,
260 int (*sum0)[4] = temp;
261 int (*sum1)[4] = sum0 + SUM_LEN(width);
266 for (y = 1; y < height; y++) {
267 for (; z <= y; z++) {
268 FFSWAP(void*, sum0, sum1);
269 dsp->ssim_4x4_line(&main[4 * z * main_stride], main_stride,
270 &ref[4 * z * ref_stride], ref_stride,
274 ssim += dsp->ssim_end_line((const int (*)[4])sum0, (const int (*)[4])sum1, width - 1);
277 return ssim / ((height - 1) * (width - 1));
280 static double ssim_db(double ssim, double weight)
282 return (fabs(weight - ssim) > 1e-9) ? 10.0 * log10(weight / (weight - ssim)) : INFINITY;
285 static int do_ssim(FFFrameSync *fs)
287 AVFilterContext *ctx = fs->parent;
288 SSIMContext *s = ctx->priv;
289 AVFrame *master, *ref;
290 AVDictionary **metadata;
291 double c[4] = { 0 }, ssimv = 0.0;
294 ret = ff_framesync_dualinput_get(fs, &master, &ref);
297 if (ctx->is_disabled || !ref)
298 return ff_filter_frame(ctx->outputs[0], master);
299 metadata = &master->metadata;
303 for (i = 0; i < s->nb_components; i++) {
304 c[i] = s->ssim_plane(&s->dsp, master->data[i], master->linesize[i],
305 ref->data[i], ref->linesize[i],
306 s->planewidth[i], s->planeheight[i], s->temp,
308 ssimv += s->coefs[i] * c[i];
311 for (i = 0; i < s->nb_components; i++) {
312 int cidx = s->is_rgb ? s->rgba_map[i] : i;
313 set_meta(metadata, "lavfi.ssim.", s->comps[i], c[cidx]);
315 s->ssim_total += ssimv;
317 set_meta(metadata, "lavfi.ssim.All", 0, ssimv);
318 set_meta(metadata, "lavfi.ssim.dB", 0, ssim_db(ssimv, 1.0));
321 fprintf(s->stats_file, "n:%"PRId64" ", s->nb_frames);
323 for (i = 0; i < s->nb_components; i++) {
324 int cidx = s->is_rgb ? s->rgba_map[i] : i;
325 fprintf(s->stats_file, "%c:%f ", s->comps[i], c[cidx]);
328 fprintf(s->stats_file, "All:%f (%f)\n", ssimv, ssim_db(ssimv, 1.0));
331 return ff_filter_frame(ctx->outputs[0], master);
334 static av_cold int init(AVFilterContext *ctx)
336 SSIMContext *s = ctx->priv;
338 if (s->stats_file_str) {
339 if (!strcmp(s->stats_file_str, "-")) {
340 s->stats_file = stdout;
342 s->stats_file = fopen(s->stats_file_str, "w");
343 if (!s->stats_file) {
344 int err = AVERROR(errno);
346 av_strerror(err, buf, sizeof(buf));
347 av_log(ctx, AV_LOG_ERROR, "Could not open stats file %s: %s\n",
348 s->stats_file_str, buf);
354 s->fs.on_event = do_ssim;
358 static int query_formats(AVFilterContext *ctx)
360 static const enum AVPixelFormat pix_fmts[] = {
361 AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY9, AV_PIX_FMT_GRAY10,
362 AV_PIX_FMT_GRAY12, AV_PIX_FMT_GRAY14, AV_PIX_FMT_GRAY16,
363 AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P,
364 AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUV411P, AV_PIX_FMT_YUV410P,
365 AV_PIX_FMT_YUVJ411P, AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P,
366 AV_PIX_FMT_YUVJ440P, AV_PIX_FMT_YUVJ444P,
368 #define PF(suf) AV_PIX_FMT_YUV420##suf, AV_PIX_FMT_YUV422##suf, AV_PIX_FMT_YUV444##suf, AV_PIX_FMT_GBR##suf
369 PF(P9), PF(P10), PF(P12), PF(P14), PF(P16),
373 AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
375 return AVERROR(ENOMEM);
376 return ff_set_common_formats(ctx, fmts_list);
379 static int config_input_ref(AVFilterLink *inlink)
381 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
382 AVFilterContext *ctx = inlink->dst;
383 SSIMContext *s = ctx->priv;
386 s->nb_components = desc->nb_components;
388 if (ctx->inputs[0]->w != ctx->inputs[1]->w ||
389 ctx->inputs[0]->h != ctx->inputs[1]->h) {
390 av_log(ctx, AV_LOG_ERROR, "Width and height of input videos must be same.\n");
391 return AVERROR(EINVAL);
393 if (ctx->inputs[0]->format != ctx->inputs[1]->format) {
394 av_log(ctx, AV_LOG_ERROR, "Inputs must be of same pixel format.\n");
395 return AVERROR(EINVAL);
398 s->is_rgb = ff_fill_rgba_map(s->rgba_map, inlink->format) >= 0;
399 s->comps[0] = s->is_rgb ? 'R' : 'Y';
400 s->comps[1] = s->is_rgb ? 'G' : 'U';
401 s->comps[2] = s->is_rgb ? 'B' : 'V';
404 s->planeheight[1] = s->planeheight[2] = AV_CEIL_RSHIFT(inlink->h, desc->log2_chroma_h);
405 s->planeheight[0] = s->planeheight[3] = inlink->h;
406 s->planewidth[1] = s->planewidth[2] = AV_CEIL_RSHIFT(inlink->w, desc->log2_chroma_w);
407 s->planewidth[0] = s->planewidth[3] = inlink->w;
408 for (i = 0; i < s->nb_components; i++)
409 sum += s->planeheight[i] * s->planewidth[i];
410 for (i = 0; i < s->nb_components; i++)
411 s->coefs[i] = (double) s->planeheight[i] * s->planewidth[i] / sum;
413 s->temp = av_mallocz_array(2 * SUM_LEN(inlink->w), (desc->comp[0].depth > 8) ? sizeof(int64_t[4]) : sizeof(int[4]));
415 return AVERROR(ENOMEM);
416 s->max = (1 << desc->comp[0].depth) - 1;
418 s->ssim_plane = desc->comp[0].depth > 8 ? ssim_plane_16bit : ssim_plane;
419 s->dsp.ssim_4x4_line = ssim_4x4xn_8bit;
420 s->dsp.ssim_end_line = ssim_endn_8bit;
422 ff_ssim_init_x86(&s->dsp);
427 static int config_output(AVFilterLink *outlink)
429 AVFilterContext *ctx = outlink->src;
430 SSIMContext *s = ctx->priv;
431 AVFilterLink *mainlink = ctx->inputs[0];
434 ret = ff_framesync_init_dualinput(&s->fs, ctx);
437 outlink->w = mainlink->w;
438 outlink->h = mainlink->h;
439 outlink->time_base = mainlink->time_base;
440 outlink->sample_aspect_ratio = mainlink->sample_aspect_ratio;
441 outlink->frame_rate = mainlink->frame_rate;
443 if ((ret = ff_framesync_configure(&s->fs)) < 0)
446 outlink->time_base = s->fs.time_base;
448 if (av_cmp_q(mainlink->time_base, outlink->time_base) ||
449 av_cmp_q(ctx->inputs[1]->time_base, outlink->time_base))
450 av_log(ctx, AV_LOG_WARNING, "not matching timebases found between first input: %d/%d and second input %d/%d, results may be incorrect!\n",
451 mainlink->time_base.num, mainlink->time_base.den,
452 ctx->inputs[1]->time_base.num, ctx->inputs[1]->time_base.den);
457 static int activate(AVFilterContext *ctx)
459 SSIMContext *s = ctx->priv;
460 return ff_framesync_activate(&s->fs);
463 static av_cold void uninit(AVFilterContext *ctx)
465 SSIMContext *s = ctx->priv;
467 if (s->nb_frames > 0) {
471 for (i = 0; i < s->nb_components; i++) {
472 int c = s->is_rgb ? s->rgba_map[i] : i;
473 av_strlcatf(buf, sizeof(buf), " %c:%f (%f)", s->comps[i], s->ssim[c] / s->nb_frames,
474 ssim_db(s->ssim[c], s->nb_frames));
476 av_log(ctx, AV_LOG_INFO, "SSIM%s All:%f (%f)\n", buf,
477 s->ssim_total / s->nb_frames, ssim_db(s->ssim_total, s->nb_frames));
480 ff_framesync_uninit(&s->fs);
482 if (s->stats_file && s->stats_file != stdout)
483 fclose(s->stats_file);
488 static const AVFilterPad ssim_inputs[] = {
491 .type = AVMEDIA_TYPE_VIDEO,
494 .type = AVMEDIA_TYPE_VIDEO,
495 .config_props = config_input_ref,
500 static const AVFilterPad ssim_outputs[] = {
503 .type = AVMEDIA_TYPE_VIDEO,
504 .config_props = config_output,
509 AVFilter ff_vf_ssim = {
511 .description = NULL_IF_CONFIG_SMALL("Calculate the SSIM between two video streams."),
512 .preinit = ssim_framesync_preinit,
515 .query_formats = query_formats,
516 .activate = activate,
517 .priv_size = sizeof(SSIMContext),
518 .priv_class = &ssim_class,
519 .inputs = ssim_inputs,
520 .outputs = ssim_outputs,
521 .flags = AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL,