xref: /aosp_15_r20/external/libvpx/vpx_dsp/ssim.c (revision fb1b10ab9aebc7c7068eedab379b749d7e3900be)
1 /*
2  *  Copyright (c) 2010 The WebM project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #include <assert.h>
12 #include <math.h>
13 #include "./vpx_dsp_rtcd.h"
14 #include "vpx_dsp/ssim.h"
15 #include "vpx_ports/mem.h"
16 #include "vpx_ports/system_state.h"
17 
vpx_ssim_parms_8x8_c(const uint8_t * s,int sp,const uint8_t * r,int rp,uint32_t * sum_s,uint32_t * sum_r,uint32_t * sum_sq_s,uint32_t * sum_sq_r,uint32_t * sum_sxr)18 void vpx_ssim_parms_8x8_c(const uint8_t *s, int sp, const uint8_t *r, int rp,
19                           uint32_t *sum_s, uint32_t *sum_r, uint32_t *sum_sq_s,
20                           uint32_t *sum_sq_r, uint32_t *sum_sxr) {
21   int i, j;
22   for (i = 0; i < 8; i++, s += sp, r += rp) {
23     for (j = 0; j < 8; j++) {
24       *sum_s += s[j];
25       *sum_r += r[j];
26       *sum_sq_s += s[j] * s[j];
27       *sum_sq_r += r[j] * r[j];
28       *sum_sxr += s[j] * r[j];
29     }
30   }
31 }
32 
33 #if CONFIG_VP9_HIGHBITDEPTH
vpx_highbd_ssim_parms_8x8_c(const uint16_t * s,int sp,const uint16_t * r,int rp,uint32_t * sum_s,uint32_t * sum_r,uint32_t * sum_sq_s,uint32_t * sum_sq_r,uint32_t * sum_sxr)34 void vpx_highbd_ssim_parms_8x8_c(const uint16_t *s, int sp, const uint16_t *r,
35                                  int rp, uint32_t *sum_s, uint32_t *sum_r,
36                                  uint32_t *sum_sq_s, uint32_t *sum_sq_r,
37                                  uint32_t *sum_sxr) {
38   int i, j;
39   for (i = 0; i < 8; i++, s += sp, r += rp) {
40     for (j = 0; j < 8; j++) {
41       *sum_s += s[j];
42       *sum_r += r[j];
43       *sum_sq_s += s[j] * s[j];
44       *sum_sq_r += r[j] * r[j];
45       *sum_sxr += s[j] * r[j];
46     }
47   }
48 }
49 #endif  // CONFIG_VP9_HIGHBITDEPTH
50 
51 static const int64_t cc1 = 26634;        // (64^2*(.01*255)^2
52 static const int64_t cc2 = 239708;       // (64^2*(.03*255)^2
53 static const int64_t cc1_10 = 428658;    // (64^2*(.01*1023)^2
54 static const int64_t cc2_10 = 3857925;   // (64^2*(.03*1023)^2
55 static const int64_t cc1_12 = 6868593;   // (64^2*(.01*4095)^2
56 static const int64_t cc2_12 = 61817334;  // (64^2*(.03*4095)^2
57 
similarity(uint32_t sum_s,uint32_t sum_r,uint32_t sum_sq_s,uint32_t sum_sq_r,uint32_t sum_sxr,int count,uint32_t bd)58 static double similarity(uint32_t sum_s, uint32_t sum_r, uint32_t sum_sq_s,
59                          uint32_t sum_sq_r, uint32_t sum_sxr, int count,
60                          uint32_t bd) {
61   double ssim_n, ssim_d;
62   int64_t c1, c2;
63   if (bd == 8) {
64     // scale the constants by number of pixels
65     c1 = (cc1 * count * count) >> 12;
66     c2 = (cc2 * count * count) >> 12;
67   } else if (bd == 10) {
68     c1 = (cc1_10 * count * count) >> 12;
69     c2 = (cc2_10 * count * count) >> 12;
70   } else if (bd == 12) {
71     c1 = (cc1_12 * count * count) >> 12;
72     c2 = (cc2_12 * count * count) >> 12;
73   } else {
74     c1 = c2 = 0;
75     assert(0);
76   }
77 
78   ssim_n = (2.0 * sum_s * sum_r + c1) *
79            (2.0 * count * sum_sxr - 2.0 * sum_s * sum_r + c2);
80 
81   ssim_d = ((double)sum_s * sum_s + (double)sum_r * sum_r + c1) *
82            ((double)count * sum_sq_s - (double)sum_s * sum_s +
83             (double)count * sum_sq_r - (double)sum_r * sum_r + c2);
84 
85   return ssim_n / ssim_d;
86 }
87 
ssim_8x8(const uint8_t * s,int sp,const uint8_t * r,int rp)88 static double ssim_8x8(const uint8_t *s, int sp, const uint8_t *r, int rp) {
89   uint32_t sum_s = 0, sum_r = 0, sum_sq_s = 0, sum_sq_r = 0, sum_sxr = 0;
90   vpx_ssim_parms_8x8(s, sp, r, rp, &sum_s, &sum_r, &sum_sq_s, &sum_sq_r,
91                      &sum_sxr);
92   return similarity(sum_s, sum_r, sum_sq_s, sum_sq_r, sum_sxr, 64, 8);
93 }
94 
95 #if CONFIG_VP9_HIGHBITDEPTH
highbd_ssim_8x8(const uint16_t * s,int sp,const uint16_t * r,int rp,uint32_t bd,uint32_t shift)96 static double highbd_ssim_8x8(const uint16_t *s, int sp, const uint16_t *r,
97                               int rp, uint32_t bd, uint32_t shift) {
98   uint32_t sum_s = 0, sum_r = 0, sum_sq_s = 0, sum_sq_r = 0, sum_sxr = 0;
99   vpx_highbd_ssim_parms_8x8(s, sp, r, rp, &sum_s, &sum_r, &sum_sq_s, &sum_sq_r,
100                             &sum_sxr);
101   return similarity(sum_s >> shift, sum_r >> shift, sum_sq_s >> (2 * shift),
102                     sum_sq_r >> (2 * shift), sum_sxr >> (2 * shift), 64, bd);
103 }
104 #endif  // CONFIG_VP9_HIGHBITDEPTH
105 
106 // We are using a 8x8 moving window with starting location of each 8x8 window
107 // on the 4x4 pixel grid. Such arrangement allows the windows to overlap
108 // block boundaries to penalize blocking artifacts.
vpx_ssim2(const uint8_t * img1,const uint8_t * img2,int stride_img1,int stride_img2,int width,int height)109 static double vpx_ssim2(const uint8_t *img1, const uint8_t *img2,
110                         int stride_img1, int stride_img2, int width,
111                         int height) {
112   int i, j;
113   int samples = 0;
114   double ssim_total = 0;
115 
116   // sample point start with each 4x4 location
117   for (i = 0; i <= height - 8;
118        i += 4, img1 += stride_img1 * 4, img2 += stride_img2 * 4) {
119     for (j = 0; j <= width - 8; j += 4) {
120       double v = ssim_8x8(img1 + j, stride_img1, img2 + j, stride_img2);
121       ssim_total += v;
122       samples++;
123     }
124   }
125   ssim_total /= samples;
126   return ssim_total;
127 }
128 
129 #if CONFIG_VP9_HIGHBITDEPTH
vpx_highbd_ssim2(const uint8_t * img1,const uint8_t * img2,int stride_img1,int stride_img2,int width,int height,uint32_t bd,uint32_t shift)130 static double vpx_highbd_ssim2(const uint8_t *img1, const uint8_t *img2,
131                                int stride_img1, int stride_img2, int width,
132                                int height, uint32_t bd, uint32_t shift) {
133   int i, j;
134   int samples = 0;
135   double ssim_total = 0;
136 
137   // sample point start with each 4x4 location
138   for (i = 0; i <= height - 8;
139        i += 4, img1 += stride_img1 * 4, img2 += stride_img2 * 4) {
140     for (j = 0; j <= width - 8; j += 4) {
141       double v = highbd_ssim_8x8(CONVERT_TO_SHORTPTR(img1 + j), stride_img1,
142                                  CONVERT_TO_SHORTPTR(img2 + j), stride_img2, bd,
143                                  shift);
144       ssim_total += v;
145       samples++;
146     }
147   }
148   ssim_total /= samples;
149   return ssim_total;
150 }
151 #endif  // CONFIG_VP9_HIGHBITDEPTH
152 
vpx_calc_ssim(const YV12_BUFFER_CONFIG * source,const YV12_BUFFER_CONFIG * dest,double * weight)153 double vpx_calc_ssim(const YV12_BUFFER_CONFIG *source,
154                      const YV12_BUFFER_CONFIG *dest, double *weight) {
155   double a, b, c;
156   double ssimv;
157 
158   a = vpx_ssim2(source->y_buffer, dest->y_buffer, source->y_stride,
159                 dest->y_stride, source->y_crop_width, source->y_crop_height);
160 
161   b = vpx_ssim2(source->u_buffer, dest->u_buffer, source->uv_stride,
162                 dest->uv_stride, source->uv_crop_width, source->uv_crop_height);
163 
164   c = vpx_ssim2(source->v_buffer, dest->v_buffer, source->uv_stride,
165                 dest->uv_stride, source->uv_crop_width, source->uv_crop_height);
166 
167   ssimv = a * .8 + .1 * (b + c);
168 
169   *weight = 1;
170 
171   return ssimv;
172 }
173 
174 // traditional ssim as per: http://en.wikipedia.org/wiki/Structural_similarity
175 //
176 // Re working out the math ->
177 //
178 // ssim(x,y) =  (2*mean(x)*mean(y) + c1)*(2*cov(x,y)+c2) /
179 //   ((mean(x)^2+mean(y)^2+c1)*(var(x)+var(y)+c2))
180 //
181 // mean(x) = sum(x) / n
182 //
183 // cov(x,y) = (n*sum(xi*yi)-sum(x)*sum(y))/(n*n)
184 //
185 // var(x) = (n*sum(xi*xi)-sum(xi)*sum(xi))/(n*n)
186 //
187 // ssim(x,y) =
188 //   (2*sum(x)*sum(y)/(n*n) + c1)*(2*(n*sum(xi*yi)-sum(x)*sum(y))/(n*n)+c2) /
189 //   (((sum(x)*sum(x)+sum(y)*sum(y))/(n*n) +c1) *
190 //    ((n*sum(xi*xi) - sum(xi)*sum(xi))/(n*n)+
191 //     (n*sum(yi*yi) - sum(yi)*sum(yi))/(n*n)+c2)))
192 //
193 // factoring out n*n
194 //
195 // ssim(x,y) =
196 //   (2*sum(x)*sum(y) + n*n*c1)*(2*(n*sum(xi*yi)-sum(x)*sum(y))+n*n*c2) /
197 //   (((sum(x)*sum(x)+sum(y)*sum(y)) + n*n*c1) *
198 //    (n*sum(xi*xi)-sum(xi)*sum(xi)+n*sum(yi*yi)-sum(yi)*sum(yi)+n*n*c2))
199 //
200 // Replace c1 with n*n * c1 for the final step that leads to this code:
201 // The final step scales by 12 bits so we don't lose precision in the constants.
202 
ssimv_similarity(const Ssimv * sv,int64_t n)203 static double ssimv_similarity(const Ssimv *sv, int64_t n) {
204   // Scale the constants by number of pixels.
205   const int64_t c1 = (cc1 * n * n) >> 12;
206   const int64_t c2 = (cc2 * n * n) >> 12;
207 
208   const double l = 1.0 * (2 * sv->sum_s * sv->sum_r + c1) /
209                    (sv->sum_s * sv->sum_s + sv->sum_r * sv->sum_r + c1);
210 
211   // Since these variables are unsigned sums, convert to double so
212   // math is done in double arithmetic.
213   const double v = (2.0 * n * sv->sum_sxr - 2 * sv->sum_s * sv->sum_r + c2) /
214                    (n * sv->sum_sq_s - sv->sum_s * sv->sum_s +
215                     n * sv->sum_sq_r - sv->sum_r * sv->sum_r + c2);
216 
217   return l * v;
218 }
219 
220 // The first term of the ssim metric is a luminance factor.
221 //
222 // (2*mean(x)*mean(y) + c1)/ (mean(x)^2+mean(y)^2+c1)
223 //
224 // This luminance factor is super sensitive to the dark side of luminance
225 // values and completely insensitive on the white side.  check out 2 sets
226 // (1,3) and (250,252) the term gives ( 2*1*3/(1+9) = .60
227 // 2*250*252/ (250^2+252^2) => .99999997
228 //
229 // As a result in this tweaked version of the calculation in which the
230 // luminance is taken as percentage off from peak possible.
231 //
232 // 255 * 255 - (sum_s - sum_r) / count * (sum_s - sum_r) / count
233 //
ssimv_similarity2(const Ssimv * sv,int64_t n)234 static double ssimv_similarity2(const Ssimv *sv, int64_t n) {
235   // Scale the constants by number of pixels.
236   const int64_t c1 = (cc1 * n * n) >> 12;
237   const int64_t c2 = (cc2 * n * n) >> 12;
238 
239   const double mean_diff = (1.0 * sv->sum_s - sv->sum_r) / n;
240   const double l = (255 * 255 - mean_diff * mean_diff + c1) / (255 * 255 + c1);
241 
242   // Since these variables are unsigned, sums convert to double so
243   // math is done in double arithmetic.
244   const double v = (2.0 * n * sv->sum_sxr - 2 * sv->sum_s * sv->sum_r + c2) /
245                    (n * sv->sum_sq_s - sv->sum_s * sv->sum_s +
246                     n * sv->sum_sq_r - sv->sum_r * sv->sum_r + c2);
247 
248   return l * v;
249 }
ssimv_parms(uint8_t * img1,int img1_pitch,uint8_t * img2,int img2_pitch,Ssimv * sv)250 static void ssimv_parms(uint8_t *img1, int img1_pitch, uint8_t *img2,
251                         int img2_pitch, Ssimv *sv) {
252   vpx_ssim_parms_8x8(img1, img1_pitch, img2, img2_pitch, &sv->sum_s, &sv->sum_r,
253                      &sv->sum_sq_s, &sv->sum_sq_r, &sv->sum_sxr);
254 }
255 
vpx_get_ssim_metrics(uint8_t * img1,int img1_pitch,uint8_t * img2,int img2_pitch,int width,int height,Ssimv * sv2,Metrics * m,int do_inconsistency)256 double vpx_get_ssim_metrics(uint8_t *img1, int img1_pitch, uint8_t *img2,
257                             int img2_pitch, int width, int height, Ssimv *sv2,
258                             Metrics *m, int do_inconsistency) {
259   double dssim_total = 0;
260   double ssim_total = 0;
261   double ssim2_total = 0;
262   double inconsistency_total = 0;
263   int i, j;
264   int c = 0;
265   double norm;
266   double old_ssim_total = 0;
267   vpx_clear_system_state();
268   // We can sample points as frequently as we like start with 1 per 4x4.
269   for (i = 0; i < height;
270        i += 4, img1 += img1_pitch * 4, img2 += img2_pitch * 4) {
271     for (j = 0; j < width; j += 4, ++c) {
272       Ssimv sv = { 0, 0, 0, 0, 0, 0 };
273       double ssim;
274       double ssim2;
275       double dssim;
276       uint32_t var_new;
277       uint32_t var_old;
278       uint32_t mean_new;
279       uint32_t mean_old;
280       double ssim_new;
281       double ssim_old;
282 
283       // Not sure there's a great way to handle the edge pixels
284       // in ssim when using a window. Seems biased against edge pixels
285       // however you handle this. This uses only samples that are
286       // fully in the frame.
287       if (j + 8 <= width && i + 8 <= height) {
288         ssimv_parms(img1 + j, img1_pitch, img2 + j, img2_pitch, &sv);
289       }
290 
291       ssim = ssimv_similarity(&sv, 64);
292       ssim2 = ssimv_similarity2(&sv, 64);
293 
294       sv.ssim = ssim2;
295 
296       // dssim is calculated to use as an actual error metric and
297       // is scaled up to the same range as sum square error.
298       // Since we are subsampling every 16th point maybe this should be
299       // *16 ?
300       dssim = 255 * 255 * (1 - ssim2) / 2;
301 
302       // Here I introduce a new error metric: consistency-weighted
303       // SSIM-inconsistency.  This metric isolates frames where the
304       // SSIM 'suddenly' changes, e.g. if one frame in every 8 is much
305       // sharper or blurrier than the others. Higher values indicate a
306       // temporally inconsistent SSIM. There are two ideas at work:
307       //
308       // 1) 'SSIM-inconsistency': the total inconsistency value
309       // reflects how much SSIM values are changing between this
310       // source / reference frame pair and the previous pair.
311       //
312       // 2) 'consistency-weighted': weights de-emphasize areas in the
313       // frame where the scene content has changed. Changes in scene
314       // content are detected via changes in local variance and local
315       // mean.
316       //
317       // Thus the overall measure reflects how inconsistent the SSIM
318       // values are, over consistent regions of the frame.
319       //
320       // The metric has three terms:
321       //
322       // term 1 -> uses change in scene Variance to weight error score
323       //  2 * var(Fi)*var(Fi-1) / (var(Fi)^2+var(Fi-1)^2)
324       //  larger changes from one frame to the next mean we care
325       //  less about consistency.
326       //
327       // term 2 -> uses change in local scene luminance to weight error
328       //  2 * avg(Fi)*avg(Fi-1) / (avg(Fi)^2+avg(Fi-1)^2)
329       //  larger changes from one frame to the next mean we care
330       //  less about consistency.
331       //
332       // term3 -> measures inconsistency in ssim scores between frames
333       //   1 - ( 2 * ssim(Fi)*ssim(Fi-1)/(ssim(Fi)^2+sssim(Fi-1)^2).
334       //
335       // This term compares the ssim score for the same location in 2
336       // subsequent frames.
337       var_new = sv.sum_sq_s - sv.sum_s * sv.sum_s / 64;
338       var_old = sv2[c].sum_sq_s - sv2[c].sum_s * sv2[c].sum_s / 64;
339       mean_new = sv.sum_s;
340       mean_old = sv2[c].sum_s;
341       ssim_new = sv.ssim;
342       ssim_old = sv2[c].ssim;
343 
344       if (do_inconsistency) {
345         // We do the metric once for every 4x4 block in the image. Since
346         // we are scaling the error to SSE for use in a psnr calculation
347         // 1.0 = 4x4x255x255 the worst error we can possibly have.
348         static const double kScaling = 4. * 4 * 255 * 255;
349 
350         // The constants have to be non 0 to avoid potential divide by 0
351         // issues other than that they affect kind of a weighting between
352         // the terms.  No testing of what the right terms should be has been
353         // done.
354         static const double c1 = 1, c2 = 1, c3 = 1;
355 
356         // This measures how much consistent variance is in two consecutive
357         // source frames. 1.0 means they have exactly the same variance.
358         const double variance_term =
359             (2.0 * var_old * var_new + c1) /
360             (1.0 * var_old * var_old + 1.0 * var_new * var_new + c1);
361 
362         // This measures how consistent the local mean are between two
363         // consecutive frames. 1.0 means they have exactly the same mean.
364         const double mean_term =
365             (2.0 * mean_old * mean_new + c2) /
366             (1.0 * mean_old * mean_old + 1.0 * mean_new * mean_new + c2);
367 
368         // This measures how consistent the ssims of two
369         // consecutive frames is. 1.0 means they are exactly the same.
370         double ssim_term =
371             pow((2.0 * ssim_old * ssim_new + c3) /
372                     (ssim_old * ssim_old + ssim_new * ssim_new + c3),
373                 5);
374 
375         double this_inconsistency;
376 
377         // Floating point math sometimes makes this > 1 by a tiny bit.
378         // We want the metric to scale between 0 and 1.0 so we can convert
379         // it to an snr scaled value.
380         if (ssim_term > 1) ssim_term = 1;
381 
382         // This converts the consistency metric to an inconsistency metric
383         // ( so we can scale it like psnr to something like sum square error.
384         // The reason for the variance and mean terms is the assumption that
385         // if there are big changes in the source we shouldn't penalize
386         // inconsistency in ssim scores a bit less as it will be less visible
387         // to the user.
388         this_inconsistency = (1 - ssim_term) * variance_term * mean_term;
389 
390         this_inconsistency *= kScaling;
391         inconsistency_total += this_inconsistency;
392       }
393       sv2[c] = sv;
394       ssim_total += ssim;
395       ssim2_total += ssim2;
396       dssim_total += dssim;
397 
398       old_ssim_total += ssim_old;
399     }
400     old_ssim_total += 0;
401   }
402 
403   norm = 1. / (width / 4) / (height / 4);
404   ssim_total *= norm;
405   ssim2_total *= norm;
406   m->ssim2 = ssim2_total;
407   m->ssim = ssim_total;
408   if (old_ssim_total == 0) inconsistency_total = 0;
409 
410   m->ssimc = inconsistency_total;
411 
412   m->dssim = dssim_total;
413   return inconsistency_total;
414 }
415 
416 #if CONFIG_VP9_HIGHBITDEPTH
vpx_highbd_calc_ssim(const YV12_BUFFER_CONFIG * source,const YV12_BUFFER_CONFIG * dest,double * weight,uint32_t bd,uint32_t in_bd)417 double vpx_highbd_calc_ssim(const YV12_BUFFER_CONFIG *source,
418                             const YV12_BUFFER_CONFIG *dest, double *weight,
419                             uint32_t bd, uint32_t in_bd) {
420   double a, b, c;
421   double ssimv;
422   uint32_t shift = 0;
423 
424   assert(bd >= in_bd);
425   shift = bd - in_bd;
426 
427   a = vpx_highbd_ssim2(source->y_buffer, dest->y_buffer, source->y_stride,
428                        dest->y_stride, source->y_crop_width,
429                        source->y_crop_height, in_bd, shift);
430 
431   b = vpx_highbd_ssim2(source->u_buffer, dest->u_buffer, source->uv_stride,
432                        dest->uv_stride, source->uv_crop_width,
433                        source->uv_crop_height, in_bd, shift);
434 
435   c = vpx_highbd_ssim2(source->v_buffer, dest->v_buffer, source->uv_stride,
436                        dest->uv_stride, source->uv_crop_width,
437                        source->uv_crop_height, in_bd, shift);
438 
439   ssimv = a * .8 + .1 * (b + c);
440 
441   *weight = 1;
442 
443   return ssimv;
444 }
445 
446 #endif  // CONFIG_VP9_HIGHBITDEPTH
447