1 // Copyright 2016 Google Inc. All Rights Reserved.
2 //
3 // Use of this source code is governed by a BSD-style license
4 // that can be found in the COPYING file in the root of the source
5 // tree. An additional intellectual property rights grant can be found
6 // in the file PATENTS. All contributing project authors may
7 // be found in the AUTHORS file in the root of the source tree.
8 // -----------------------------------------------------------------------------
9 //
10 // Simple tool to load two webp/png/jpg/tiff files and compute PSNR/SSIM.
11 // This is mostly a wrapper around WebPPictureDistortion().
12 //
13 /*
14  gcc -o get_disto get_disto.c -O3 -I../ -L../examples -L../imageio \
15     -lexample_util -limageio_util -limagedec -lwebp -L/opt/local/lib \
16     -lpng -lz -ljpeg -ltiff -lm -lpthread
17 */
18 //
19 // Author: Skal (pascal.massimino@gmail.com)
20 
21 #include <assert.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 
26 #include "webp/encode.h"
27 #include "imageio/image_dec.h"
28 #include "imageio/imageio_util.h"
29 #include "../examples/unicode.h"
30 
ReadPicture(const char * const filename,WebPPicture * const pic,int keep_alpha)31 static size_t ReadPicture(const char* const filename, WebPPicture* const pic,
32                           int keep_alpha) {
33   const uint8_t* data = NULL;
34   size_t data_size = 0;
35   WebPImageReader reader = NULL;
36   int ok = ImgIoUtilReadFile(filename, &data, &data_size);
37   if (!ok) goto End;
38 
39   pic->use_argb = 1;  // force ARGB
40 
41 #ifdef HAVE_WINCODEC_H
42   // Try to decode the file using WIC falling back to the other readers for
43   // e.g., WebP.
44   ok = ReadPictureWithWIC(filename, pic, keep_alpha, NULL);
45   if (ok) goto End;
46 #endif
47   reader = WebPGuessImageReader(data, data_size);
48   ok = reader(data, data_size, pic, keep_alpha, NULL);
49 
50  End:
51   if (!ok) {
52     WFPRINTF(stderr, "Error! Could not process file %s\n",
53              (const W_CHAR*)filename);
54   }
55   free((void*)data);
56   return ok ? data_size : 0;
57 }
58 
RescalePlane(uint8_t * plane,int width,int height,int x_stride,int y_stride,int max)59 static void RescalePlane(uint8_t* plane, int width, int height,
60                          int x_stride, int y_stride, int max) {
61   const uint32_t factor = (max > 0) ? (255u << 16) / max : 0;
62   int x, y;
63   for (y = 0; y < height; ++y) {
64     uint8_t* const ptr = plane + y * y_stride;
65     for (x = 0; x < width * x_stride; x += x_stride) {
66       const uint32_t diff = (ptr[x] * factor + (1 << 15)) >> 16;
67       ptr[x] = diff;
68     }
69   }
70 }
71 
72 // Return the max absolute difference.
DiffScaleChannel(uint8_t * src1,int stride1,const uint8_t * src2,int stride2,int x_stride,int w,int h,int do_scaling)73 static int DiffScaleChannel(uint8_t* src1, int stride1,
74                             const uint8_t* src2, int stride2,
75                             int x_stride, int w, int h, int do_scaling) {
76   int x, y;
77   int max = 0;
78   for (y = 0; y < h; ++y) {
79     uint8_t* const ptr1 = src1 + y * stride1;
80     const uint8_t* const ptr2 = src2 + y * stride2;
81     for (x = 0; x < w * x_stride; x += x_stride) {
82       const int diff = abs(ptr1[x] - ptr2[x]);
83       if (diff > max) max = diff;
84       ptr1[x] = diff;
85     }
86   }
87 
88   if (do_scaling) RescalePlane(src1, w, h, x_stride, stride1, max);
89   return max;
90 }
91 
92 //------------------------------------------------------------------------------
93 // SSIM calculation. We re-implement these functions here, out of dsp/, to avoid
94 // breaking the library's hidden visibility. This code duplication avoids the
95 // bigger annoyance of having to open up internal details of libdsp...
96 
97 #define SSIM_KERNEL 3   // total size of the kernel: 2 * SSIM_KERNEL + 1
98 
99 // struct for accumulating statistical moments
100 typedef struct {
101   uint32_t w;              // sum(w_i) : sum of weights
102   uint32_t xm, ym;         // sum(w_i * x_i), sum(w_i * y_i)
103   uint32_t xxm, xym, yym;  // sum(w_i * x_i * x_i), etc.
104 } DistoStats;
105 
106 // hat-shaped filter. Sum of coefficients is equal to 16.
107 static const uint32_t kWeight[2 * SSIM_KERNEL + 1] = { 1, 2, 3, 4, 3, 2, 1 };
108 
SSIMCalculation(const DistoStats * const stats)109 static WEBP_INLINE double SSIMCalculation(const DistoStats* const stats) {
110   const uint32_t N = stats->w;
111   const uint32_t w2 =  N * N;
112   const uint32_t C1 = 20 * w2;
113   const uint32_t C2 = 60 * w2;
114   const uint32_t C3 = 8 * 8 * w2;   // 'dark' limit ~= 6
115   const uint64_t xmxm = (uint64_t)stats->xm * stats->xm;
116   const uint64_t ymym = (uint64_t)stats->ym * stats->ym;
117   if (xmxm + ymym >= C3) {
118     const int64_t xmym = (int64_t)stats->xm * stats->ym;
119     const int64_t sxy = (int64_t)stats->xym * N - xmym;    // can be negative
120     const uint64_t sxx = (uint64_t)stats->xxm * N - xmxm;
121     const uint64_t syy = (uint64_t)stats->yym * N - ymym;
122     // we descale by 8 to prevent overflow during the fnum/fden multiply.
123     const uint64_t num_S = (2 * (uint64_t)(sxy < 0 ? 0 : sxy) + C2) >> 8;
124     const uint64_t den_S = (sxx + syy + C2) >> 8;
125     const uint64_t fnum = (2 * xmym + C1) * num_S;
126     const uint64_t fden = (xmxm + ymym + C1) * den_S;
127     const double r = (double)fnum / fden;
128     assert(r >= 0. && r <= 1.0);
129     return r;
130   }
131   return 1.;   // area is too dark to contribute meaningfully
132 }
133 
SSIMGetClipped(const uint8_t * src1,int stride1,const uint8_t * src2,int stride2,int xo,int yo,int W,int H)134 static double SSIMGetClipped(const uint8_t* src1, int stride1,
135                              const uint8_t* src2, int stride2,
136                              int xo, int yo, int W, int H) {
137   DistoStats stats = { 0, 0, 0, 0, 0, 0 };
138   const int ymin = (yo - SSIM_KERNEL < 0) ? 0 : yo - SSIM_KERNEL;
139   const int ymax = (yo + SSIM_KERNEL > H - 1) ? H - 1 : yo + SSIM_KERNEL;
140   const int xmin = (xo - SSIM_KERNEL < 0) ? 0 : xo - SSIM_KERNEL;
141   const int xmax = (xo + SSIM_KERNEL > W - 1) ? W - 1 : xo + SSIM_KERNEL;
142   int x, y;
143   src1 += ymin * stride1;
144   src2 += ymin * stride2;
145   for (y = ymin; y <= ymax; ++y, src1 += stride1, src2 += stride2) {
146     for (x = xmin; x <= xmax; ++x) {
147       const uint32_t w = kWeight[SSIM_KERNEL + x - xo]
148                        * kWeight[SSIM_KERNEL + y - yo];
149       const uint32_t s1 = src1[x];
150       const uint32_t s2 = src2[x];
151       stats.w   += w;
152       stats.xm  += w * s1;
153       stats.ym  += w * s2;
154       stats.xxm += w * s1 * s1;
155       stats.xym += w * s1 * s2;
156       stats.yym += w * s2 * s2;
157     }
158   }
159   return SSIMCalculation(&stats);
160 }
161 
162 // Compute SSIM-score map. Return -1 in case of error, max diff otherwise.
SSIMScaleChannel(uint8_t * src1,int stride1,const uint8_t * src2,int stride2,int x_stride,int w,int h,int do_scaling)163 static int SSIMScaleChannel(uint8_t* src1, int stride1,
164                             const uint8_t* src2, int stride2,
165                             int x_stride, int w, int h, int do_scaling) {
166   int x, y;
167   int max = 0;
168   uint8_t* const plane1 = (uint8_t*)malloc(2 * w * h * sizeof(*plane1));
169   uint8_t* const plane2 = plane1 + w * h;
170   if (plane1 == NULL) return -1;
171 
172   // extract plane
173   for (y = 0; y < h; ++y) {
174     for (x = 0; x < w; ++x) {
175       plane1[x + y * w] = src1[x * x_stride + y * stride1];
176       plane2[x + y * w] = src2[x * x_stride + y * stride2];
177     }
178   }
179   for (y = 0; y < h; ++y) {
180     for (x = 0; x < w; ++x) {
181       const double ssim = SSIMGetClipped(plane1, w, plane2, w, x, y, w, h);
182       int diff = (int)(255 * (1. - ssim));
183       if (diff < 0) {
184         diff = 0;
185       } else if (diff > max) {
186         max = diff;
187       }
188       src1[x * x_stride + y * stride1] = (diff > 255) ? 255u : (uint8_t)diff;
189     }
190   }
191   free(plane1);
192 
193   if (do_scaling) RescalePlane(src1, w, h, x_stride, stride1, max);
194   return max;
195 }
196 
197 // Convert an argb picture to luminance.
ConvertToGray(WebPPicture * const pic)198 static void ConvertToGray(WebPPicture* const pic) {
199   int x, y;
200   assert(pic != NULL);
201   assert(pic->use_argb);
202   for (y = 0; y < pic->height; ++y) {
203     uint32_t* const row = &pic->argb[y * pic->argb_stride];
204     for (x = 0; x < pic->width; ++x) {
205       const uint32_t argb = row[x];
206       const uint32_t r = (argb >> 16) & 0xff;
207       const uint32_t g = (argb >>  8) & 0xff;
208       const uint32_t b = (argb >>  0) & 0xff;
209       // We use BT.709 for converting to luminance.
210       const uint32_t Y = (uint32_t)(0.2126 * r + 0.7152 * g + 0.0722 * b + .5);
211       row[x] = (argb & 0xff000000u) | (Y * 0x010101u);
212     }
213   }
214 }
215 
Help(void)216 static void Help(void) {
217   fprintf(stderr,
218           "Usage: get_disto [-ssim][-psnr][-alpha] compressed.webp orig.webp\n"
219           "  -ssim ..... print SSIM distortion\n"
220           "  -psnr ..... print PSNR distortion (default)\n"
221           "  -alpha .... preserve alpha plane\n"
222           "  -h ........ this message\n"
223           "  -o <file> . save the diff map as a WebP lossless file\n"
224           "  -scale .... scale the difference map to fit [0..255] range\n"
225           "  -gray ..... use grayscale for difference map (-scale)\n"
226           " Also handles PNG, JPG and TIFF files, in addition to WebP.\n");
227 }
228 
main(int argc,const char * argv[])229 int main(int argc, const char* argv[]) {
230   WebPPicture pic1, pic2;
231   size_t size1 = 0, size2 = 0;
232   int ret = 1;
233   float disto[5];
234   int type = 0;
235   int c;
236   int help = 0;
237   int keep_alpha = 0;
238   int scale = 0;
239   int use_gray = 0;
240   const char* name1 = NULL;
241   const char* name2 = NULL;
242   const char* output = NULL;
243 
244   INIT_WARGV(argc, argv);
245 
246   if (!WebPPictureInit(&pic1) || !WebPPictureInit(&pic2)) {
247     fprintf(stderr, "Can't init pictures\n");
248     FREE_WARGV_AND_RETURN(1);
249   }
250 
251   for (c = 1; c < argc; ++c) {
252     if (!strcmp(argv[c], "-ssim")) {
253       type = 1;
254     } else if (!strcmp(argv[c], "-psnr")) {
255       type = 0;
256     } else if (!strcmp(argv[c], "-alpha")) {
257       keep_alpha = 1;
258     } else if (!strcmp(argv[c], "-scale")) {
259       scale = 1;
260     } else if (!strcmp(argv[c], "-gray")) {
261       use_gray = 1;
262     } else if (!strcmp(argv[c], "-h")) {
263       help = 1;
264       ret = 0;
265     } else if (!strcmp(argv[c], "-o")) {
266       if (++c == argc) {
267         fprintf(stderr, "missing file name after %s option.\n", argv[c - 1]);
268         goto End;
269       }
270       output = (const char*)GET_WARGV(argv, c);
271     } else if (name1 == NULL) {
272       name1 = (const char*)GET_WARGV(argv, c);
273     } else {
274       name2 = (const char*)GET_WARGV(argv, c);
275     }
276   }
277   if (help || name1 == NULL || name2 == NULL) {
278     if (!help) {
279       fprintf(stderr, "Error: missing arguments.\n");
280     }
281     Help();
282     goto End;
283   }
284   size1 = ReadPicture(name1, &pic1, 1);
285   size2 = ReadPicture(name2, &pic2, 1);
286   if (size1 == 0 || size2 == 0) goto End;
287 
288   if (!keep_alpha) {
289     WebPBlendAlpha(&pic1, 0x00000000);
290     WebPBlendAlpha(&pic2, 0x00000000);
291   }
292 
293   if (!WebPPictureDistortion(&pic1, &pic2, type, disto)) {
294     fprintf(stderr, "Error while computing the distortion.\n");
295     goto End;
296   }
297   printf("%u %.2f    %.2f %.2f %.2f %.2f [ %.2f bpp ]\n",
298          (unsigned int)size1,
299          disto[4], disto[0], disto[1], disto[2], disto[3],
300          8.f * size1 / pic1.width / pic1.height);
301 
302   if (output != NULL) {
303     uint8_t* data = NULL;
304     size_t data_size = 0;
305     if (pic1.use_argb != pic2.use_argb) {
306       fprintf(stderr, "Pictures are not in the same argb format. "
307                       "Can't save the difference map.\n");
308       goto End;
309     }
310     if (pic1.use_argb) {
311       int n;
312       fprintf(stderr, "max differences per channel: ");
313       for (n = 0; n < 3; ++n) {    // skip the alpha channel
314         const int range = (type == 1) ?
315           SSIMScaleChannel((uint8_t*)pic1.argb + n, pic1.argb_stride * 4,
316                            (const uint8_t*)pic2.argb + n, pic2.argb_stride * 4,
317                            4, pic1.width, pic1.height, scale) :
318           DiffScaleChannel((uint8_t*)pic1.argb + n, pic1.argb_stride * 4,
319                            (const uint8_t*)pic2.argb + n, pic2.argb_stride * 4,
320                            4, pic1.width, pic1.height, scale);
321         if (range < 0) fprintf(stderr, "\nError computing diff map\n");
322         fprintf(stderr, "[%d]", range);
323       }
324       fprintf(stderr, "\n");
325       if (use_gray) ConvertToGray(&pic1);
326     } else {
327       fprintf(stderr, "Can only compute the difference map in ARGB format.\n");
328       goto End;
329     }
330 #if !defined(WEBP_REDUCE_CSP)
331     data_size = WebPEncodeLosslessBGRA((const uint8_t*)pic1.argb,
332                                        pic1.width, pic1.height,
333                                        pic1.argb_stride * 4,
334                                        &data);
335     if (data_size == 0) {
336       fprintf(stderr, "Error during lossless encoding.\n");
337       goto End;
338     }
339     ret = ImgIoUtilWriteFile(output, data, data_size) ? 0 : 1;
340     WebPFree(data);
341     if (ret) goto End;
342 #else
343     (void)data;
344     (void)data_size;
345     fprintf(stderr, "Cannot save the difference map. Please recompile "
346                     "without the WEBP_REDUCE_CSP flag.\n");
347 #endif  // WEBP_REDUCE_CSP
348   }
349   ret = 0;
350 
351  End:
352   WebPPictureFree(&pic1);
353   WebPPictureFree(&pic2);
354   FREE_WARGV_AND_RETURN(ret);
355 }
356