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 {
57 double ssim[4], ssim_total;
66 int (*ssim_plane)(AVFilterContext *ctx, void *arg,
67 int jobnr, int nb_jobs);
71 #define OFFSET(x) offsetof(SSIMContext, x)
72 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
74 static const AVOption ssim_options[] = {
75 {"stats_file", "Set file where to store per-frame difference information", OFFSET(stats_file_str), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, FLAGS },
76 {"f", "Set file where to store per-frame difference information", OFFSET(stats_file_str), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, FLAGS },
80 FRAMESYNC_DEFINE_CLASS(ssim, SSIMContext, fs);
82 static void set_meta(AVDictionary **metadata, const char *key, char comp, float d)
85 snprintf(value, sizeof(value), "%f", d);
88 snprintf(key2, sizeof(key2), "%s%c", key, comp);
89 av_dict_set(metadata, key2, value, 0);
91 av_dict_set(metadata, key, value, 0);
95 static void ssim_4x4xn_16bit(const uint8_t *main8, ptrdiff_t main_stride,
96 const uint8_t *ref8, ptrdiff_t ref_stride,
97 int64_t (*sums)[4], int width)
99 const uint16_t *main16 = (const uint16_t *)main8;
100 const uint16_t *ref16 = (const uint16_t *)ref8;
106 for (z = 0; z < width; z++) {
107 uint64_t s1 = 0, s2 = 0, ss = 0, s12 = 0;
109 for (y = 0; y < 4; y++) {
110 for (x = 0; x < 4; x++) {
111 unsigned a = main16[x + y * main_stride];
112 unsigned b = ref16[x + y * ref_stride];
131 static void ssim_4x4xn_8bit(const uint8_t *main, ptrdiff_t main_stride,
132 const uint8_t *ref, ptrdiff_t ref_stride,
133 int (*sums)[4], int width)
137 for (z = 0; z < width; z++) {
138 uint32_t s1 = 0, s2 = 0, ss = 0, s12 = 0;
140 for (y = 0; y < 4; y++) {
141 for (x = 0; x < 4; x++) {
142 int a = main[x + y * main_stride];
143 int b = ref[x + y * ref_stride];
162 static float ssim_end1x(int64_t s1, int64_t s2, int64_t ss, int64_t s12, int max)
164 int64_t ssim_c1 = (int64_t)(.01*.01*max*max*64 + .5);
165 int64_t ssim_c2 = (int64_t)(.03*.03*max*max*64*63 + .5);
171 int64_t vars = fss * 64 - fs1 * fs1 - fs2 * fs2;
172 int64_t covar = fs12 * 64 - fs1 * fs2;
174 return (float)(2 * fs1 * fs2 + ssim_c1) * (float)(2 * covar + ssim_c2)
175 / ((float)(fs1 * fs1 + fs2 * fs2 + ssim_c1) * (float)(vars + ssim_c2));
178 static float ssim_end1(int s1, int s2, int ss, int s12)
180 static const int ssim_c1 = (int)(.01*.01*255*255*64 + .5);
181 static const int ssim_c2 = (int)(.03*.03*255*255*64*63 + .5);
187 int vars = fss * 64 - fs1 * fs1 - fs2 * fs2;
188 int covar = fs12 * 64 - fs1 * fs2;
190 return (float)(2 * fs1 * fs2 + ssim_c1) * (float)(2 * covar + ssim_c2)
191 / ((float)(fs1 * fs1 + fs2 * fs2 + ssim_c1) * (float)(vars + ssim_c2));
194 static float ssim_endn_16bit(const int64_t (*sum0)[4], const int64_t (*sum1)[4], int width, int max)
199 for (i = 0; i < width; i++)
200 ssim += ssim_end1x(sum0[i][0] + sum0[i + 1][0] + sum1[i][0] + sum1[i + 1][0],
201 sum0[i][1] + sum0[i + 1][1] + sum1[i][1] + sum1[i + 1][1],
202 sum0[i][2] + sum0[i + 1][2] + sum1[i][2] + sum1[i + 1][2],
203 sum0[i][3] + sum0[i + 1][3] + sum1[i][3] + sum1[i + 1][3],
208 static double ssim_endn_8bit(const int (*sum0)[4], const int (*sum1)[4], int width)
213 for (i = 0; i < width; i++)
214 ssim += ssim_end1(sum0[i][0] + sum0[i + 1][0] + sum1[i][0] + sum1[i + 1][0],
215 sum0[i][1] + sum0[i + 1][1] + sum1[i][1] + sum1[i + 1][1],
216 sum0[i][2] + sum0[i + 1][2] + sum1[i][2] + sum1[i + 1][2],
217 sum0[i][3] + sum0[i + 1][3] + sum1[i][3] + sum1[i + 1][3]);
221 #define SUM_LEN(w) (((w) >> 2) + 3)
223 typedef struct ThreadData {
224 const uint8_t *main_data[4];
225 const uint8_t *ref_data[4];
226 int main_linesize[4];
237 static int ssim_plane_16bit(AVFilterContext *ctx, void *arg,
238 int jobnr, int nb_jobs)
240 ThreadData *td = arg;
241 double *score = td->score[jobnr];
242 void *temp = td->temp[jobnr];
243 const int max = td->max;
245 for (int c = 0; c < td->nb_components; c++) {
246 const uint8_t *main_data = td->main_data[c];
247 const uint8_t *ref_data = td->ref_data[c];
248 const int main_stride = td->main_linesize[c];
249 const int ref_stride = td->ref_linesize[c];
250 int width = td->planewidth[c];
251 int height = td->planeheight[c];
252 const int slice_start = ((height >> 2) * jobnr) / nb_jobs;
253 const int slice_end = ((height >> 2) * (jobnr+1)) / nb_jobs;
254 const int ystart = FFMAX(1, slice_start);
257 int64_t (*sum0)[4] = temp;
258 int64_t (*sum1)[4] = sum0 + SUM_LEN(width);
263 for (int y = ystart; y < slice_end; y++) {
264 for (; z <= y; z++) {
265 FFSWAP(void*, sum0, sum1);
266 ssim_4x4xn_16bit(&main_data[4 * z * main_stride], main_stride,
267 &ref_data[4 * z * ref_stride], ref_stride,
271 ssim += ssim_endn_16bit((const int64_t (*)[4])sum0, (const int64_t (*)[4])sum1, width - 1, max);
280 static int ssim_plane(AVFilterContext *ctx, void *arg,
281 int jobnr, int nb_jobs)
283 ThreadData *td = arg;
284 double *score = td->score[jobnr];
285 void *temp = td->temp[jobnr];
286 SSIMDSPContext *dsp = td->dsp;
288 for (int c = 0; c < td->nb_components; c++) {
289 const uint8_t *main_data = td->main_data[c];
290 const uint8_t *ref_data = td->ref_data[c];
291 const int main_stride = td->main_linesize[c];
292 const int ref_stride = td->ref_linesize[c];
293 int width = td->planewidth[c];
294 int height = td->planeheight[c];
295 const int slice_start = ((height >> 2) * jobnr) / nb_jobs;
296 const int slice_end = ((height >> 2) * (jobnr+1)) / nb_jobs;
297 const int ystart = FFMAX(1, slice_start);
300 int (*sum0)[4] = temp;
301 int (*sum1)[4] = sum0 + SUM_LEN(width);
306 for (int y = ystart; y < slice_end; y++) {
307 for (; z <= y; z++) {
308 FFSWAP(void*, sum0, sum1);
309 dsp->ssim_4x4_line(&main_data[4 * z * main_stride], main_stride,
310 &ref_data[4 * z * ref_stride], ref_stride,
314 ssim += dsp->ssim_end_line((const int (*)[4])sum0, (const int (*)[4])sum1, width - 1);
323 static double ssim_db(double ssim, double weight)
325 return (fabs(weight - ssim) > 1e-9) ? 10.0 * log10(weight / (weight - ssim)) : INFINITY;
328 static int do_ssim(FFFrameSync *fs)
330 AVFilterContext *ctx = fs->parent;
331 SSIMContext *s = ctx->priv;
332 AVFrame *master, *ref;
333 AVDictionary **metadata;
334 double c[4] = {0}, ssimv = 0.0;
338 ret = ff_framesync_dualinput_get(fs, &master, &ref);
341 if (ctx->is_disabled || !ref)
342 return ff_filter_frame(ctx->outputs[0], master);
343 metadata = &master->metadata;
347 td.nb_components = s->nb_components;
353 for (int n = 0; n < s->nb_components; n++) {
354 td.main_data[n] = master->data[n];
355 td.ref_data[n] = ref->data[n];
356 td.main_linesize[n] = master->linesize[n];
357 td.ref_linesize[n] = ref->linesize[n];
358 td.planewidth[n] = s->planewidth[n];
359 td.planeheight[n] = s->planeheight[n];
362 ctx->internal->execute(ctx, s->ssim_plane, &td, NULL, FFMIN((s->planeheight[1] + 3) >> 2, s->nb_threads));
364 for (i = 0; i < s->nb_components; i++) {
365 for (int j = 0; j < s->nb_threads; j++)
366 c[i] += s->score[j][i];
367 c[i] = c[i] / (((s->planewidth[i] >> 2) - 1) * ((s->planeheight[i] >> 2) - 1));
370 for (i = 0; i < s->nb_components; i++) {
371 ssimv += s->coefs[i] * c[i];
375 for (i = 0; i < s->nb_components; i++) {
376 int cidx = s->is_rgb ? s->rgba_map[i] : i;
377 set_meta(metadata, "lavfi.ssim.", s->comps[i], c[cidx]);
379 s->ssim_total += ssimv;
381 set_meta(metadata, "lavfi.ssim.All", 0, ssimv);
382 set_meta(metadata, "lavfi.ssim.dB", 0, ssim_db(ssimv, 1.0));
385 fprintf(s->stats_file, "n:%"PRId64" ", s->nb_frames);
387 for (i = 0; i < s->nb_components; i++) {
388 int cidx = s->is_rgb ? s->rgba_map[i] : i;
389 fprintf(s->stats_file, "%c:%f ", s->comps[i], c[cidx]);
392 fprintf(s->stats_file, "All:%f (%f)\n", ssimv, ssim_db(ssimv, 1.0));
395 return ff_filter_frame(ctx->outputs[0], master);
398 static av_cold int init(AVFilterContext *ctx)
400 SSIMContext *s = ctx->priv;
402 if (s->stats_file_str) {
403 if (!strcmp(s->stats_file_str, "-")) {
404 s->stats_file = stdout;
406 s->stats_file = fopen(s->stats_file_str, "w");
407 if (!s->stats_file) {
408 int err = AVERROR(errno);
410 av_strerror(err, buf, sizeof(buf));
411 av_log(ctx, AV_LOG_ERROR, "Could not open stats file %s: %s\n",
412 s->stats_file_str, buf);
418 s->fs.on_event = do_ssim;
422 static int query_formats(AVFilterContext *ctx)
424 static const enum AVPixelFormat pix_fmts[] = {
425 AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY9, AV_PIX_FMT_GRAY10,
426 AV_PIX_FMT_GRAY12, AV_PIX_FMT_GRAY14, AV_PIX_FMT_GRAY16,
427 AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV444P,
428 AV_PIX_FMT_YUV440P, AV_PIX_FMT_YUV411P, AV_PIX_FMT_YUV410P,
429 AV_PIX_FMT_YUVJ411P, AV_PIX_FMT_YUVJ420P, AV_PIX_FMT_YUVJ422P,
430 AV_PIX_FMT_YUVJ440P, AV_PIX_FMT_YUVJ444P,
432 #define PF(suf) AV_PIX_FMT_YUV420##suf, AV_PIX_FMT_YUV422##suf, AV_PIX_FMT_YUV444##suf, AV_PIX_FMT_GBR##suf
433 PF(P9), PF(P10), PF(P12), PF(P14), PF(P16),
437 AVFilterFormats *fmts_list = ff_make_format_list(pix_fmts);
439 return AVERROR(ENOMEM);
440 return ff_set_common_formats(ctx, fmts_list);
443 static int config_input_ref(AVFilterLink *inlink)
445 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
446 AVFilterContext *ctx = inlink->dst;
447 SSIMContext *s = ctx->priv;
450 s->nb_threads = ff_filter_get_nb_threads(ctx);
451 s->nb_components = desc->nb_components;
453 if (ctx->inputs[0]->w != ctx->inputs[1]->w ||
454 ctx->inputs[0]->h != ctx->inputs[1]->h) {
455 av_log(ctx, AV_LOG_ERROR, "Width and height of input videos must be same.\n");
456 return AVERROR(EINVAL);
458 if (ctx->inputs[0]->format != ctx->inputs[1]->format) {
459 av_log(ctx, AV_LOG_ERROR, "Inputs must be of same pixel format.\n");
460 return AVERROR(EINVAL);
463 s->is_rgb = ff_fill_rgba_map(s->rgba_map, inlink->format) >= 0;
464 s->comps[0] = s->is_rgb ? 'R' : 'Y';
465 s->comps[1] = s->is_rgb ? 'G' : 'U';
466 s->comps[2] = s->is_rgb ? 'B' : 'V';
469 s->planeheight[1] = s->planeheight[2] = AV_CEIL_RSHIFT(inlink->h, desc->log2_chroma_h);
470 s->planeheight[0] = s->planeheight[3] = inlink->h;
471 s->planewidth[1] = s->planewidth[2] = AV_CEIL_RSHIFT(inlink->w, desc->log2_chroma_w);
472 s->planewidth[0] = s->planewidth[3] = inlink->w;
473 for (i = 0; i < s->nb_components; i++)
474 sum += s->planeheight[i] * s->planewidth[i];
475 for (i = 0; i < s->nb_components; i++)
476 s->coefs[i] = (double) s->planeheight[i] * s->planewidth[i] / sum;
478 s->temp = av_calloc(s->nb_threads, sizeof(*s->temp));
480 return AVERROR(ENOMEM);
482 for (int t = 0; t < s->nb_threads; t++) {
483 s->temp[t] = av_mallocz_array(2 * SUM_LEN(inlink->w), (desc->comp[0].depth > 8) ? sizeof(int64_t[4]) : sizeof(int[4]));
485 return AVERROR(ENOMEM);
487 s->max = (1 << desc->comp[0].depth) - 1;
489 s->ssim_plane = desc->comp[0].depth > 8 ? ssim_plane_16bit : ssim_plane;
490 s->dsp.ssim_4x4_line = ssim_4x4xn_8bit;
491 s->dsp.ssim_end_line = ssim_endn_8bit;
493 ff_ssim_init_x86(&s->dsp);
495 s->score = av_calloc(s->nb_threads, sizeof(*s->score));
497 return AVERROR(ENOMEM);
499 for (int t = 0; t < s->nb_threads && s->score; t++) {
500 s->score[t] = av_calloc(s->nb_components, sizeof(*s->score[0]));
502 return AVERROR(ENOMEM);
508 static int config_output(AVFilterLink *outlink)
510 AVFilterContext *ctx = outlink->src;
511 SSIMContext *s = ctx->priv;
512 AVFilterLink *mainlink = ctx->inputs[0];
515 ret = ff_framesync_init_dualinput(&s->fs, ctx);
518 outlink->w = mainlink->w;
519 outlink->h = mainlink->h;
520 outlink->time_base = mainlink->time_base;
521 outlink->sample_aspect_ratio = mainlink->sample_aspect_ratio;
522 outlink->frame_rate = mainlink->frame_rate;
524 if ((ret = ff_framesync_configure(&s->fs)) < 0)
527 outlink->time_base = s->fs.time_base;
529 if (av_cmp_q(mainlink->time_base, outlink->time_base) ||
530 av_cmp_q(ctx->inputs[1]->time_base, outlink->time_base))
531 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",
532 mainlink->time_base.num, mainlink->time_base.den,
533 ctx->inputs[1]->time_base.num, ctx->inputs[1]->time_base.den);
538 static int activate(AVFilterContext *ctx)
540 SSIMContext *s = ctx->priv;
541 return ff_framesync_activate(&s->fs);
544 static av_cold void uninit(AVFilterContext *ctx)
546 SSIMContext *s = ctx->priv;
548 if (s->nb_frames > 0) {
552 for (i = 0; i < s->nb_components; i++) {
553 int c = s->is_rgb ? s->rgba_map[i] : i;
554 av_strlcatf(buf, sizeof(buf), " %c:%f (%f)", s->comps[i], s->ssim[c] / s->nb_frames,
555 ssim_db(s->ssim[c], s->nb_frames));
557 av_log(ctx, AV_LOG_INFO, "SSIM%s All:%f (%f)\n", buf,
558 s->ssim_total / s->nb_frames, ssim_db(s->ssim_total, s->nb_frames));
561 ff_framesync_uninit(&s->fs);
563 if (s->stats_file && s->stats_file != stdout)
564 fclose(s->stats_file);
566 for (int t = 0; t < s->nb_threads && s->score; t++)
567 av_freep(&s->score[t]);
570 for (int t = 0; t < s->nb_threads && s->temp; t++)
571 av_freep(&s->temp[t]);
575 static const AVFilterPad ssim_inputs[] = {
578 .type = AVMEDIA_TYPE_VIDEO,
581 .type = AVMEDIA_TYPE_VIDEO,
582 .config_props = config_input_ref,
587 static const AVFilterPad ssim_outputs[] = {
590 .type = AVMEDIA_TYPE_VIDEO,
591 .config_props = config_output,
596 AVFilter ff_vf_ssim = {
598 .description = NULL_IF_CONFIG_SMALL("Calculate the SSIM between two video streams."),
599 .preinit = ssim_framesync_preinit,
602 .query_formats = query_formats,
603 .activate = activate,
604 .priv_size = sizeof(SSIMContext),
605 .priv_class = &ssim_class,
606 .inputs = ssim_inputs,
607 .outputs = ssim_outputs,
608 .flags = AVFILTER_FLAG_SUPPORT_TIMELINE_INTERNAL | AVFILTER_FLAG_SLICE_THREADS,