xref: /aosp_15_r20/external/webp/extras/get_disto.c (revision b2055c353e87c8814eb2b6b1b11112a1562253bd)
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 ([email protected])
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           "\nSupported input formats:\n  %s\n",
227           WebPGetEnabledInputFileFormats());
228 }
229 
main(int argc,const char * argv[])230 int main(int argc, const char* argv[]) {
231   WebPPicture pic1, pic2;
232   size_t size1 = 0, size2 = 0;
233   int ret = 1;
234   float disto[5];
235   int type = 0;
236   int c;
237   int help = 0;
238   int keep_alpha = 0;
239   int scale = 0;
240   int use_gray = 0;
241   const char* name1 = NULL;
242   const char* name2 = NULL;
243   const char* output = NULL;
244 
245   INIT_WARGV(argc, argv);
246 
247   if (!WebPPictureInit(&pic1) || !WebPPictureInit(&pic2)) {
248     fprintf(stderr, "Can't init pictures\n");
249     FREE_WARGV_AND_RETURN(1);
250   }
251 
252   for (c = 1; c < argc; ++c) {
253     if (!strcmp(argv[c], "-ssim")) {
254       type = 1;
255     } else if (!strcmp(argv[c], "-psnr")) {
256       type = 0;
257     } else if (!strcmp(argv[c], "-alpha")) {
258       keep_alpha = 1;
259     } else if (!strcmp(argv[c], "-scale")) {
260       scale = 1;
261     } else if (!strcmp(argv[c], "-gray")) {
262       use_gray = 1;
263     } else if (!strcmp(argv[c], "-h")) {
264       help = 1;
265       ret = 0;
266     } else if (!strcmp(argv[c], "-o")) {
267       if (++c == argc) {
268         fprintf(stderr, "missing file name after %s option.\n", argv[c - 1]);
269         goto End;
270       }
271       output = (const char*)GET_WARGV(argv, c);
272     } else if (name1 == NULL) {
273       name1 = (const char*)GET_WARGV(argv, c);
274     } else {
275       name2 = (const char*)GET_WARGV(argv, c);
276     }
277   }
278   if (help || name1 == NULL || name2 == NULL) {
279     if (!help) {
280       fprintf(stderr, "Error: missing arguments.\n");
281     }
282     Help();
283     goto End;
284   }
285   size1 = ReadPicture(name1, &pic1, 1);
286   size2 = ReadPicture(name2, &pic2, 1);
287   if (size1 == 0 || size2 == 0) goto End;
288 
289   if (!keep_alpha) {
290     WebPBlendAlpha(&pic1, 0x00000000);
291     WebPBlendAlpha(&pic2, 0x00000000);
292   }
293 
294   if (!WebPPictureDistortion(&pic1, &pic2, type, disto)) {
295     fprintf(stderr, "Error while computing the distortion.\n");
296     goto End;
297   }
298   printf("%u %.2f    %.2f %.2f %.2f %.2f [ %.2f bpp ]\n",
299          (unsigned int)size1,
300          disto[4], disto[0], disto[1], disto[2], disto[3],
301          8.f * size1 / pic1.width / pic1.height);
302 
303   if (output != NULL) {
304     uint8_t* data = NULL;
305     size_t data_size = 0;
306     if (pic1.use_argb != pic2.use_argb) {
307       fprintf(stderr, "Pictures are not in the same argb format. "
308                       "Can't save the difference map.\n");
309       goto End;
310     }
311     if (pic1.use_argb) {
312       int n;
313       fprintf(stderr, "max differences per channel: ");
314       for (n = 0; n < 3; ++n) {    // skip the alpha channel
315         const int range = (type == 1) ?
316           SSIMScaleChannel((uint8_t*)pic1.argb + n, pic1.argb_stride * 4,
317                            (const uint8_t*)pic2.argb + n, pic2.argb_stride * 4,
318                            4, pic1.width, pic1.height, scale) :
319           DiffScaleChannel((uint8_t*)pic1.argb + n, pic1.argb_stride * 4,
320                            (const uint8_t*)pic2.argb + n, pic2.argb_stride * 4,
321                            4, pic1.width, pic1.height, scale);
322         if (range < 0) fprintf(stderr, "\nError computing diff map\n");
323         fprintf(stderr, "[%d]", range);
324       }
325       fprintf(stderr, "\n");
326       if (use_gray) ConvertToGray(&pic1);
327     } else {
328       fprintf(stderr, "Can only compute the difference map in ARGB format.\n");
329       goto End;
330     }
331 #if !defined(WEBP_REDUCE_CSP)
332     data_size = WebPEncodeLosslessBGRA((const uint8_t*)pic1.argb,
333                                        pic1.width, pic1.height,
334                                        pic1.argb_stride * 4,
335                                        &data);
336     if (data_size == 0) {
337       fprintf(stderr, "Error during lossless encoding.\n");
338       goto End;
339     }
340     ret = ImgIoUtilWriteFile(output, data, data_size) ? 0 : 1;
341     WebPFree(data);
342     if (ret) goto End;
343 #else
344     (void)data;
345     (void)data_size;
346     fprintf(stderr, "Cannot save the difference map. Please recompile "
347                     "without the WEBP_REDUCE_CSP flag.\n");
348 #endif  // WEBP_REDUCE_CSP
349   }
350   ret = 0;
351 
352  End:
353   WebPPictureFree(&pic1);
354   WebPPictureFree(&pic2);
355   FREE_WARGV_AND_RETURN(ret);
356 }
357