vf_ssim.c 12 KB

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