/work/vvenc/source/Lib/EncoderLib/SEIFilmGrainAnalyzer.cpp
Line | Count | Source |
1 | | /* ----------------------------------------------------------------------------- |
2 | | The copyright in this software is being made available under the Clear BSD |
3 | | License, included below. No patent rights, trademark rights and/or |
4 | | other Intellectual Property Rights other than the copyrights concerning |
5 | | the Software are granted under this license. |
6 | | |
7 | | The Clear BSD License |
8 | | |
9 | | Copyright (c) 2019-2026, Fraunhofer-Gesellschaft zur Förderung der angewandten Forschung e.V. & The VVenC Authors. |
10 | | All rights reserved. |
11 | | |
12 | | Redistribution and use in source and binary forms, with or without modification, |
13 | | are permitted (subject to the limitations in the disclaimer below) provided that |
14 | | the following conditions are met: |
15 | | |
16 | | * Redistributions of source code must retain the above copyright notice, |
17 | | this list of conditions and the following disclaimer. |
18 | | |
19 | | * Redistributions in binary form must reproduce the above copyright |
20 | | notice, this list of conditions and the following disclaimer in the |
21 | | documentation and/or other materials provided with the distribution. |
22 | | |
23 | | * Neither the name of the copyright holder nor the names of its |
24 | | contributors may be used to endorse or promote products derived from this |
25 | | software without specific prior written permission. |
26 | | |
27 | | NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY |
28 | | THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND |
29 | | CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
30 | | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A |
31 | | PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR |
32 | | CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, |
33 | | EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, |
34 | | PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR |
35 | | BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER |
36 | | IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) |
37 | | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
38 | | POSSIBILITY OF SUCH DAMAGE. |
39 | | |
40 | | |
41 | | ------------------------------------------------------------------------------------------- */ |
42 | | |
43 | | #include "SEIFilmGrainAnalyzer.h" |
44 | | #include "SEIFilmGrainSpectra.h" |
45 | | |
46 | | #include "CommonLib/Picture.h" |
47 | | #include "CommonLib/Rom.h" |
48 | | |
49 | | #include <algorithm> |
50 | | #include <cmath> |
51 | | #include <limits> |
52 | | #include <numeric> |
53 | | |
54 | | namespace vvenc { |
55 | | |
56 | | namespace { |
57 | | |
58 | | // Constants of the VTM analysis. |
59 | | constexpr int MAXPAIRS = 256; |
60 | | constexpr int MAXORDER = 8; // maximum order of the polynomial fit |
61 | | constexpr int MAX_REAL_SCALE = 16; |
62 | | constexpr int ORDER = 4; // order of the polynomial function |
63 | | constexpr int QUANT_LEVELS = 4; // quantization levels of the Lloyd-Max quantizer |
64 | | constexpr int INTERVAL_SIZE = 8; |
65 | | constexpr int MIN_ELEMENTS_PER_INTERVAL = 8; |
66 | | constexpr int POINT_STEP = 16; // step size of the point extension |
67 | | constexpr int MAX_POINTS_TO_EXTEND = 4; |
68 | | constexpr double POINT_SCALE = 1.25; // scaling of the point extension (VTM; the improved analysis keeps the dark side's level) |
69 | | constexpr double VAR_SCALE_DOWN = 1.2; // filter out points far below the fitted function |
70 | | constexpr double VAR_SCALE_UP = 0.6; // filter out points far above the fitted function |
71 | | constexpr int NUM_PASSES = 2; // the second pass of the fit filters the data points |
72 | | constexpr int NBRS = 1; // neighbours a point needs within WINDOW to be kept |
73 | | constexpr int WINDOW = 1; |
74 | | constexpr int MIN_MEASURED_POINTS = 2; // measured points the improved fit needs, before the point extension |
75 | | constexpr int MIN_INTENSITY = 40; |
76 | | constexpr int MAX_INTENSITY = 950; |
77 | | constexpr int MAX_STANDARD_DEVIATION = 255; // at 8 bits |
78 | | // With the improvements, the grain strength is kept in units of a quarter of twice the standard deviation (VTM: twice |
79 | | // the standard deviation), so that the scaling factors calibrated from it keep their precision for weak grain. |
80 | | constexpr int IMPROVED_STRENGTH_SCALE = 4; |
81 | | constexpr int BIT_DEPTH_8 = 8; |
82 | | constexpr int MAX_ALLOWED_MODEL_VALUES = 3; |
83 | | constexpr int MAX_NUM_INTENSITIES = 256; |
84 | | constexpr int MAX_CUTOFF_PAIRS = 10; // different cut-off pairs the synthesis supports per picture |
85 | | constexpr double MIN_BLOCK_WEIGHT = 1.0; // accumulated block weight an interval needs for cut-off estimation |
86 | | // A luma value is a grain-free plateau (a clipped highlight, a blown-out sky) when the original has constant 16x16 |
87 | | // blocks of it (grain never leaves a block constant) and |
88 | | // - they form an area: at least PLATEAU_MIN_BLOCKS of them, and at least PLATEAU_JOINED_NUM / PLATEAU_JOINED_DEN of all |
89 | | // of them, have a constant block of the same value beside, above or below, and |
90 | | // - the value is the picture's ceiling: at most one block in PLATEAU_CEILING_BLOCKS is brighter than the plateau's hole. |
91 | | // A lossy source also has constant blocks where its own coding flattened single blocks of a grainy area, at any level |
92 | | // and scattered; they are no plateau, and a hole there would take the grain of the grainy blocks around them |
93 | | // (gangster_chase, H.264: 19 and 20 such blocks among 1400 grainy ones at their levels, 9 to 24 % of the picture |
94 | | // brighter, 4 and 9 of them joined; bk_1191's clipped highlight and Top Gun's sky: none brighter, 93 to 100 % joined). The |
95 | | // MAX_PLATEAUS values with the most constant blocks get a hole. A highlight too small to hold two 16x16 blocks side by |
96 | | // side is not found. |
97 | | constexpr int PLATEAU_MIN_BLOCKS = 8; |
98 | | constexpr int PLATEAU_JOINED_NUM = 3; |
99 | | constexpr int PLATEAU_JOINED_DEN = 4; |
100 | | constexpr int PLATEAU_CEILING_BLOCKS = 200; |
101 | | constexpr int MAX_PLATEAUS = 2; |
102 | | constexpr int PLATEAU_MIN_INTENSITY = 18; // at 8 bits: the hole v8 - 1 .. v8 + 1 stays above digital black (16) |
103 | | |
104 | | // Calibration of the scaling factors, per component type (luma, 4:2:0 chroma) and cut-off pair, measured with the |
105 | | // vvdec film grain synthesis on flat grey 1920x1080 10-bit pictures: |
106 | | // - PATTERN_STDDEV: standard deviation of the synthesized grain for scaling factor 64 at log2_scale_factor 2, so that |
107 | | // a scaling factor s at log2 scale factor l gives grain of standard deviation |
108 | | // s * PATTERN_STDDEV / 2^( l + 14 - bitDepth ) (the synthesis of VTM gives the same); |
109 | | // - BLOCK_VARIANCE_SHARE: the share of that grain's variance that remains after removing the mean of every 16x16 |
110 | | // block, as the analysis measures it. |
111 | | constexpr int NUM_CUTOFFS = 13; // cut-off frequencies 2 to 14 |
112 | | // Largest scaling factor signalled. The syntax allows 255 and so does the scalar synthesis of vvdec, but its x86 SIMD |
113 | | // synthesis sign-extends the 8-bit scaling factors, so 128 and above would make weaker grain of the wrong sign. |
114 | | constexpr int MAX_SCALING_FACTOR = 127; |
115 | | constexpr double PATTERN_STDDEV[ 2 ][ NUM_CUTOFFS ][ NUM_CUTOFFS ] = |
116 | | { |
117 | | { // luma: [ horizontal - 2 ][ vertical - 2 ] |
118 | | { 11.3471, 13.1953, 14.4713, 16.0922, 17.5548, 18.7151, 20.0700, 20.9957, 21.8035, 22.8604, 23.8162, 24.4313, 25.4741 }, |
119 | | { 12.7110, 14.8901, 16.3847, 18.3015, 19.9240, 21.3337, 22.8999, 24.0157, 25.0655, 26.3700, 27.3986, 28.3434, 29.3805 }, |
120 | | { 14.1172, 16.5524, 18.2611, 20.5952, 22.4983, 24.0530, 25.9973, 27.3273, 28.5572, 30.0424, 31.1997, 32.1487, 33.2355 }, |
121 | | { 15.5021, 18.0297, 20.0899, 22.4546, 24.4364, 26.2005, 28.2301, 29.8060, 31.3123, 32.9112, 34.1466, 35.3053, 36.4918 }, |
122 | | { 16.4720, 19.2467, 21.3980, 23.9320, 26.0343, 28.0799, 30.3483, 32.0788, 33.6981, 35.4062, 36.7268, 37.9420, 39.4344 }, |
123 | | { 17.4095, 20.4055, 22.9677, 25.5371, 27.8608, 30.1310, 32.3993, 34.2167, 35.9951, 37.9442, 39.4321, 40.6859, 42.2433 }, |
124 | | { 18.1305, 21.4469, 24.0610, 26.8472, 29.2790, 31.7692, 34.0672, 36.0396, 37.8454, 39.9101, 41.3417, 42.7916, 44.3514 }, |
125 | | { 19.2211, 22.7276, 25.4476, 28.2473, 30.8452, 33.3751, 35.7479, 37.6866, 39.5467, 41.7627, 43.3952, 44.7700, 46.4703 }, |
126 | | { 20.4457, 24.1150, 27.0148, 29.9963, 32.7611, 35.2320, 37.6624, 39.8350, 41.6697, 43.8564, 45.5852, 46.9930, 48.9238 }, |
127 | | { 21.6430, 25.4942, 28.5270, 31.8942, 34.6005, 37.0724, 39.4975, 41.7995, 43.5896, 45.7560, 47.5483, 49.0574, 50.9609 }, |
128 | | { 22.5390, 26.4786, 29.5484, 32.9731, 35.8114, 38.4931, 41.0125, 43.2637, 45.0366, 47.2199, 49.1412, 50.7580, 52.6695 }, |
129 | | { 23.4841, 27.5594, 30.6919, 34.2237, 37.1031, 39.7887, 42.3244, 44.6668, 46.6079, 48.6607, 50.7871, 52.3455, 54.2592 }, |
130 | | { 24.0446, 28.2479, 31.5268, 35.1441, 38.0267, 40.7036, 43.3165, 45.7409, 47.7803, 49.8510, 51.9981, 53.5674, 55.5688 }, |
131 | | }, |
132 | | { // 4:2:0 chroma: [ horizontal - 2 ][ vertical - 2 ] |
133 | | { 9.8329, 11.6354, 12.8245, 13.6625, 15.3470, 16.4060, 16.4060, 16.4060, 16.4060, 16.4060, 16.4060, 16.4060, 16.4060 }, |
134 | | { 11.7467, 14.0110, 15.6190, 16.6803, 18.4311, 19.4934, 19.4934, 19.4934, 19.4934, 19.4934, 19.4934, 19.4934, 19.4934 }, |
135 | | { 12.8707, 15.3081, 17.2100, 18.5999, 20.4333, 21.5392, 21.5392, 21.5392, 21.5392, 21.5392, 21.5392, 21.5392, 21.5392 }, |
136 | | { 14.0068, 16.3715, 18.4529, 19.9943, 21.8958, 23.3361, 23.3361, 23.3361, 23.3361, 23.3361, 23.3361, 23.3361, 23.3361 }, |
137 | | { 15.2300, 17.7825, 20.0028, 21.6539, 23.5309, 25.4114, 25.4114, 25.4114, 25.4114, 25.4114, 25.4114, 25.4114, 25.4114 }, |
138 | | { 16.5225, 19.3558, 21.5353, 23.2748, 25.1079, 27.1849, 27.1849, 27.1849, 27.1849, 27.1849, 27.1849, 27.1849, 27.1849 }, |
139 | | { 16.5225, 19.3558, 21.5353, 23.2748, 25.1079, 27.1849, 27.1849, 27.1849, 27.1849, 27.1849, 27.1849, 27.1849, 27.1849 }, |
140 | | { 16.5225, 19.3558, 21.5353, 23.2748, 25.1079, 27.1849, 27.1849, 27.1849, 27.1849, 27.1849, 27.1849, 27.1849, 27.1849 }, |
141 | | { 16.5225, 19.3558, 21.5353, 23.2748, 25.1079, 27.1849, 27.1849, 27.1849, 27.1849, 27.1849, 27.1849, 27.1849, 27.1849 }, |
142 | | { 16.5225, 19.3558, 21.5353, 23.2748, 25.1079, 27.1849, 27.1849, 27.1849, 27.1849, 27.1849, 27.1849, 27.1849, 27.1849 }, |
143 | | { 16.5225, 19.3558, 21.5353, 23.2748, 25.1079, 27.1849, 27.1849, 27.1849, 27.1849, 27.1849, 27.1849, 27.1849, 27.1849 }, |
144 | | { 16.5225, 19.3558, 21.5353, 23.2748, 25.1079, 27.1849, 27.1849, 27.1849, 27.1849, 27.1849, 27.1849, 27.1849, 27.1849 }, |
145 | | { 16.5225, 19.3558, 21.5353, 23.2748, 25.1079, 27.1849, 27.1849, 27.1849, 27.1849, 27.1849, 27.1849, 27.1849, 27.1849 }, |
146 | | }, |
147 | | }; |
148 | | |
149 | | constexpr double BLOCK_VARIANCE_SHARE[ 2 ][ NUM_CUTOFFS ][ NUM_CUTOFFS ] = |
150 | | { |
151 | | { // luma: [ horizontal - 2 ][ vertical - 2 ] |
152 | | { 0.9137, 0.9350, 0.9456, 0.9547, 0.9619, 0.9646, 0.9688, 0.9716, 0.9733, 0.9758, 0.9777, 0.9789, 0.9805 }, |
153 | | { 0.9299, 0.9481, 0.9568, 0.9642, 0.9699, 0.9724, 0.9756, 0.9778, 0.9795, 0.9813, 0.9828, 0.9839, 0.9850 }, |
154 | | { 0.9429, 0.9577, 0.9650, 0.9715, 0.9762, 0.9780, 0.9809, 0.9828, 0.9840, 0.9855, 0.9867, 0.9875, 0.9883 }, |
155 | | { 0.9520, 0.9641, 0.9708, 0.9757, 0.9796, 0.9815, 0.9837, 0.9854, 0.9867, 0.9879, 0.9888, 0.9895, 0.9902 }, |
156 | | { 0.9568, 0.9680, 0.9740, 0.9784, 0.9818, 0.9836, 0.9858, 0.9873, 0.9884, 0.9894, 0.9902, 0.9908, 0.9915 }, |
157 | | { 0.9609, 0.9709, 0.9770, 0.9807, 0.9839, 0.9856, 0.9874, 0.9886, 0.9896, 0.9907, 0.9914, 0.9919, 0.9925 }, |
158 | | { 0.9634, 0.9733, 0.9786, 0.9822, 0.9851, 0.9868, 0.9883, 0.9896, 0.9904, 0.9914, 0.9920, 0.9926, 0.9931 }, |
159 | | { 0.9674, 0.9761, 0.9809, 0.9839, 0.9866, 0.9881, 0.9894, 0.9905, 0.9913, 0.9921, 0.9928, 0.9933, 0.9938 }, |
160 | | { 0.9711, 0.9788, 0.9830, 0.9857, 0.9881, 0.9893, 0.9904, 0.9914, 0.9921, 0.9929, 0.9934, 0.9939, 0.9945 }, |
161 | | { 0.9744, 0.9811, 0.9848, 0.9875, 0.9894, 0.9904, 0.9914, 0.9923, 0.9929, 0.9936, 0.9941, 0.9945, 0.9950 }, |
162 | | { 0.9762, 0.9824, 0.9859, 0.9883, 0.9901, 0.9911, 0.9920, 0.9929, 0.9934, 0.9940, 0.9945, 0.9948, 0.9953 }, |
163 | | { 0.9782, 0.9838, 0.9869, 0.9891, 0.9907, 0.9916, 0.9925, 0.9933, 0.9938, 0.9943, 0.9948, 0.9951, 0.9956 }, |
164 | | { 0.9792, 0.9846, 0.9876, 0.9897, 0.9911, 0.9920, 0.9928, 0.9936, 0.9941, 0.9946, 0.9951, 0.9954, 0.9959 }, |
165 | | }, |
166 | | { // 4:2:0 chroma: [ horizontal - 2 ][ vertical - 2 ] |
167 | | { 0.9488, 0.9625, 0.9686, 0.9723, 0.9781, 0.9805, 0.9805, 0.9805, 0.9805, 0.9805, 0.9805, 0.9805, 0.9805 }, |
168 | | { 0.9621, 0.9727, 0.9776, 0.9805, 0.9840, 0.9855, 0.9855, 0.9855, 0.9855, 0.9855, 0.9855, 0.9855, 0.9855 }, |
169 | | { 0.9684, 0.9770, 0.9817, 0.9842, 0.9870, 0.9881, 0.9881, 0.9881, 0.9881, 0.9881, 0.9881, 0.9881, 0.9881 }, |
170 | | { 0.9733, 0.9798, 0.9839, 0.9862, 0.9886, 0.9897, 0.9897, 0.9897, 0.9897, 0.9897, 0.9897, 0.9897, 0.9897 }, |
171 | | { 0.9772, 0.9829, 0.9862, 0.9881, 0.9901, 0.9914, 0.9914, 0.9914, 0.9914, 0.9914, 0.9914, 0.9914, 0.9914 }, |
172 | | { 0.9807, 0.9855, 0.9882, 0.9899, 0.9914, 0.9925, 0.9925, 0.9925, 0.9925, 0.9925, 0.9925, 0.9925, 0.9925 }, |
173 | | { 0.9807, 0.9855, 0.9882, 0.9899, 0.9914, 0.9925, 0.9925, 0.9925, 0.9925, 0.9925, 0.9925, 0.9925, 0.9925 }, |
174 | | { 0.9807, 0.9855, 0.9882, 0.9899, 0.9914, 0.9925, 0.9925, 0.9925, 0.9925, 0.9925, 0.9925, 0.9925, 0.9925 }, |
175 | | { 0.9807, 0.9855, 0.9882, 0.9899, 0.9914, 0.9925, 0.9925, 0.9925, 0.9925, 0.9925, 0.9925, 0.9925, 0.9925 }, |
176 | | { 0.9807, 0.9855, 0.9882, 0.9899, 0.9914, 0.9925, 0.9925, 0.9925, 0.9925, 0.9925, 0.9925, 0.9925, 0.9925 }, |
177 | | { 0.9807, 0.9855, 0.9882, 0.9899, 0.9914, 0.9925, 0.9925, 0.9925, 0.9925, 0.9925, 0.9925, 0.9925, 0.9925 }, |
178 | | { 0.9807, 0.9855, 0.9882, 0.9899, 0.9914, 0.9925, 0.9925, 0.9925, 0.9925, 0.9925, 0.9925, 0.9925, 0.9925 }, |
179 | | { 0.9807, 0.9855, 0.9882, 0.9899, 0.9914, 0.9925, 0.9925, 0.9925, 0.9925, 0.9925, 0.9925, 0.9925, 0.9925 }, |
180 | | }, |
181 | | }; |
182 | | |
183 | | // After this many analyses in a row whose scaling function fit failed, a component's grain is no longer signalled. |
184 | | constexpr int MAX_FAILED_FITS = 3; |
185 | | // A picture whose mean grain strength differs from that of the accumulated data by more than this factor starts the |
186 | | // statistics anew (a new scene with different grain); it needs this many blocks for a reliable mean. |
187 | | constexpr double GRAIN_CHANGE_RATIO = 2.0; |
188 | | constexpr int GRAIN_CHANGE_MIN_BLOCKS = 64; |
189 | | |
190 | | // The auto-regressive model (--fga 3): vvdec's synthesis makes grain of standard deviation |
191 | | // scale * AR_PATTERN_STDDEV * sqrt( energy ) / 2^( log2ScaleFactor + 10 - bitDepth ) for the AR filter whose impulse |
192 | | // response has the given energy (its quantized coefficients, as the synthesis computes them). Measured with vvdec on |
193 | | // flat grey 1920x1088 10-bit pictures over 24 filters (left coefficient 0 to 0.375) and log2 scale factors 3 to 7: |
194 | | // the ratio stays within 3% of these values. |
195 | | constexpr double AR_PATTERN_STDDEV[ 2 ] = { 3.83, 3.60 }; // luma, chroma |
196 | | constexpr int AR_SPECTRUM_BINS = 64; // frequency bins per direction of the AR spectrum computation |
197 | | constexpr int AR_FIT_ITERATIONS = 200; // largest number of Nelder-Mead iterations of the AR filter fit |
198 | | constexpr double AR_FIT_TOLERANCE = 1e-5; // the fit stops when its simplex spans less than this cost |
199 | | // The fitted filter must be stable (arFilterStable) with this margin: poles no closer to the unit circle, so that the |
200 | | // quantized filter is stable too and the grain reaches its level within the few rows the synthesis runs in before its |
201 | | // pattern starts. |
202 | | constexpr double AR_STABILITY_MARGIN = 1.05; |
203 | | // Largest variance gain of the fitted filter (variance of its output per variance of the noise it filters). vvdec builds |
204 | | // the pattern in 8 bits, clipped to +-127, from noise of standard deviation 31.5: at gain 4 the pattern's is 63 and 4 % of |
205 | | // its samples clip (10 % at gain 6), which the calibration of the scaling factors (AR_PATTERN_STDDEV) does not model. |
206 | | constexpr double AR_MAX_GAIN = 4.0; |
207 | | // In the fit of the filter, grain power beyond the measured counts this many times more than power missing, as in the |
208 | | // fit to the grain the coding lost (LOST_GRAIN_OVERSHOOT_WEIGHT): too much grain is worse than too little. |
209 | | constexpr double AR_OVERSHOOT_WEIGHT = 4.0; |
210 | | constexpr double AR_MIN_POWER_SCALE = 0.05; // smallest share of the measured grain power the fit may give |
211 | | |
212 | | // Outliers of the temporal residual: per intensity bin (16 bins), blocks above this ratio of the median grain variance |
213 | | // are motion compensation failures; bins need this many blocks for the median. |
214 | | constexpr int NUM_OUTLIER_BINS = 16; |
215 | | constexpr double OUTLIER_VARIANCE_RATIO = 4.0; |
216 | | constexpr int MIN_OUTLIER_BIN_BLOCKS = 8; |
217 | | |
218 | | // Motion compensation failures of the temporal residual, block by block: where the compensation works, the grain variance |
219 | | // from the residual is about twice that of the spatial estimate (denoised minus original, which sees about half the grain: |
220 | | // median ratio 1.7-2.2 on gangster_chase, nocturne and crowd); where it fails (fast motion, whip pans) the residual keeps |
221 | | // picture structure and the ratio reads 5-8. The existing per-bin outlier test cannot see this when most blocks fail. |
222 | | constexpr double MOTION_FAILURE_RATIO = 4.0; // a flat block above this ratio is left out |
223 | | constexpr double MIN_SPATIAL_STDDEV = 0.5; // 8-bit units: clean flat blocks (black) must not fail by rounding alone |
224 | | constexpr double MAX_MOTION_FAILURE_SHARE = 0.5; // a picture with more failed flat luma blocks updates nothing |
225 | | |
226 | | // Repeated grain: lossy sources (UHD Blu-ray HEVC) partly repeat the grain from picture to picture (the encoder of the |
227 | | // source skips or bi-predicts flat areas), and both estimates above are temporal: they read such grain at a fraction. |
228 | | // The high frequencies of the original itself see all of the grain, so the residual's grain variance is scaled up by the |
229 | | // median ratio of the two over the flat blocks, per intensity bin: bright flat areas (sky) repeat more than dark ones |
230 | | // (Top Gun, 8-bit intensity: 1.6 at 32-63, 2.7 at 64-79, 3.9-4.2 at 80-111, 6.2 at 112-127). Only the finest frequencies |
231 | | // count, where static texture in flat blocks has less energy than grain: fresh grain reads 1.1 (nocturne) to 1.3-1.6 |
232 | | // (Beekeeper) with them, 1.2 to 1.4-1.75 from u + v >= 6. Texture or dither in flat blocks still raises the ratio |
233 | | // somewhat; the median and the limit bound that. |
234 | | constexpr int REPEATED_GRAIN_MIN_FREQ = 10; // DCT coefficients with u + v at least this are the high frequencies |
235 | | constexpr int REPEATED_GRAIN_BIN_BITS = 4; // log2 of the intensity bins |
236 | | constexpr int NUM_REPEATED_GRAIN_BINS = 1 << REPEATED_GRAIN_BIN_BITS; |
237 | | constexpr int MIN_REPEATED_GRAIN_BIN_BLOCKS = 32; // a bin with fewer blocks takes the picture's ratio |
238 | | constexpr double MAX_REPEATED_GRAIN_RATIO = 16.0; // largest variance scale (4x in standard deviation) |
239 | | |
240 | | // Levels without flat blocks: bright picture areas are mostly texture and edges, so the mask leaves few or no flat blocks |
241 | | // there (gangster_chase, 8-bit 160-239: 15 of 558 blocks), and above the brightest measured blocks the scaling function |
242 | | // only faded out (extendPoints): the synthesis put back 0.69-0.74 of the source's fine grain at 8-bit 145-176 and 0.43-0.56 |
243 | | // from 177, while the source's grain there is at least as strong as in the mid-tones. The grain of such a level is read |
244 | | // from the finest frequencies of its smoothest blocks instead, relative to the same reading at the levels that have flat |
245 | | // blocks (FGAnalyzer::addSmoothBlockPoints). Luma only. |
246 | | constexpr int SMOOTH_BIN_BITS = 4; // log2 of the intensity bins |
247 | | constexpr int NUM_SMOOTH_BINS = 1 << SMOOTH_BIN_BITS; |
248 | | constexpr int MIN_SMOOTH_BIN_BLOCKS = 32; // flat blocks of a measured bin; blocks of a bin that is read this way |
249 | | constexpr int SMOOTH_BLOCK_PERCENTILE = 15; // the bin's typical smooth block: the median of its smoothest 30 % |
250 | | |
251 | | constexpr double LOW_THRESHOLD_RATIO = 0.1; // Canny: low threshold relative to the strongest gradient |
252 | | constexpr int HIGH_THRESHOLD_RATIO = 3; // Canny: high threshold relative to the low threshold |
253 | | constexpr double LOW_INTENSITY_RATIO = 0.1; // VTM: samples below this share of the range are not analysed |
254 | | constexpr int LOW_INTENSITY_8BIT = 18; // improved analysis: samples below this (8-bit; black is 16) are not analysed |
255 | | |
256 | | constexpr double TAP_FILTER[ 3 ] = { 1, 2, 1 }; |
257 | | constexpr double NORM_TAP = 4.0; |
258 | | |
259 | | typedef FGAnalyzer::Plane Plane; |
260 | | |
261 | | // ==================================================================================================================== |
262 | | // Flat area detection: Canny edge detector and morphological operations |
263 | | // ==================================================================================================================== |
264 | | |
265 | | // Classifies the magnitudes as strong, weak or no edge, with thresholds relative to the strongest gradient. |
266 | | void doubleThreshold( const FgaRowKernels& k, Plane& mag, int bitDepth ) |
267 | 0 | { |
268 | 0 | const Pel strongPel = (Pel) ( ( 1 << bitDepth ) - 1 ); |
269 | 0 | const Pel weakPel = (Pel) ( ( 1 << ( bitDepth - 1 ) ) - 1 ); |
270 | 0 | const int n = mag.width * mag.height; // the storage can be larger than the plane |
271 | |
|
272 | 0 | const Pel highest = k.rowMax( mag.samples.data(), n ); |
273 | 0 | const Pel lowThreshold = (Pel) ( LOW_THRESHOLD_RATIO * highest ); |
274 | 0 | const Pel highThreshold = (Pel) Clip3( 0, ( 1 << bitDepth ) - 1, HIGH_THRESHOLD_RATIO * lowThreshold ); |
275 | 0 | k.classify( mag.samples.data(), n, lowThreshold, highThreshold, weakPel, strongPel ); |
276 | 0 | } |
277 | | |
278 | | // Hysteresis: a weak edge becomes strong when a strong edge is in its 3x3 neighbourhood, otherwise it is removed. |
279 | | // As in VTM, the picture is updated in place, column by column, so a weak edge turned strong can promote weak edges |
280 | | // processed after it. Neighbours outside the picture repeat the border as it was before the tracking started. |
281 | | template<class ScratchT> |
282 | | void edgeTracking( const FgaRowKernels& k, Plane& edges, int bitDepth, ScratchT& s ) |
283 | 0 | { |
284 | 0 | const Pel strongPel = (Pel) ( ( 1 << bitDepth ) - 1 ); |
285 | 0 | const Pel weakPel = (Pel) ( ( 1 << ( bitDepth - 1 ) ) - 1 ); |
286 | 0 | const int w = edges.width, h = edges.height; |
287 | | |
288 | | // The weak edges in column-major order: found row by row, then sorted by column (counting sort, stable, so the |
289 | | // rows of every column stay in increasing order). |
290 | 0 | s.positions.resize( w ); |
291 | 0 | s.weakX.clear(); |
292 | 0 | s.weakY.clear(); |
293 | 0 | for( int y = 0; y < h; y++ ) |
294 | 0 | { |
295 | 0 | const int n = k.findEqual( edges.row( y ), w, weakPel, s.positions.data() ); |
296 | 0 | for( int i = 0; i < n; i++ ) |
297 | 0 | { |
298 | 0 | s.weakX.push_back( s.positions[ i ] ); |
299 | 0 | s.weakY.push_back( y ); |
300 | 0 | } |
301 | 0 | } |
302 | 0 | if( s.weakX.empty() ) |
303 | 0 | { |
304 | 0 | return; |
305 | 0 | } |
306 | 0 | std::vector<int>& columnStart = s.columnStart; |
307 | 0 | columnStart.assign( w + 1, 0 ); |
308 | 0 | for( int px : s.weakX ) |
309 | 0 | { |
310 | 0 | columnStart[ px + 1 ]++; |
311 | 0 | } |
312 | 0 | for( int px = 0; px < w; px++ ) |
313 | 0 | { |
314 | 0 | columnStart[ px + 1 ] += columnStart[ px ]; |
315 | 0 | } |
316 | 0 | std::vector<int>& weakRows = s.positions; |
317 | 0 | weakRows.resize( s.weakX.size() ); |
318 | 0 | { |
319 | 0 | std::vector<int> fill( columnStart.begin(), columnStart.end() - 1 ); |
320 | 0 | for( size_t i = 0; i < s.weakX.size(); i++ ) |
321 | 0 | { |
322 | 0 | weakRows[ fill[ s.weakX[ i ] ]++ ] = s.weakY[ i ]; |
323 | 0 | } |
324 | 0 | } |
325 | | |
326 | | // Neighbours outside the picture are border samples as they were before the tracking. |
327 | 0 | s.top.assign( edges.row( 0 ), edges.row( 0 ) + w ); |
328 | 0 | s.bottom.assign( edges.row( h - 1 ), edges.row( h - 1 ) + w ); |
329 | 0 | s.left.resize( h ); |
330 | 0 | s.right.resize( h ); |
331 | 0 | for( int y = 0; y < h; y++ ) |
332 | 0 | { |
333 | 0 | s.left[ y ] = edges.row( y )[ 0 ]; |
334 | 0 | s.right[ y ] = edges.row( y )[ w - 1 ]; |
335 | 0 | } |
336 | 0 | auto borderAt = [ & ]( int bx, int by ) |
337 | 0 | { |
338 | 0 | const int cx = Clip3( 0, w - 1, bx ), cy = Clip3( 0, h - 1, by ); |
339 | 0 | return cy == 0 ? s.top[ cx ] : cy == h - 1 ? s.bottom[ cx ] : cx == 0 ? s.left[ cy ] : s.right[ cy ]; |
340 | 0 | }; |
341 | |
|
342 | 0 | for( int x = 0; x < w; x++ ) |
343 | 0 | { |
344 | 0 | for( int i = columnStart[ x ]; i < columnStart[ x + 1 ]; i++ ) |
345 | 0 | { |
346 | 0 | const int y = weakRows[ i ]; |
347 | 0 | bool strong = false; |
348 | 0 | for( int ny = y - 1; ny <= y + 1 && !strong; ny++ ) |
349 | 0 | { |
350 | 0 | for( int nx = x - 1; nx <= x + 1 && !strong; nx++ ) |
351 | 0 | { |
352 | 0 | const bool inside = nx >= 0 && nx < w && ny >= 0 && ny < h; |
353 | 0 | strong = ( inside ? edges.row( ny )[ nx ] : borderAt( nx, ny ) ) == strongPel; |
354 | 0 | } |
355 | 0 | } |
356 | 0 | edges.row( y )[ x ] = strong ? strongPel : 0; |
357 | 0 | } |
358 | 0 | } |
359 | 0 | } |
360 | | |
361 | | // Sets the binary mask to "edge" where the picture is too dark to be analysed. VTM leaves out the darkest 10 % of the |
362 | | // range; with the dilations of every scale that hides intensities up to about 10-bit 135, the first 70 code values |
363 | | // above limited-range black (64), where PQ films keep much of their picture and their grain. With nothing measured |
364 | | // there, the improved analysis held the darkest measured strength down to black: 1.66x the grain the coding lost on |
365 | | // Beekeeper's 8-bit 17-32. The improved analysis leaves out only black and the code values just above it (letterbox |
366 | | // bars, crushed shadows), which carry no grain to measure. |
367 | | void suppressLowIntensity( const Plane& p, Plane& mask, int bitDepth, bool improved ) |
368 | 0 | { |
369 | 0 | const Pel maxIntensity = (Pel) ( ( 1 << bitDepth ) - 1 ); |
370 | 0 | const Pel threshold = improved ? (Pel) ( LOW_INTENSITY_8BIT << ( bitDepth - BIT_DEPTH_8 ) ) |
371 | 0 | : (Pel) ( LOW_INTENSITY_RATIO * maxIntensity ); |
372 | 0 | const size_t n = (size_t) mask.width * mask.height; |
373 | 0 | const Pel* src = p.samples.data(); |
374 | 0 | Pel* dst = mask.samples.data(); |
375 | 0 | for( size_t i = 0; i < n; i++ ) |
376 | 0 | { |
377 | 0 | dst[ i ] = src[ i ] < threshold ? maxIntensity : dst[ i ]; // a select, so that the loop vectorizes |
378 | 0 | } |
379 | 0 | } |
380 | | |
381 | | // Subsampling as in VTM: the average of the top-left 2x2 samples of every factor x factor block. |
382 | | void subsample( const Plane& in, Plane& out, int factor ) |
383 | 0 | { |
384 | 0 | out.resize( in.width / factor, in.height / factor ); |
385 | 0 | for( int y = 0; y < out.height; y++ ) |
386 | 0 | { |
387 | 0 | const Pel* r0 = in.row( y * factor ); |
388 | 0 | const Pel* r1 = in.row( y * factor + 1 ); |
389 | 0 | Pel* dst = out.row( y ); |
390 | 0 | for( int x = 0; x < out.width; x++ ) |
391 | 0 | { |
392 | 0 | const int sx = x * factor; |
393 | 0 | dst[ x ] = (Pel) ( ( r0[ sx ] + r1[ sx ] + r0[ sx + 1 ] + r1[ sx + 1 ] + 2 ) >> 2 ); |
394 | 0 | } |
395 | 0 | } |
396 | 0 | } |
397 | | |
398 | | // Adds a mask found at a lower resolution to the full-resolution mask (sample replication, then bitwise or). |
399 | | void combineUpsampled( Plane& mask, const Plane& low, int factor, std::vector<Pel>& wide ) |
400 | 0 | { |
401 | 0 | const int w = low.width * factor; |
402 | 0 | wide.resize( w ); |
403 | 0 | for( int ly = 0; ly < low.height; ly++ ) |
404 | 0 | { |
405 | 0 | const Pel* src = low.row( ly ); |
406 | 0 | for( int lx = 0; lx < low.width; lx++ ) |
407 | 0 | { |
408 | 0 | for( int f = 0; f < factor; f++ ) |
409 | 0 | { |
410 | 0 | wide[ lx * factor + f ] = src[ lx ]; |
411 | 0 | } |
412 | 0 | } |
413 | 0 | for( int y = ly * factor; y < ( ly + 1 ) * factor; y++ ) |
414 | 0 | { |
415 | 0 | Pel* dst = mask.row( y ); |
416 | 0 | for( int x = 0; x < w; x++ ) |
417 | 0 | { |
418 | 0 | dst[ x ] |= wide[ x ]; |
419 | 0 | } |
420 | 0 | } |
421 | 0 | } |
422 | 0 | } |
423 | | |
424 | | // ==================================================================================================================== |
425 | | // Block statistics |
426 | | // ==================================================================================================================== |
427 | | |
428 | | struct BlockStats |
429 | | { |
430 | | int mean; // truncated, as in VTM (it selects the intensity) |
431 | | double stddev; // exact; VTM truncates it to an integer, which loses up to a third of the grain strength |
432 | | }; |
433 | | |
434 | | // Mean and standard deviation of a 16x16 block. |
435 | | BlockStats meanStdDev( const FgaRowKernels& k, const Plane& p, int x0, int y0 ) |
436 | 0 | { |
437 | 0 | int64_t sum = 0, sumSq = 0; |
438 | 0 | k.blockSums( p.row( y0 ) + x0, p.width, sum, sumSq ); |
439 | 0 | const int n = 16 * 16; |
440 | 0 | const double variance = ( (double) sumSq - (double) sum * sum / n ) / n; |
441 | 0 | return { (int) ( sum / n ), std::sqrt( std::max( variance, 0.0 ) ) }; |
442 | 0 | } |
443 | | |
444 | | // A flat 16x16 block: no edge of the mask in it, and the denoised block flat enough that the mask did not miss texture. |
445 | | // stats receives the denoised block's mean and standard deviation. |
446 | | static bool isFlatBlock( const FgaRowKernels& k, const Plane& mask, const Plane& denoised, int x, int y, int maxStrength, |
447 | | BlockStats& stats ) |
448 | 0 | { |
449 | 0 | if( !k.isZeroBlock( mask.row( y ) + x, mask.width ) ) |
450 | 0 | { |
451 | 0 | return false; |
452 | 0 | } |
453 | 0 | stats = meanStdDev( k, denoised, x, y ); |
454 | 0 | return 2 * stats.stddev < ( maxStrength >> 1 ); |
455 | 0 | } |
456 | | |
457 | | // The 16x16 blocks of a luma picture (whole blocks only, raster order, `columns` per row): per block its value when its |
458 | | // 256 samples are equal (256 * sumSq == sum^2), else -1; per 8-bit mean the number of blocks. |
459 | | static std::vector<int> constantBlockValues( const FgaRowKernels& k, const CPelBuf& luma, int bitDepth, int& columns, |
460 | | std::vector<int>& blocksAtLevel ) |
461 | 0 | { |
462 | 0 | constexpr int N = 16; |
463 | 0 | columns = (int) luma.width / N; |
464 | 0 | blocksAtLevel.assign( MAX_NUM_INTENSITIES, 0 ); |
465 | 0 | std::vector<int> values; |
466 | 0 | values.reserve( size_t( columns ) * ( luma.height / N ) ); |
467 | 0 | for( int y = 0; y + N <= (int) luma.height; y += N ) |
468 | 0 | { |
469 | 0 | for( int x = 0; x + N <= (int) luma.width; x += N ) |
470 | 0 | { |
471 | 0 | int64_t sum = 0, sumSq = 0; |
472 | 0 | k.blockSums( luma.bufAt( x, y ), luma.stride, sum, sumSq ); |
473 | 0 | const int mean = (int) ( sum / ( N * N ) ); |
474 | 0 | blocksAtLevel[ mean >> ( bitDepth - BIT_DEPTH_8 ) ]++; |
475 | 0 | values.push_back( N * N * sumSq == sum * sum ? mean : -1 ); |
476 | 0 | } |
477 | 0 | } |
478 | 0 | return values; |
479 | 0 | } |
480 | | |
481 | | // The grain-free plateaus of a luma picture (see PLATEAU_MIN_BLOCKS): the qualifying values, at most MAX_PLATEAUS, most |
482 | | // constant blocks first (ties: the lower value). |
483 | | static std::vector<int> findPlateaus( const FgaRowKernels& k, const CPelBuf& luma, int bitDepth ) |
484 | 0 | { |
485 | 0 | int columns = 0; |
486 | 0 | std::vector<int> blocksAtLevel; |
487 | 0 | const std::vector<int> values = constantBlockValues( k, luma, bitDepth, columns, blocksAtLevel ); |
488 | 0 | const int numBlocks = (int) values.size(), shift = bitDepth - BIT_DEPTH_8; |
489 | | |
490 | | // per value: its constant blocks, and those of them with a constant block of the same value beside, above or below |
491 | 0 | std::vector<int> constantBlocks( size_t( 1 ) << bitDepth, 0 ), joinedBlocks( size_t( 1 ) << bitDepth, 0 ); |
492 | 0 | for( int i = 0; i < numBlocks; i++ ) |
493 | 0 | { |
494 | 0 | const int value = values[ i ]; |
495 | 0 | if( value < ( PLATEAU_MIN_INTENSITY << shift ) ) |
496 | 0 | { |
497 | 0 | continue; // not constant (-1), or too dark |
498 | 0 | } |
499 | 0 | const int column = i % columns; |
500 | 0 | const bool joined = ( column > 0 && values[ i - 1 ] == value ) || ( column + 1 < columns && values[ i + 1 ] == value ) |
501 | 0 | || ( i >= columns && values[ i - columns ] == value ) |
502 | 0 | || ( i + columns < numBlocks && values[ i + columns ] == value ); |
503 | 0 | constantBlocks[ value ]++; |
504 | 0 | joinedBlocks [ value ] += joined; |
505 | 0 | } |
506 | |
|
507 | 0 | const auto isPlateau = [ & ]( int value, int numConstant ) |
508 | 0 | { |
509 | 0 | int brighter = 0; // blocks above the hole, which is ( value >> shift ) - 1 .. + 1 (cutPlateauHoles) |
510 | 0 | for( int level = ( value >> shift ) + 2; level < MAX_NUM_INTENSITIES; level++ ) |
511 | 0 | { |
512 | 0 | brighter += blocksAtLevel[ level ]; |
513 | 0 | } |
514 | 0 | return joinedBlocks[ value ] >= PLATEAU_MIN_BLOCKS |
515 | 0 | && joinedBlocks[ value ] * PLATEAU_JOINED_DEN >= numConstant * PLATEAU_JOINED_NUM |
516 | 0 | && brighter * PLATEAU_CEILING_BLOCKS <= numBlocks; |
517 | 0 | }; |
518 | |
|
519 | 0 | std::vector<int> plateaus; |
520 | 0 | while( (int) plateaus.size() < MAX_PLATEAUS ) |
521 | 0 | { |
522 | 0 | const auto most = std::max_element( constantBlocks.begin(), constantBlocks.end() ); |
523 | 0 | if( *most < PLATEAU_MIN_BLOCKS ) |
524 | 0 | { |
525 | 0 | break; |
526 | 0 | } |
527 | 0 | const int value = (int) ( most - constantBlocks.begin() ); |
528 | 0 | if( isPlateau( value, *most ) ) |
529 | 0 | { |
530 | 0 | plateaus.push_back( value ); |
531 | 0 | } |
532 | 0 | *most = 0; |
533 | 0 | } |
534 | 0 | return plateaus; |
535 | 0 | } |
536 | | |
537 | | // Energy of the high frequencies (REPEATED_GRAIN_MIN_FREQ) of the 16x16 DCT of a block. |
538 | | static double highFrequencyEnergy( const FgaRowKernels& k, const Pel* src, int stride, int bitDepth ) |
539 | 0 | { |
540 | 0 | constexpr int N = 16; // squaredDct16's block size |
541 | 0 | double spectrum[ N * N ] = {}; |
542 | 0 | k.squaredDct16( src, stride, ( 1 << ( bitDepth + 4 ) ) - 1, spectrum ); |
543 | 0 | double energy = 0.0; |
544 | 0 | for( int u = 0; u < N; u++ ) |
545 | 0 | { |
546 | 0 | for( int v = std::max( 0, REPEATED_GRAIN_MIN_FREQ - u ); v < N; v++ ) |
547 | 0 | { |
548 | 0 | energy += spectrum[ u * N + v ]; |
549 | 0 | } |
550 | 0 | } |
551 | 0 | return energy; |
552 | 0 | } |
553 | | |
554 | | // Median of a non-empty list (reorders it). |
555 | | static double median( std::vector<double>& values ) |
556 | 0 | { |
557 | 0 | std::nth_element( values.begin(), values.begin() + values.size() / 2, values.end() ); |
558 | 0 | return values[ values.size() / 2 ]; |
559 | 0 | } |
560 | | |
561 | | // Expected power of the coefficients of the orthonormal 16x16 DCT-II of grain made by the AR filter of vvdec's SEI AR |
562 | | // mode (see FGAnalyzer::ArFilter), as spec[ vertical * 16 + horizontal ]: its power spectrum 1 / |1 - A(w)|^2, |
563 | | // integrated against the squared spectra of the DCT basis vectors on AR_SPECTRUM_BINS x AR_SPECTRUM_BINS frequencies. |
564 | | class ArSpectrum |
565 | | { |
566 | | public: |
567 | | ArSpectrum() |
568 | 0 | { |
569 | 0 | constexpr int N = 16; |
570 | 0 | constexpr double PI = 3.14159265358979323846; |
571 | 0 | for( int k = 0; k < AR_SPECTRUM_BINS; k++ ) |
572 | 0 | { |
573 | 0 | const double w = 2.0 * PI * k / AR_SPECTRUM_BINS; |
574 | 0 | m_cos[ k ] = std::cos( w ); |
575 | 0 | m_sin[ k ] = std::sin( w ); |
576 | 0 | for( int u = 0; u < N; u++ ) |
577 | 0 | { |
578 | 0 | double re = 0.0, im = 0.0; |
579 | 0 | for( int n = 0; n < N; n++ ) |
580 | 0 | { |
581 | 0 | const double b = std::sqrt( ( u ? 2.0 : 1.0 ) / N ) * std::cos( PI * ( 2 * n + 1 ) * u / ( 2 * N ) ); |
582 | 0 | re += b * std::cos( w * n ); |
583 | 0 | im -= b * std::sin( w * n ); |
584 | 0 | } |
585 | 0 | m_basisPower[ u ][ k ] = re * re + im * im; |
586 | 0 | } |
587 | 0 | } |
588 | 0 | } |
589 | | |
590 | | // Scratch space of compute(), reused by the caller over the calls of a fit. |
591 | | static constexpr size_t SCRATCH_SIZE = AR_SPECTRUM_BINS * AR_SPECTRUM_BINS + 16 * AR_SPECTRUM_BINS; |
592 | | |
593 | | // spec: 256 values, the DC coefficient set to 0 and the rest normalized to sum 1; returns the share of the power |
594 | | // outside the DC coefficient. scratch: SCRATCH_SIZE values. gain, if given, receives the filter's variance gain (the |
595 | | // mean of its power spectrum). |
596 | | double compute( double a1, double a3, double a5, double r, double* spec, std::vector<double>& scratch, double* gain = nullptr ) const |
597 | 0 | { |
598 | 0 | constexpr int N = 16, K = AR_SPECTRUM_BINS; |
599 | 0 | scratch.resize( SCRATCH_SIZE ); |
600 | 0 | double* psd = scratch.data(); |
601 | 0 | double* rows = psd + K * K; |
602 | 0 | double psdSum = 0.0; |
603 | 0 | for( int ky = 0; ky < K; ky++ ) |
604 | 0 | { |
605 | 0 | for( int kx = 0; kx < K; kx++ ) |
606 | 0 | { |
607 | | // A(w) = sum of coefficient * e^(-i w . offset) over the filter taps |
608 | 0 | const int sum = ( kx + ky ) % K, diff = ( ky - kx + K ) % K, x2 = ( 2 * kx ) % K, y2 = ( 2 * ky ) % K; |
609 | 0 | const double re = a1 * m_cos[ kx ] + a1 * r * m_cos[ ky ] + a3 * r * ( m_cos[ sum ] + m_cos[ diff ] ) |
610 | 0 | + a5 * m_cos[ x2 ] + a5 * r * r * m_cos[ y2 ]; |
611 | 0 | const double im = -( a1 * m_sin[ kx ] + a1 * r * m_sin[ ky ] + a3 * r * ( m_sin[ sum ] + m_sin[ diff ] ) |
612 | 0 | + a5 * m_sin[ x2 ] + a5 * r * r * m_sin[ y2 ] ); |
613 | 0 | psd[ ky * K + kx ] = 1.0 / std::max( ( 1.0 - re ) * ( 1.0 - re ) + im * im, 1e-6 ); |
614 | 0 | psdSum += psd[ ky * K + kx ]; |
615 | 0 | } |
616 | 0 | } |
617 | 0 | for( int v = 0; v < N; v++ ) |
618 | 0 | { |
619 | 0 | for( int kx = 0; kx < K; kx++ ) |
620 | 0 | { |
621 | 0 | double s = 0.0; |
622 | 0 | for( int ky = 0; ky < K; ky++ ) |
623 | 0 | { |
624 | 0 | s += m_basisPower[ v ][ ky ] * psd[ ky * K + kx ]; |
625 | 0 | } |
626 | 0 | rows[ v * K + kx ] = s; |
627 | 0 | } |
628 | 0 | } |
629 | 0 | double total = 0.0; |
630 | 0 | for( int v = 0; v < N; v++ ) |
631 | 0 | { |
632 | 0 | for( int h = 0; h < N; h++ ) |
633 | 0 | { |
634 | 0 | double s = 0.0; |
635 | 0 | for( int kx = 0; kx < K; kx++ ) |
636 | 0 | { |
637 | 0 | s += rows[ v * K + kx ] * m_basisPower[ h ][ kx ]; |
638 | 0 | } |
639 | 0 | spec[ v * N + h ] = s; |
640 | 0 | total += s; |
641 | 0 | } |
642 | 0 | } |
643 | 0 | const double nonDc = total - spec[ 0 ]; |
644 | 0 | spec[ 0 ] = 0.0; |
645 | 0 | for( int i = 0; i < N * N; i++ ) |
646 | 0 | { |
647 | 0 | spec[ i ] /= nonDc; |
648 | 0 | } |
649 | 0 | if( gain ) |
650 | 0 | { |
651 | 0 | *gain = psdSum / ( K * K ); |
652 | 0 | } |
653 | 0 | return nonDc / total; |
654 | 0 | } |
655 | | |
656 | | private: |
657 | | double m_cos[ AR_SPECTRUM_BINS ], m_sin[ AR_SPECTRUM_BINS ]; |
658 | | double m_basisPower[ 16 ][ AR_SPECTRUM_BINS ]; |
659 | | }; |
660 | | |
661 | | // The filter coefficients of vvdec's SEI AR mode as it computes them, in units of 2^-log2: left, top, diagonal |
662 | | // (top-left and top-right), left-left and top-top. |
663 | | struct ArTaps |
664 | | { |
665 | | int left, top, diag, leftLeft, topTop; |
666 | | ArTaps( const int c[ 6 ], int log2 ) |
667 | 0 | : left( c[ 1 ] ), top( ( c[ 1 ] * c[ 4 ] ) >> log2 ), diag( ( c[ 3 ] * c[ 4 ] ) >> log2 ), leftLeft( c[ 5 ] ), |
668 | 0 | topTop( ( c[ 5 ] * c[ 4 ] * c[ 4 ] ) >> ( 2 * log2 ) ) {} |
669 | | }; |
670 | | |
671 | | // Whether the recursion of vvdec's SEI AR mode, x = left * x(-1, 0) + leftLeft * x(-2, 0) + top * x(0, -1) |
672 | | // + diag * ( x(-1, -1) + x(1, -1) ) + topTop * x(0, -2) + noise, is stable, with poles at least the factor margin away |
673 | | // from the unit circle. It is a recursive filter on a non-symmetric half plane (the row above reaches to the right), stable |
674 | | // exactly when (Ekstrom and Woods, "Two-dimensional spectral factorization with applications in recursive digital |
675 | | // filtering", IEEE Trans. ASSP, 1976) |
676 | | // - the row part 1 - left z^-1 - leftLeft z^-2 has both roots inside the unit circle (Jury's conditions), and |
677 | | // - at every horizontal frequency w, the polynomial of the vertical delay v, c0 + c1 v + c2 v^2 with |
678 | | // c0 = 1 - left e^-iw - leftLeft e^-2iw, c1 = -( top + 2 diag cos w ) and c2 = -topTop, has no root with |v| <= 1. |
679 | | // The sum of the absolute tap weights below 1, the test used before, is sufficient but far from necessary: it rejects the |
680 | | // filters whose spectrum falls off toward the finest frequencies as film grain's does (a1 0.746, a3 -0.140, a5 -0.259, |
681 | | // r 0.89 has the sum 2.12 and is stable). On 260 random filters the test agreed with the recursion run on noise except |
682 | | // for 7 that it calls unstable and that had not grown yet after 160 rows. |
683 | | bool arFilterStable( double left, double top, double diag, double leftLeft, double topTop, double margin ) |
684 | 0 | { |
685 | 0 | constexpr double PI = 3.14159265358979323846; |
686 | | // the row part with z scaled by the margin: z^2 - l z - ll with both roots inside the unit circle |
687 | 0 | const double l = left * margin, ll = leftLeft * margin * margin; |
688 | 0 | if( std::fabs( ll ) >= 1.0 || 1.0 - l - ll <= 0.0 || 1.0 + l - ll <= 0.0 ) |
689 | 0 | { |
690 | 0 | return false; |
691 | 0 | } |
692 | 0 | const double c2 = -topTop; |
693 | 0 | for( int k = 0; k < AR_SPECTRUM_BINS; k++ ) |
694 | 0 | { |
695 | 0 | const double w = 2.0 * PI * k / AR_SPECTRUM_BINS; |
696 | 0 | const double c0re = 1.0 - left * std::cos( w ) - leftLeft * std::cos( 2.0 * w ); |
697 | 0 | const double c0im = left * std::sin( w ) + leftLeft * std::sin( 2.0 * w ); |
698 | 0 | const double c1 = -( top + 2.0 * diag * std::cos( w ) ); |
699 | 0 | if( std::fabs( c2 ) < 1e-12 ) |
700 | 0 | { |
701 | | // one root, v = -c0 / c1 |
702 | 0 | if( c0re * c0re + c0im * c0im <= margin * margin * c1 * c1 ) |
703 | 0 | { |
704 | 0 | return false; |
705 | 0 | } |
706 | 0 | continue; |
707 | 0 | } |
708 | | // the roots ( -c1 +- sqrt( c1^2 - 4 c2 c0 ) ) / ( 2 c2 ): the complex square root of the discriminant d |
709 | 0 | const double dre = c1 * c1 - 4.0 * c2 * c0re, dim = -4.0 * c2 * c0im; |
710 | 0 | const double mod = std::sqrt( dre * dre + dim * dim ); |
711 | 0 | const double sre = std::sqrt( std::max( 0.0, ( mod + dre ) / 2.0 ) ); |
712 | 0 | const double sim = ( dim < 0.0 ? -1.0 : 1.0 ) * std::sqrt( std::max( 0.0, ( mod - dre ) / 2.0 ) ); |
713 | 0 | const double limit = 2.0 * std::fabs( c2 ) * margin; // |root| > margin <=> |-c1 +- s| > limit |
714 | 0 | if( ( -c1 + sre ) * ( -c1 + sre ) + sim * sim <= limit * limit || ( -c1 - sre ) * ( -c1 - sre ) + sim * sim <= limit * limit ) |
715 | 0 | { |
716 | 0 | return false; |
717 | 0 | } |
718 | 0 | } |
719 | 0 | return true; |
720 | 0 | } |
721 | | |
722 | | // Energy of the impulse response of vvdec's AR filter with the signalled (integer) coefficients c[ 1 ] to c[ 5 ]. |
723 | | double arEnergy( const int c[ 6 ], int log2 ) |
724 | 0 | { |
725 | 0 | constexpr int SIZE = 96; |
726 | 0 | const ArTaps t( c, log2 ); |
727 | 0 | const double one = 1 << log2; |
728 | 0 | std::vector<double> h( SIZE * SIZE, 0.0 ); |
729 | 0 | double energy = 0.0; |
730 | 0 | for( int y = 0; y < SIZE; y++ ) |
731 | 0 | { |
732 | 0 | for( int x = 2; x < SIZE - 2; x++ ) |
733 | 0 | { |
734 | 0 | double g = t.left * h[ y * SIZE + x - 1 ] + t.leftLeft * h[ y * SIZE + x - 2 ]; |
735 | 0 | if( y >= 1 ) |
736 | 0 | { |
737 | 0 | g += t.top * h[ ( y - 1 ) * SIZE + x ] + t.diag * ( h[ ( y - 1 ) * SIZE + x - 1 ] + h[ ( y - 1 ) * SIZE + x + 1 ] ); |
738 | 0 | } |
739 | 0 | if( y >= 2 ) |
740 | 0 | { |
741 | 0 | g += t.topTop * h[ ( y - 2 ) * SIZE + x ]; |
742 | 0 | } |
743 | 0 | h[ y * SIZE + x ] = g / one + ( y == 0 && x == SIZE / 2 ? 1.0 : 0.0 ); |
744 | 0 | energy += h[ y * SIZE + x ] * h[ y * SIZE + x ]; |
745 | 0 | } |
746 | 0 | } |
747 | 0 | return energy; |
748 | 0 | } |
749 | | |
750 | | double ldpow( double n, unsigned p ) |
751 | 0 | { |
752 | 0 | double x = 1; |
753 | 0 | for( unsigned i = 0; i < p; i++ ) |
754 | 0 | { |
755 | 0 | x = x * n; |
756 | 0 | } |
757 | 0 | return x; |
758 | 0 | } |
759 | | |
760 | | Pel rowMax( const Pel* src, int n ) |
761 | 0 | { |
762 | 0 | return fgaRowMaxCore( src, n ); |
763 | 0 | } |
764 | | |
765 | | void classify( Pel* row, int n, Pel low, Pel high, Pel weak, Pel strong ) |
766 | 0 | { |
767 | 0 | fgaClassifyCore( row, n, low, high, weak, strong ); |
768 | 0 | } |
769 | | |
770 | | void sobelRow( const Pel* above, const Pel* cur, const Pel* below, int width, Pel maxVal, Pel* mag, Pel* dir ) |
771 | 0 | { |
772 | 0 | fgaSobelCore( above, cur, below, width, 0, width, maxVal, mag, dir ); |
773 | 0 | } |
774 | | |
775 | | void nonMaxRow( const Pel* magAbove, const Pel* mag, const Pel* magBelow, const Pel* dir, int width, Pel* dst ) |
776 | 0 | { |
777 | 0 | fgaNonMaxCore( magAbove, mag, magBelow, dir, width, 0, width, dst ); |
778 | 0 | } |
779 | | |
780 | | void morphRow( const Pel* src, int width, bool dilate, Pel* dst ) |
781 | 0 | { |
782 | 0 | fgaMorphRowCore( src, width, 0, width, dilate, dst ); |
783 | 0 | } |
784 | | |
785 | | void morphCol( const Pel* above, const Pel* cur, const Pel* below, int width, bool dilate, Pel* dst ) |
786 | 0 | { |
787 | 0 | fgaMorphColCore( above, cur, below, 0, width, dilate, dst ); |
788 | 0 | } |
789 | | |
790 | | // Gradient magnitude after non-maximum suppression along the edge direction. |
791 | | void gradientWithNonMaxSuppression( const FgaRowKernels& k, const Plane& p, Plane& out, int bitDepth, Plane& mag, Plane& dir ) |
792 | 0 | { |
793 | 0 | const int w = p.width, h = p.height; |
794 | 0 | const Pel maxVal = (Pel) ( ( 1 << bitDepth ) - 1 ); |
795 | 0 | mag.resize( w, h ); |
796 | 0 | dir.resize( w, h ); |
797 | 0 | for( int y = 0; y < h; y++ ) |
798 | 0 | { |
799 | 0 | k.sobel( p.row( std::max( y - 1, 0 ) ), p.row( y ), p.row( std::min( y + 1, h - 1 ) ), w, maxVal, mag.row( y ), dir.row( y ) ); |
800 | 0 | } |
801 | 0 | out.resize( w, h ); |
802 | 0 | for( int y = 0; y < h; y++ ) |
803 | 0 | { |
804 | 0 | k.nonMax( mag.row( std::max( y - 1, 0 ) ), mag.row( y ), mag.row( std::min( y + 1, h - 1 ) ), dir.row( y ), w, out.row( y ) ); |
805 | 0 | } |
806 | 0 | } |
807 | | |
808 | | // One 3x3 dilation or erosion of a binary mask (values 0 and "edge"): on such a mask, dilation is the 3x3 maximum and |
809 | | // erosion the 3x3 minimum, and both are separable. Borders are replicated. |
810 | | void morphStep( const FgaRowKernels& k, Plane& mask, Plane& tmp, bool dilate ) |
811 | 0 | { |
812 | 0 | const int w = mask.width, h = mask.height; |
813 | 0 | tmp.resize( w, h ); |
814 | 0 | for( int y = 0; y < h; y++ ) |
815 | 0 | { |
816 | 0 | k.morphRow( mask.row( y ), w, dilate, tmp.row( y ) ); |
817 | 0 | } |
818 | 0 | for( int y = 0; y < h; y++ ) |
819 | 0 | { |
820 | 0 | k.morphCol( tmp.row( std::max( y - 1, 0 ) ), tmp.row( y ), tmp.row( std::min( y + 1, h - 1 ) ), w, dilate, mask.row( y ) ); |
821 | 0 | } |
822 | 0 | } |
823 | | |
824 | | } // anonymous namespace |
825 | | |
826 | | // ==================================================================================================================== |
827 | | // Scalar kernels |
828 | | // ==================================================================================================================== |
829 | | |
830 | | Pel fgaRowMaxCore( const Pel* src, int n ) |
831 | 0 | { |
832 | 0 | Pel highest = 0; |
833 | 0 | for( int i = 0; i < n; i++ ) |
834 | 0 | { |
835 | 0 | highest = std::max( highest, src[ i ] ); |
836 | 0 | } |
837 | 0 | return highest; |
838 | 0 | } |
839 | | |
840 | | void fgaClassifyCore( Pel* row, int n, Pel low, Pel high, Pel weak, Pel strong ) |
841 | 0 | { |
842 | 0 | for( int i = 0; i < n; i++ ) |
843 | 0 | { |
844 | 0 | row[ i ] = row[ i ] > high ? strong : row[ i ] > low ? weak : 0; |
845 | 0 | } |
846 | 0 | } |
847 | | |
848 | | int fgaFindEqualCore( const Pel* row, int n, Pel value, int* positions ) |
849 | 0 | { |
850 | 0 | int count = 0; |
851 | 0 | for( int i = 0; i < n; i++ ) |
852 | 0 | { |
853 | 0 | if( row[ i ] == value ) |
854 | 0 | { |
855 | 0 | positions[ count++ ] = i; |
856 | 0 | } |
857 | 0 | } |
858 | 0 | return count; |
859 | 0 | } |
860 | | |
861 | | bool fgaIsZeroBlockCore( const Pel* src, int stride ) |
862 | 0 | { |
863 | 0 | for( int y = 0; y < 16; y++, src += stride ) |
864 | 0 | { |
865 | 0 | for( int x = 0; x < 16; x++ ) |
866 | 0 | { |
867 | 0 | if( src[ x ] ) |
868 | 0 | { |
869 | 0 | return false; |
870 | 0 | } |
871 | 0 | } |
872 | 0 | } |
873 | 0 | return true; |
874 | 0 | } |
875 | | |
876 | | void fgaBlockSumsCore( const Pel* src, int stride, int64_t& sum, int64_t& sumSq ) |
877 | 0 | { |
878 | 0 | sum = sumSq = 0; |
879 | 0 | for( int y = 0; y < 16; y++, src += stride ) |
880 | 0 | { |
881 | 0 | for( int x = 0; x < 16; x++ ) |
882 | 0 | { |
883 | 0 | sum += src[ x ]; |
884 | 0 | sumSq += src[ x ] * src[ x ]; |
885 | 0 | } |
886 | 0 | } |
887 | 0 | } |
888 | | |
889 | | void fgaResidualRowCore( const Pel* cur, const Pel* prev, const Pel* next, int n, Pel* dst ) |
890 | 0 | { |
891 | 0 | if( next ) |
892 | 0 | { |
893 | 0 | for( int x = 0; x < n; x++ ) |
894 | 0 | { |
895 | 0 | dst[ x ] = (Pel) ( 2 * cur[ x ] - prev[ x ] - next[ x ] ); |
896 | 0 | } |
897 | 0 | } |
898 | 0 | else |
899 | 0 | { |
900 | 0 | for( int x = 0; x < n; x++ ) |
901 | 0 | { |
902 | 0 | dst[ x ] = (Pel) ( cur[ x ] - prev[ x ] ); |
903 | 0 | } |
904 | 0 | } |
905 | 0 | } |
906 | | |
907 | | // VVC's 16-point DCT-II as a matrix multiplication, as VTM's film grain analysis computes it. |
908 | | void fgaSquaredDct16Core( const Pel* src, int stride, int maxRange, double* sum ) |
909 | 0 | { |
910 | 0 | constexpr int N = 16; |
911 | 0 | const TMatrixCoeff* tr = g_trCoreDCT2P16[ TRANSFORM_FORWARD ][ 0 ]; |
912 | 0 | int horizontal[ N ][ N ]; // [horizontal frequency][row] |
913 | 0 | for( int u = 0; u < N; u++ ) |
914 | 0 | { |
915 | 0 | for( int y = 0; y < N; y++ ) |
916 | 0 | { |
917 | 0 | const Pel* row = src + y * stride; |
918 | 0 | int acc = 0; |
919 | 0 | for( int k = 0; k < N; k++ ) |
920 | 0 | { |
921 | 0 | acc += tr[ u * N + k ] * row[ k ]; |
922 | 0 | } |
923 | 0 | horizontal[ u ][ y ] = ( acc + 128 ) >> 8; |
924 | 0 | } |
925 | 0 | } |
926 | 0 | for( int u = 0; u < N; u++ ) |
927 | 0 | { |
928 | 0 | for( int v = 0; v < N; v++ ) |
929 | 0 | { |
930 | 0 | int acc = 0; |
931 | 0 | for( int k = 0; k < N; k++ ) |
932 | 0 | { |
933 | 0 | acc += horizontal[ u ][ k ] * tr[ v * N + k ]; |
934 | 0 | } |
935 | 0 | const int64_t c = Clip3( -maxRange, maxRange, ( acc + 128 ) >> 8 ); |
936 | 0 | sum[ u * N + v ] += (double) ( c * c ); |
937 | 0 | } |
938 | 0 | } |
939 | 0 | } |
940 | | |
941 | | // Sobel gradients as in VTM: "gx" is the difference of the rows below and above (a vertical derivative), "gy" the |
942 | | // difference of the columns right and left. VTM quantizes the angle atan2(gx, gy) to 0, 45, 90 or 135 degrees with |
943 | | // bounds at 22.5 + k * 45 degrees. As tan(22.5) = sqrt(2) - 1 and tan(67.5) = sqrt(2) + 1, with a = |gx| and b = |gy| |
944 | | // a <= (sqrt(2) - 1) * b <=> (a + b)^2 <= 2 * b^2 : 0 degrees, |
945 | | // a > (sqrt(2) + 1) * b <=> a > b and (a - b)^2 > 2 * b^2 : 90 degrees, |
946 | | // otherwise 45 degrees when gx and gy have the same sign and 135 when not. This integer rule gives the same direction |
947 | | // as atan2 for every 10-bit gradient pair (checked exhaustively) and needs no floating point. |
948 | | void fgaSobelCore( const Pel* above, const Pel* cur, const Pel* below, int width, int xStart, int xEnd, Pel maxVal, Pel* mag, Pel* dir ) |
949 | 0 | { |
950 | 0 | for( int x = xStart; x < xEnd; x++ ) |
951 | 0 | { |
952 | 0 | const int l = std::max( x - 1, 0 ), r = std::min( x + 1, width - 1 ); |
953 | 0 | const int gx = ( below[ l ] + 2 * below[ x ] + below[ r ] ) - ( above[ l ] + 2 * above[ x ] + above[ r ] ); |
954 | 0 | const int gy = ( above[ r ] + 2 * cur[ r ] + below[ r ] ) - ( above[ l ] + 2 * cur[ l ] + below[ l ] ); |
955 | 0 | const int a = abs( gx ), b = abs( gy ); |
956 | 0 | mag[ x ] = (Pel) std::min<int>( ( a + b ) / 2, maxVal ); |
957 | 0 | if( ( a + b ) * ( a + b ) <= 2 * b * b ) |
958 | 0 | { |
959 | 0 | dir[ x ] = 0; |
960 | 0 | } |
961 | 0 | else if( a > b && ( a - b ) * ( a - b ) > 2 * b * b ) |
962 | 0 | { |
963 | 0 | dir[ x ] = 90; |
964 | 0 | } |
965 | 0 | else |
966 | 0 | { |
967 | 0 | dir[ x ] = ( gx ^ gy ) >= 0 ? 45 : 135; |
968 | 0 | } |
969 | 0 | } |
970 | 0 | } |
971 | | |
972 | | // Neighbours along the direction: 0 degrees compares left and right, 45 lower right and upper left, 90 above and |
973 | | // below, 135 lower left and upper right. |
974 | | void fgaNonMaxCore( const Pel* magAbove, const Pel* mag, const Pel* magBelow, const Pel* dir, int width, int xStart, int xEnd, Pel* dst ) |
975 | 0 | { |
976 | 0 | for( int x = xStart; x < xEnd; x++ ) |
977 | 0 | { |
978 | 0 | const int l = std::max( x - 1, 0 ), r = std::min( x + 1, width - 1 ); |
979 | 0 | Pel n1, n2; |
980 | 0 | switch( dir[ x ] ) |
981 | 0 | { |
982 | 0 | case 0: n1 = mag[ r ]; n2 = mag[ l ]; break; |
983 | 0 | case 45: n1 = magBelow[ r ]; n2 = magAbove[ l ]; break; |
984 | 0 | case 90: n1 = magBelow[ x ]; n2 = magAbove[ x ]; break; |
985 | 0 | default: n1 = magBelow[ l ]; n2 = magAbove[ r ]; break; |
986 | 0 | } |
987 | 0 | dst[ x ] = mag[ x ] < n1 || mag[ x ] < n2 ? 0 : mag[ x ]; |
988 | 0 | } |
989 | 0 | } |
990 | | |
991 | | void fgaMorphRowCore( const Pel* src, int width, int xStart, int xEnd, bool dilate, Pel* dst ) |
992 | 0 | { |
993 | 0 | for( int x = xStart; x < xEnd; x++ ) |
994 | 0 | { |
995 | 0 | const Pel l = src[ std::max( x - 1, 0 ) ], r = src[ std::min( x + 1, width - 1 ) ]; |
996 | 0 | dst[ x ] = dilate ? std::max( { l, src[ x ], r } ) : std::min( { l, src[ x ], r } ); |
997 | 0 | } |
998 | 0 | } |
999 | | |
1000 | | void fgaMorphColCore( const Pel* above, const Pel* cur, const Pel* below, int xStart, int xEnd, bool dilate, Pel* dst ) |
1001 | 0 | { |
1002 | 0 | for( int x = xStart; x < xEnd; x++ ) |
1003 | 0 | { |
1004 | 0 | dst[ x ] = dilate ? std::max( { above[ x ], cur[ x ], below[ x ] } ) : std::min( { above[ x ], cur[ x ], below[ x ] } ); |
1005 | 0 | } |
1006 | 0 | } |
1007 | | |
1008 | | Pel FGAnalyzer::Plane::clampedAt( int x, int y ) const |
1009 | 0 | { |
1010 | 0 | return at( Clip3( 0, width - 1, x ), Clip3( 0, height - 1, y ) ); |
1011 | 0 | } |
1012 | | |
1013 | | // ==================================================================================================================== |
1014 | | // Initialization |
1015 | | // ==================================================================================================================== |
1016 | | |
1017 | | FGAnalyzer::FGAnalyzer() |
1018 | 1.43k | { |
1019 | 1.43k | initKernels( m_kernels ); |
1020 | 1.43k | } |
1021 | | |
1022 | | void FGAnalyzer::initKernels( FgaRowKernels& k ) |
1023 | 2.86k | { |
1024 | 2.86k | k.sobel = sobelRow; |
1025 | 2.86k | k.nonMax = nonMaxRow; |
1026 | 2.86k | k.morphRow = morphRow; |
1027 | 2.86k | k.morphCol = morphCol; |
1028 | 2.86k | k.rowMax = rowMax; |
1029 | 2.86k | k.classify = classify; |
1030 | 2.86k | k.findEqual = fgaFindEqualCore; |
1031 | 2.86k | k.isZeroBlock = fgaIsZeroBlockCore; |
1032 | 2.86k | k.blockSums = fgaBlockSumsCore; |
1033 | 2.86k | k.squaredDct16 = fgaSquaredDct16Core; |
1034 | 2.86k | k.residualRow = fgaResidualRowCore; |
1035 | | #if ENABLE_SIMD_OPT_FGA && defined( TARGET_SIMD_X86 ) |
1036 | | initFGAnalyzerX86( k ); |
1037 | | #endif |
1038 | | #if ENABLE_SIMD_OPT_FGA && defined( TARGET_SIMD_ARM ) |
1039 | | initFGAnalyzerARM( k ); |
1040 | | #endif |
1041 | 2.86k | } |
1042 | | |
1043 | | void FGAnalyzer::init( int width, int height, ChromaFormat chromaFormat, const int bitDepths[ MAX_NUM_CH ], const bool doAnalysis[ MAX_NUM_COMP ], bool improved, bool arModel ) |
1044 | 0 | { |
1045 | 0 | m_improved = improved || arModel; |
1046 | 0 | m_arModel = arModel; |
1047 | 0 | for( ArFilter& f : m_arFilter ) |
1048 | 0 | { |
1049 | 0 | f = ArFilter(); |
1050 | 0 | } |
1051 | 0 | m_strengthScale = m_improved ? IMPROVED_STRENGTH_SCALE : 1; |
1052 | 0 | m_width = width; |
1053 | 0 | m_height = height; |
1054 | 0 | m_chromaFormat = chromaFormat; |
1055 | 0 | for( int ch = 0; ch < MAX_NUM_CH; ch++ ) |
1056 | 0 | { |
1057 | 0 | m_bitDepths[ ch ] = bitDepths[ ch ]; |
1058 | 0 | } |
1059 | | |
1060 | | // No grain is signalled until an analysis has measured it. VTM signals default parameters (scaling factor 16 for |
1061 | | // luma and 8 for chroma) until its first successful fit, which adds strong grain to video without grain, where the |
1062 | | // fit never succeeds. |
1063 | 0 | for( int c = 0; c < MAX_NUM_COMP; c++ ) |
1064 | 0 | { |
1065 | 0 | SeiFgc::CompModel& cm = m_compModel[ c ]; |
1066 | 0 | cm.presentFlag = false; |
1067 | 0 | cm.numModelValues = 1; |
1068 | 0 | cm.numIntensityIntervals = 0; |
1069 | 0 | cm.intensityValues.resize( MAX_NUM_INTENSITIES ); |
1070 | 0 | for( auto& iv : cm.intensityValues ) |
1071 | 0 | { |
1072 | 0 | iv.intensityIntervalLowerBound = 0; |
1073 | 0 | iv.intensityIntervalUpperBound = 0; |
1074 | 0 | iv.compModelValue.assign( MAX_ALLOWED_MODEL_VALUES, 0 ); |
1075 | 0 | } |
1076 | 0 | m_doAnalysis[ c ] = doAnalysis[ c ]; |
1077 | 0 | m_cutoffPairs[ c ] = 0; |
1078 | 0 | m_failedFits [ c ] = 0; |
1079 | 0 | resetStatistics( c ); |
1080 | 0 | } |
1081 | 0 | } |
1082 | | |
1083 | | // Drops the data accumulated over the analysed pictures of a component. |
1084 | | void FGAnalyzer::resetStatistics( int c ) |
1085 | 0 | { |
1086 | 0 | const int numMeans = 1 << m_bitDepths[ toChannelType( ComponentID( c ) ) ]; |
1087 | 0 | m_squaredDctSums[ c ].assign( numMeans, SquaredDctSum( BLOCK_SIZE * BLOCK_SIZE, 0.0 ) ); |
1088 | 0 | m_numDctBlocks [ c ].assign( numMeans, 0.0 ); |
1089 | 0 | m_storedMeanIntensity[ c ].clear(); |
1090 | 0 | m_storedStrengthIntensity[ c ].clear(); |
1091 | 0 | m_storedElementsPerInterval[ c ].clear(); |
1092 | 0 | } |
1093 | | |
1094 | | // VTM's scaling factors: twice the standard deviation, at log2 scale factor 2. As in getSignalledParameters(), the 4:2:0 |
1095 | | // chroma cut-off frequencies are halved and the scaling factors stay at MAX_SCALING_FACTOR or below. |
1096 | | void FGAnalyzer::getVtmParameters( double strength, int& log2ScaleFactor, SeiFgc::CompModel compModel[ MAX_NUM_COMP ] ) const |
1097 | 0 | { |
1098 | 0 | log2ScaleFactor = 2; |
1099 | 0 | for( int c = 0; c < MAX_NUM_COMP; c++ ) |
1100 | 0 | { |
1101 | 0 | SeiFgc::CompModel& cm = compModel[ c ]; |
1102 | 0 | cm = m_compModel[ c ]; |
1103 | 0 | if( !cm.presentFlag || strength <= 0.0 ) |
1104 | 0 | { |
1105 | 0 | cm.presentFlag = false; |
1106 | 0 | continue; |
1107 | 0 | } |
1108 | 0 | const bool chroma420 = c != COMP_Y && m_chromaFormat == CHROMA_420; |
1109 | 0 | const int bitDepth = m_bitDepths[ toChannelType( ComponentID( c ) ) ]; |
1110 | 0 | bool anyGrain = false; |
1111 | 0 | for( int i = 0; i < cm.numIntensityIntervals; i++ ) |
1112 | 0 | { |
1113 | 0 | std::vector<int>& v = cm.intensityValues[ i ].compModelValue; |
1114 | 0 | for( int k = 1; chroma420 && k < cm.numModelValues; k++ ) |
1115 | 0 | { |
1116 | 0 | v[ k ] = Clip3( 2, 14, ( v[ k ] + 1 ) >> 1 ); |
1117 | 0 | } |
1118 | 0 | const int scale = ( v[ 0 ] << log2ScaleFactor ) >> ( bitDepth - BIT_DEPTH_8 ); |
1119 | 0 | v[ 0 ] = std::min( MAX_SCALING_FACTOR, (int) ( scale * strength + 0.5 ) ); |
1120 | 0 | anyGrain = anyGrain || v[ 0 ] > 0; |
1121 | 0 | } |
1122 | 0 | cm.presentFlag = anyGrain; |
1123 | 0 | } |
1124 | 0 | } |
1125 | | |
1126 | | // The parameters of the auto-regressive model: model values scale, a1, 0 (no correlation between the components), a3, |
1127 | | // r and a5, the last four in units of 2^-log2ScaleFactor. The scaling factors are calibrated with the impulse response |
1128 | | // energy of the quantized filter (AR_PATTERN_STDDEV); the log2 scale factor is the largest (2 to 7) at which they stay |
1129 | | // at MAX_SCALING_FACTOR or below, for the finest steps of both the scaling factors and the filter coefficients, and at |
1130 | | // which the quantized filters can be signalled (stable, coefficients in range). When the scaling factors fit at none of |
1131 | | // those, the smallest such log2 scale factor is taken and the scaling factors are limited (weaker grain); without any, no |
1132 | | // grain is signalled. |
1133 | | void FGAnalyzer::getArParameters( double strength, int& log2ScaleFactor, SeiFgc::CompModel compModel[ MAX_NUM_COMP ] ) const |
1134 | 0 | { |
1135 | 0 | int smallestUsable = 0; |
1136 | 0 | for( log2ScaleFactor = 7; log2ScaleFactor >= 2; log2ScaleFactor-- ) |
1137 | 0 | { |
1138 | 0 | bool usable = true; |
1139 | 0 | const bool fits = arParametersAt( strength, log2ScaleFactor, compModel, usable ); |
1140 | 0 | if( fits && usable ) |
1141 | 0 | { |
1142 | 0 | return; |
1143 | 0 | } |
1144 | 0 | smallestUsable = usable ? log2ScaleFactor : smallestUsable; |
1145 | 0 | } |
1146 | 0 | log2ScaleFactor = std::max( smallestUsable, 2 ); |
1147 | 0 | bool usable = true; |
1148 | 0 | arParametersAt( strength, log2ScaleFactor, compModel, usable ); |
1149 | 0 | for( int c = 0; !usable && c < MAX_NUM_COMP; c++ ) |
1150 | 0 | { |
1151 | 0 | compModel[ c ].presentFlag = false; |
1152 | 0 | } |
1153 | 0 | } |
1154 | | |
1155 | | // H.274 limits the model values of the auto-regressive model to +-2^(film grain bit depth - 1). Without a separate colour |
1156 | | // description in the SEI (as here) FFmpeg takes that bit depth as 8: it accepts only [-128, 127] and drops the whole |
1157 | | // access unit otherwise. The ratio r of the vertical to the horizontal correlation is above 1 where the grain is |
1158 | | // correlated further vertically, and then exceeds 127 at log2 scale factor 7 (gangster_chase: 128-147 in 48 of 712 SEIs). |
1159 | | static constexpr int MIN_AR_COEFFICIENT = -128; |
1160 | | static constexpr int MAX_AR_COEFFICIENT = 127; |
1161 | | |
1162 | | // Sets the parameters of the auto-regressive model for one log2 scale factor. Returns whether all scaling factors stay |
1163 | | // at MAX_SCALING_FACTOR or below (they are limited to it); usable: whether every component's quantized filter is stable, |
1164 | | // with its upper taps computed as vvdec computes them (ArTaps), and has all coefficients in [MIN_AR_COEFFICIENT, |
1165 | | // MAX_AR_COEFFICIENT]. |
1166 | | bool FGAnalyzer::arParametersAt( double strength, int log2ScaleFactor, SeiFgc::CompModel compModel[ MAX_NUM_COMP ], bool& usable ) const |
1167 | 0 | { |
1168 | 0 | const int one = 1 << log2ScaleFactor; |
1169 | 0 | bool fits = true; |
1170 | 0 | usable = true; |
1171 | 0 | for( int c = 0; c < MAX_NUM_COMP; c++ ) |
1172 | 0 | { |
1173 | 0 | SeiFgc::CompModel& cm = compModel[ c ]; |
1174 | 0 | cm = m_compModel[ c ]; |
1175 | 0 | const ArFilter& f = m_arFilter[ c ]; |
1176 | 0 | if( !cm.presentFlag || strength <= 0.0 || !f.valid ) |
1177 | 0 | { |
1178 | 0 | cm.presentFlag = false; |
1179 | 0 | continue; |
1180 | 0 | } |
1181 | 0 | const int coef[ 6 ] = { 0, (int) std::lround( f.a1 * one ), 0, (int) std::lround( f.a3 * one ), (int) std::lround( f.r * one ), |
1182 | 0 | (int) std::lround( f.a5 * one ) }; |
1183 | 0 | const ArTaps taps( coef, log2ScaleFactor ); |
1184 | 0 | const double unit = 1.0 / one; |
1185 | 0 | usable = usable && arFilterStable( taps.left * unit, taps.top * unit, taps.diag * unit, taps.leftLeft * unit, taps.topTop * unit, 1.0 ); |
1186 | 0 | for( int k = 1; k < 6; k++ ) |
1187 | 0 | { |
1188 | 0 | usable = usable && coef[ k ] >= MIN_AR_COEFFICIENT && coef[ k ] <= MAX_AR_COEFFICIENT; |
1189 | 0 | } |
1190 | 0 | const int bitDepth = m_bitDepths[ toChannelType( ComponentID( c ) ) ]; |
1191 | 0 | const double patternStddev = AR_PATTERN_STDDEV[ c == COMP_Y ? 0 : 1 ] * std::sqrt( arEnergy( coef, log2ScaleFactor ) ); |
1192 | 0 | bool anyGrain = false; |
1193 | 0 | cm.numModelValues = 6; |
1194 | 0 | for( int i = 0; i < cm.numIntensityIntervals; i++ ) |
1195 | 0 | { |
1196 | 0 | std::vector<int>& v = cm.intensityValues[ i ].compModelValue; |
1197 | 0 | const double stddev = v[ 0 ] / ( 2.0 * m_strengthScale ) * std::sqrt( f.powerScale / f.nonDcShare ); |
1198 | 0 | const double scale = std::ldexp( stddev * strength, log2ScaleFactor + 10 - bitDepth ) / patternStddev; |
1199 | 0 | fits = fits && scale <= MAX_SCALING_FACTOR + 0.5; |
1200 | 0 | v.assign( 6, 0 ); |
1201 | 0 | v[ 0 ] = std::min( MAX_SCALING_FACTOR, (int) ( scale + 0.5 ) ); |
1202 | 0 | std::copy( coef + 1, coef + 6, v.begin() + 1 ); |
1203 | 0 | anyGrain = anyGrain || v[ 0 ] > 0; |
1204 | 0 | } |
1205 | 0 | cm.presentFlag = anyGrain; |
1206 | 0 | } |
1207 | 0 | return fits; |
1208 | 0 | } |
1209 | | |
1210 | | // The scaling factors are calibrated, because the standard deviation of the synthesized grain depends on the cut-off |
1211 | | // frequencies by a factor of up to 5 (PATTERN_STDDEV), and the block measurement misses up to 9% of the grain |
1212 | | // variance (BLOCK_VARIANCE_SHARE). VTM signals twice the standard deviation, which fits only cut-off frequencies near 8. |
1213 | | // The log2 scale factor is the largest (2 to 7, the range of the synthesis) at which all scaling factors stay at |
1214 | | // MAX_SCALING_FACTOR or below, for the finest steps. |
1215 | | void FGAnalyzer::getSignalledParameters( double strength, int& log2ScaleFactor, SeiFgc::CompModel compModel[ MAX_NUM_COMP ] ) const |
1216 | 0 | { |
1217 | 0 | if( !m_improved ) |
1218 | 0 | { |
1219 | 0 | getVtmParameters( strength, log2ScaleFactor, compModel ); |
1220 | 0 | return; |
1221 | 0 | } |
1222 | 0 | if( m_arModel ) |
1223 | 0 | { |
1224 | 0 | getArParameters( strength, log2ScaleFactor, compModel ); |
1225 | 0 | return; |
1226 | 0 | } |
1227 | 0 | std::vector<double> scales[ MAX_NUM_COMP ]; // per interval, at log2 scale factor 0 |
1228 | 0 | double maxScale = 0.0; |
1229 | 0 | for( int c = 0; c < MAX_NUM_COMP; c++ ) |
1230 | 0 | { |
1231 | 0 | SeiFgc::CompModel& cm = compModel[ c ]; |
1232 | 0 | cm = m_compModel[ c ]; |
1233 | 0 | if( !cm.presentFlag || strength <= 0.0 ) |
1234 | 0 | { |
1235 | 0 | cm.presentFlag = false; |
1236 | 0 | continue; |
1237 | 0 | } |
1238 | | // The analysis measures the chroma grain on the subsampled chroma planes, but for 4:2:0 the synthesis (VTM, vvdec) |
1239 | | // treats the chroma cut-off frequencies as luma resolution values and doubles them: they are halved here. Its |
1240 | | // halving of the chroma scaling factors is part of the chroma calibration tables. |
1241 | 0 | const bool chroma420 = c != COMP_Y && m_chromaFormat == CHROMA_420; |
1242 | 0 | const int table = chroma420 ? 1 : 0; |
1243 | 0 | const int bitDepth = m_bitDepths[ toChannelType( ComponentID( c ) ) ]; |
1244 | 0 | for( int i = 0; i < cm.numIntensityIntervals; i++ ) |
1245 | 0 | { |
1246 | 0 | std::vector<int>& v = cm.intensityValues[ i ].compModelValue; |
1247 | 0 | for( int k = 1; chroma420 && k < cm.numModelValues; k++ ) |
1248 | 0 | { |
1249 | 0 | v[ k ] = Clip3( 2, 14, ( v[ k ] + 1 ) >> 1 ); |
1250 | 0 | } |
1251 | 0 | const int h = cm.numModelValues > 1 ? Clip3( 2, 14, v[ 1 ] ) : 8; |
1252 | 0 | const int w = cm.numModelValues > 2 ? Clip3( 2, 14, v[ 2 ] ) : h; |
1253 | 0 | const double stddev = v[ 0 ] / ( 2.0 * m_strengthScale ) / std::sqrt( BLOCK_VARIANCE_SHARE[ table ][ h - 2 ][ w - 2 ] ); |
1254 | 0 | scales[ c ].push_back( stddev * strength * ( 1 << ( 14 - bitDepth ) ) / PATTERN_STDDEV[ table ][ h - 2 ][ w - 2 ] ); |
1255 | 0 | maxScale = std::max( maxScale, scales[ c ].back() ); |
1256 | 0 | } |
1257 | 0 | } |
1258 | |
|
1259 | 0 | log2ScaleFactor = 7; |
1260 | 0 | while( log2ScaleFactor > 2 && maxScale * ( 1 << log2ScaleFactor ) > MAX_SCALING_FACTOR + 0.5 ) |
1261 | 0 | { |
1262 | 0 | log2ScaleFactor--; |
1263 | 0 | } |
1264 | 0 | for( int c = 0; c < MAX_NUM_COMP; c++ ) |
1265 | 0 | { |
1266 | 0 | SeiFgc::CompModel& cm = compModel[ c ]; |
1267 | 0 | if( !cm.presentFlag ) |
1268 | 0 | { |
1269 | 0 | continue; |
1270 | 0 | } |
1271 | 0 | bool anyGrain = false; |
1272 | 0 | for( int i = 0; i < cm.numIntensityIntervals; i++ ) |
1273 | 0 | { |
1274 | 0 | int& scale = cm.intensityValues[ i ].compModelValue[ 0 ]; |
1275 | 0 | scale = std::min( MAX_SCALING_FACTOR, (int) ( scales[ c ][ i ] * ( 1 << log2ScaleFactor ) + 0.5 ) ); |
1276 | 0 | anyGrain = anyGrain || scale > 0; |
1277 | 0 | } |
1278 | 0 | cm.presentFlag = anyGrain; |
1279 | 0 | } |
1280 | 0 | } |
1281 | | |
1282 | | // ==================================================================================================================== |
1283 | | // Analysis of one picture |
1284 | | // ==================================================================================================================== |
1285 | | |
1286 | | void FGAnalyzer::estimateGrainParameters( const CPelUnitBuf& orig, const CPelUnitBuf& denoised, const CPelUnitBuf* residual, int residualWeight, |
1287 | | bool sceneCut ) |
1288 | 0 | { |
1289 | 0 | const int numComp = getNumberValidComponents( m_chromaFormat ); |
1290 | 0 | m_grainWeight = residual ? residualWeight : 1; |
1291 | 0 | m_plateaus.clear(); |
1292 | 0 | if( m_improved && m_doAnalysis[ COMP_Y ] ) // --fga 1 stays the VTM analysis |
1293 | 0 | { |
1294 | 0 | m_plateaus = findPlateaus( m_kernels, orig.get( COMP_Y ), m_bitDepths[ CH_L ] ); |
1295 | 0 | } |
1296 | 0 | for( int c = 0; c < numComp; c++ ) |
1297 | 0 | { |
1298 | 0 | const ComponentID compId = ComponentID( c ); |
1299 | 0 | const CPelBuf o = orig.get( compId ); |
1300 | 0 | const CPelBuf d = denoised.get( compId ); |
1301 | 0 | Plane& spatial = m_scratch.spatial; // the spatial grain estimate, needed beside the temporal residual |
1302 | 0 | m_repeatedGrainRatio[ c ].assign( NUM_REPEATED_GRAIN_BINS, 1.0 ); |
1303 | 0 | m_denoised[ c ].resize( d.width, d.height ); |
1304 | 0 | m_grain [ c ].resize( d.width, d.height ); |
1305 | 0 | if( residual ) |
1306 | 0 | { |
1307 | 0 | spatial.resize( d.width, d.height ); |
1308 | 0 | } |
1309 | 0 | for( int y = 0; y < (int) o.height; y++ ) |
1310 | 0 | { |
1311 | 0 | const Pel* ro = o.bufAt( 0, y ); |
1312 | 0 | const Pel* rd = d.bufAt( 0, y ); |
1313 | 0 | Pel* td = m_denoised[ c ].row( y ); |
1314 | 0 | Pel* tg = residual ? spatial.row( y ) : m_grain[ c ].row( y ); |
1315 | 0 | std::copy( rd, rd + o.width, td ); |
1316 | 0 | for( int x = 0; x < (int) o.width; x++ ) |
1317 | 0 | { |
1318 | 0 | tg[ x ] = (Pel) ( rd[ x ] - ro[ x ] ); |
1319 | 0 | } |
1320 | 0 | if( residual ) |
1321 | 0 | { |
1322 | 0 | const Pel* rr = residual->get( compId ).bufAt( 0, y ); |
1323 | 0 | std::copy( rr, rr + o.width, m_grain[ c ].row( y ) ); |
1324 | 0 | } |
1325 | 0 | } |
1326 | 0 | if( m_doAnalysis[ c ] ) |
1327 | 0 | { |
1328 | 0 | findMask( compId ); |
1329 | 0 | if( residual && markMotionFailures( compId ) ) |
1330 | 0 | { |
1331 | | // The motion compensation failed on most of the picture: its grain measurement is mostly picture structure. |
1332 | | // Nothing is updated, so the model of the last good picture stays. This comes before the scene-cut reset on |
1333 | | // purpose: a failed picture at a cut keeps the old scene's model until the next good picture, which resets the |
1334 | | // statistics only when its grain differs by more than GRAIN_CHANGE_RATIO (else old and new data mix). |
1335 | 0 | return; |
1336 | 0 | } |
1337 | | // both need this component's spatial estimate, which the next component overwrites |
1338 | 0 | if( m_improved && ( residual || isLuma( compId ) ) ) |
1339 | 0 | { |
1340 | 0 | measureFineDetail( compId, residual ? spatial : m_grain[ c ] ); |
1341 | 0 | } |
1342 | 0 | if( residual ) |
1343 | 0 | { |
1344 | 0 | measureRepeatedGrain( compId ); |
1345 | 0 | } |
1346 | 0 | } |
1347 | 0 | } |
1348 | 0 | for( int c = 0; sceneCut && c < numComp; c++ ) |
1349 | 0 | { |
1350 | 0 | resetStatistics( c ); |
1351 | 0 | } |
1352 | |
|
1353 | 0 | m_cutoffPairs[ COMP_Y ] = m_cutoffPairs[ COMP_Cb ] = m_cutoffPairs[ COMP_Cr ] = 0; |
1354 | 0 | for( int c = 0; c < numComp; c++ ) |
1355 | 0 | { |
1356 | 0 | estimateComponent( ComponentID( c ) ); |
1357 | 0 | } |
1358 | 0 | } |
1359 | | |
1360 | | // Marks the flat blocks of one component whose temporal residual reads far more grain than the spatial estimate |
1361 | | // (MOTION_FAILURE_RATIO). Returns true when luma failed on most flat blocks of the picture (MAX_MOTION_FAILURE_SHARE, |
1362 | | // with at least GRAIN_CHANGE_MIN_BLOCKS flat blocks): then the picture is not used. |
1363 | | bool FGAnalyzer::markMotionFailures( ComponentID compId ) |
1364 | 0 | { |
1365 | 0 | const int bitDepth = m_bitDepths[ toChannelType( compId ) ]; |
1366 | 0 | const int maxStrength = MAX_REAL_SCALE << ( bitDepth - BIT_DEPTH_8 ); |
1367 | 0 | const double minSpatial = MIN_SPATIAL_STDDEV * ( 1 << ( bitDepth - BIT_DEPTH_8 ) ); |
1368 | 0 | const Plane& denoised = m_denoised[ compId ]; |
1369 | 0 | const int blocksX = denoised.width / BLOCK_SIZE; |
1370 | 0 | std::vector<uint8_t>& failed = m_motionFailed[ compId ]; |
1371 | 0 | failed.assign( (size_t) blocksX * ( denoised.height / BLOCK_SIZE ), 0 ); |
1372 | |
|
1373 | 0 | int numFlat = 0, numFailed = 0; |
1374 | 0 | for( int y = 0; y + BLOCK_SIZE <= denoised.height; y += BLOCK_SIZE ) |
1375 | 0 | { |
1376 | 0 | for( int x = 0; x + BLOCK_SIZE <= denoised.width; x += BLOCK_SIZE ) |
1377 | 0 | { |
1378 | 0 | BlockStats picStats; |
1379 | 0 | if( !isFlatBlock( m_kernels, m_mask[ compId ], denoised, x, y, maxStrength, picStats ) ) |
1380 | 0 | { |
1381 | 0 | continue; |
1382 | 0 | } |
1383 | 0 | const double temporal = meanStdDev( m_kernels, m_grain[ compId ], x, y ).stddev; |
1384 | 0 | const double spatial = std::max( meanStdDev( m_kernels, m_scratch.spatial, x, y ).stddev, minSpatial ); |
1385 | 0 | numFlat++; |
1386 | 0 | if( temporal * temporal > MOTION_FAILURE_RATIO * m_grainWeight * spatial * spatial ) |
1387 | 0 | { |
1388 | 0 | failed[ ( y / BLOCK_SIZE ) * blocksX + x / BLOCK_SIZE ] = 1; |
1389 | 0 | numFailed++; |
1390 | 0 | } |
1391 | 0 | } |
1392 | 0 | } |
1393 | 0 | return isLuma( compId ) && numFlat >= GRAIN_CHANGE_MIN_BLOCKS && numFailed > MAX_MOTION_FAILURE_SHARE * numFlat; |
1394 | 0 | } |
1395 | | |
1396 | | // The energy of the finest frequencies (highFrequencyEnergy) of the original's 16x16 blocks, in m_fineEnergy: of every |
1397 | | // block of luma (addSmoothBlockPoints), of the flat blocks only of chroma (measureRepeatedGrain reads no others; the |
1398 | | // rest stay 0). spatialGrain: the denoised picture minus the original. |
1399 | | void FGAnalyzer::measureFineDetail( ComponentID compId, const Plane& spatialGrain ) |
1400 | 0 | { |
1401 | 0 | const int bitDepth = m_bitDepths[ toChannelType( compId ) ]; |
1402 | 0 | const int maxStrength = MAX_REAL_SCALE << ( bitDepth - BIT_DEPTH_8 ); |
1403 | 0 | const Plane& denoised = m_denoised[ compId ]; |
1404 | 0 | const int blocksX = denoised.width / BLOCK_SIZE; |
1405 | 0 | std::vector<double>& energy = m_fineEnergy[ compId ]; |
1406 | 0 | energy.assign( (size_t) blocksX * ( denoised.height / BLOCK_SIZE ), 0.0 ); |
1407 | 0 | for( int y = 0; y + BLOCK_SIZE <= denoised.height; y += BLOCK_SIZE ) |
1408 | 0 | { |
1409 | 0 | for( int x = 0; x + BLOCK_SIZE <= denoised.width; x += BLOCK_SIZE ) |
1410 | 0 | { |
1411 | 0 | BlockStats picStats; |
1412 | 0 | if( !isLuma( compId ) && !isFlatBlock( m_kernels, m_mask[ compId ], denoised, x, y, maxStrength, picStats ) ) |
1413 | 0 | { |
1414 | 0 | continue; |
1415 | 0 | } |
1416 | 0 | Pel original[ BLOCK_SIZE * BLOCK_SIZE ]; |
1417 | 0 | for( int j = 0; j < BLOCK_SIZE; j++ ) |
1418 | 0 | { |
1419 | 0 | const Pel* rd = denoised.row( y + j ) + x; |
1420 | 0 | const Pel* rs = spatialGrain.row( y + j ) + x; |
1421 | 0 | for( int i = 0; i < BLOCK_SIZE; i++ ) |
1422 | 0 | { |
1423 | 0 | original[ j * BLOCK_SIZE + i ] = (Pel) ( rd[ i ] - rs[ i ] ); |
1424 | 0 | } |
1425 | 0 | } |
1426 | 0 | energy[ ( y / BLOCK_SIZE ) * blocksX + x / BLOCK_SIZE ] = highFrequencyEnergy( m_kernels, original, BLOCK_SIZE, bitDepth ); |
1427 | 0 | } |
1428 | 0 | } |
1429 | 0 | } |
1430 | | |
1431 | | // The fine energy of a bin's typical smooth block: SMOOTH_BLOCK_PERCENTILE of its blocks' energies (reorders them). |
1432 | | static double typicalSmoothEnergy( std::vector<double>& energies ) |
1433 | 0 | { |
1434 | 0 | const size_t typical = energies.size() * SMOOTH_BLOCK_PERCENTILE / 100; |
1435 | 0 | std::nth_element( energies.begin(), energies.begin() + typical, energies.end() ); |
1436 | 0 | return energies[ typical ]; |
1437 | 0 | } |
1438 | | |
1439 | | // Adds scaling function points for the levels above the darkest measured one that have no flat blocks to measure the grain |
1440 | | // on. Per intensity bin, the fine energy of its typical smooth block (typicalSmoothEnergy of all its blocks' m_fineEnergy) |
1441 | | // is mostly grain: texture has little energy at the finest frequencies, and the smoothest blocks have the least of it. In |
1442 | | // the measured bins (MIN_SMOOTH_BIN_BLOCKS flat blocks) the grain strength per square root of that energy is known; their |
1443 | | // median is applied to every other bin, whose blocks each add a point at their own mean. The same reading on both sides |
1444 | | // lets its bias (the selection, the share of the grain at the finest frequencies) cancel: applied to the measured bins |
1445 | | // themselves it gives 0.67-1.29 times the flat blocks' strength on gangster_chase, nocturne and crowd_run (up to 2x on |
1446 | | // Top Gun's darkest bins). A clean highlight has no fine energy and gets next to no grain. |
1447 | | // Texture that is fine even in a bin's smoothest blocks reads as grain (the letters of Top Gun's credits read 5.0-5.4 |
1448 | | // against 1.3-1.5 on the sky beside them), so the reading is limited to the grain of the nearest measured bin on either |
1449 | | // side. |
1450 | | // On gangster_chase the synthesis then puts back, of the source's fine grain from 8-bit 177 up, 0.56-1.00 (was 0.43-0.56) |
1451 | | // with --fga 2 and 0.61-1.11 (was 0.42-0.50) with --fga 3; a limit at the strongest measured bin gave 0.86-1.34 with |
1452 | | // --fga 3 (too much) and no more than this one with --fga 2. |
1453 | | // The levels below the darkest measured bin keep its strength (holdDarkStrength). means, strengths: the points of the flat |
1454 | | // blocks (strengths in the analysis's units), to which the new points are added. |
1455 | | void FGAnalyzer::addSmoothBlockPoints( ComponentID compId, std::vector<int>& means, std::vector<int>& strengths ) const |
1456 | 0 | { |
1457 | 0 | const int bitDepth = m_bitDepths[ toChannelType( compId ) ]; |
1458 | 0 | const int binShift = bitDepth - SMOOTH_BIN_BITS; |
1459 | 0 | const Plane& denoised = m_denoised[ compId ]; |
1460 | 0 | const int blocksX = denoised.width / BLOCK_SIZE; |
1461 | | |
1462 | | // the flat blocks' mean strength per bin, and the bins they measure |
1463 | 0 | double flatStrength[ NUM_SMOOTH_BINS ] = {}; |
1464 | 0 | int flatBlocks [ NUM_SMOOTH_BINS ] = {}; |
1465 | 0 | for( size_t i = 0; i < means.size(); i++ ) |
1466 | 0 | { |
1467 | 0 | flatStrength[ means[ i ] >> binShift ] += strengths[ i ]; |
1468 | 0 | flatBlocks [ means[ i ] >> binShift ]++; |
1469 | 0 | } |
1470 | 0 | auto measured = [ &flatBlocks ]( int bin ) { return flatBlocks[ bin ] >= MIN_SMOOTH_BIN_BLOCKS; }; |
1471 | 0 | int darkestMeasured = NUM_SMOOTH_BINS; |
1472 | 0 | for( int bin = NUM_SMOOTH_BINS - 1; bin >= 0; bin-- ) |
1473 | 0 | { |
1474 | 0 | if( measured( bin ) ) |
1475 | 0 | { |
1476 | 0 | flatStrength[ bin ] /= flatBlocks[ bin ]; |
1477 | 0 | darkestMeasured = bin; |
1478 | 0 | } |
1479 | 0 | } |
1480 | | |
1481 | | // every block's mean and fine energy per bin, then the bin's typical smooth block |
1482 | 0 | std::vector<int> blockMeans [ NUM_SMOOTH_BINS ]; |
1483 | 0 | std::vector<double> blockEnergies[ NUM_SMOOTH_BINS ]; |
1484 | 0 | for( int y = 0; y + BLOCK_SIZE <= denoised.height; y += BLOCK_SIZE ) |
1485 | 0 | { |
1486 | 0 | for( int x = 0; x + BLOCK_SIZE <= denoised.width; x += BLOCK_SIZE ) |
1487 | 0 | { |
1488 | 0 | const int mean = meanStdDev( m_kernels, denoised, x, y ).mean; |
1489 | 0 | blockMeans [ mean >> binShift ].push_back( mean ); |
1490 | 0 | blockEnergies[ mean >> binShift ].push_back( m_fineEnergy[ compId ][ ( y / BLOCK_SIZE ) * blocksX + x / BLOCK_SIZE ] ); |
1491 | 0 | } |
1492 | 0 | } |
1493 | 0 | double smoothEnergy[ NUM_SMOOTH_BINS ] = {}; |
1494 | 0 | for( int bin = 0; bin < NUM_SMOOTH_BINS; bin++ ) |
1495 | 0 | { |
1496 | 0 | if( (int) blockEnergies[ bin ].size() >= MIN_SMOOTH_BIN_BLOCKS ) |
1497 | 0 | { |
1498 | 0 | smoothEnergy[ bin ] = typicalSmoothEnergy( blockEnergies[ bin ] ); |
1499 | 0 | } |
1500 | 0 | } |
1501 | | |
1502 | | // the measured bins: strength per square root of the smooth block's fine energy |
1503 | 0 | std::vector<double> strengthPerDetail; |
1504 | 0 | for( int bin = darkestMeasured; bin < NUM_SMOOTH_BINS; bin++ ) |
1505 | 0 | { |
1506 | 0 | if( measured( bin ) && smoothEnergy[ bin ] > 0.0 ) |
1507 | 0 | { |
1508 | 0 | strengthPerDetail.push_back( flatStrength[ bin ] / std::sqrt( smoothEnergy[ bin ] ) ); |
1509 | 0 | } |
1510 | 0 | } |
1511 | 0 | if( strengthPerDetail.empty() ) |
1512 | 0 | { |
1513 | 0 | return; // nothing measured to compare with |
1514 | 0 | } |
1515 | 0 | const double scale = median( strengthPerDetail ); |
1516 | |
|
1517 | 0 | double darkerStrength = 0.0; // of the nearest measured bin below |
1518 | 0 | for( int bin = darkestMeasured; bin < NUM_SMOOTH_BINS; bin++ ) |
1519 | 0 | { |
1520 | 0 | if( measured( bin ) ) |
1521 | 0 | { |
1522 | 0 | darkerStrength = flatStrength[ bin ]; |
1523 | 0 | continue; |
1524 | 0 | } |
1525 | 0 | if( (int) blockMeans[ bin ].size() < MIN_SMOOTH_BIN_BLOCKS ) |
1526 | 0 | { |
1527 | 0 | continue; // too few blocks for the typical smooth one: the fit and its fade-out bridge the bin |
1528 | 0 | } |
1529 | 0 | double limit = darkerStrength; // the stronger grain of the nearest measured bins below and above |
1530 | 0 | for( int brighter = bin + 1; brighter < NUM_SMOOTH_BINS; brighter++ ) |
1531 | 0 | { |
1532 | 0 | if( measured( brighter ) ) |
1533 | 0 | { |
1534 | 0 | limit = std::max( limit, flatStrength[ brighter ] ); |
1535 | 0 | break; |
1536 | 0 | } |
1537 | 0 | } |
1538 | 0 | const int strength = (int) ( std::min( limit, scale * std::sqrt( smoothEnergy[ bin ] ) ) + 0.5 ); |
1539 | 0 | for( int mean : blockMeans[ bin ] ) |
1540 | 0 | { |
1541 | 0 | means.push_back( mean ); |
1542 | 0 | strengths.push_back( strength ); |
1543 | 0 | } |
1544 | 0 | } |
1545 | 0 | } |
1546 | | |
1547 | | // The share of the grain that repeats from picture to picture, which the temporal residual does not see: per flat block |
1548 | | // that markMotionFailures kept, the high-frequency energy of the original over that of the residual per grain variance. |
1549 | | // m_repeatedGrainRatio gets, per intensity bin, the median of its blocks (the picture's median for a bin with fewer than |
1550 | | // MIN_REPEATED_GRAIN_BIN_BLOCKS), limited to [ 1, MAX_REPEATED_GRAIN_RATIO ] (see REPEATED_GRAIN_MIN_FREQ). A block |
1551 | | // whose original has no high frequencies counts with ratio 0: nothing repeats there (Top Gun's almost grain-free chroma). |
1552 | | void FGAnalyzer::measureRepeatedGrain( ComponentID compId ) |
1553 | 0 | { |
1554 | 0 | const int bitDepth = m_bitDepths[ toChannelType( compId ) ]; |
1555 | 0 | const int maxStrength = MAX_REAL_SCALE << ( bitDepth - BIT_DEPTH_8 ); |
1556 | 0 | const int binShift = bitDepth - REPEATED_GRAIN_BIN_BITS; |
1557 | 0 | const Plane& denoised = m_denoised[ compId ]; |
1558 | 0 | const Plane& residual = m_grain[ compId ]; |
1559 | 0 | const int blocksX = denoised.width / BLOCK_SIZE; |
1560 | 0 | std::vector<double>& ratios = m_scratch.repeatedGrainRatios; |
1561 | 0 | std::vector<std::vector<double>>& binRatios = m_scratch.repeatedGrainBinRatios; |
1562 | 0 | ratios.clear(); |
1563 | 0 | binRatios.resize( NUM_REPEATED_GRAIN_BINS ); |
1564 | 0 | for( std::vector<double>& v : binRatios ) |
1565 | 0 | { |
1566 | 0 | v.clear(); |
1567 | 0 | } |
1568 | 0 | for( int y = 0; y + BLOCK_SIZE <= denoised.height; y += BLOCK_SIZE ) |
1569 | 0 | { |
1570 | 0 | for( int x = 0; x + BLOCK_SIZE <= denoised.width; x += BLOCK_SIZE ) |
1571 | 0 | { |
1572 | 0 | BlockStats picStats; |
1573 | 0 | if( m_motionFailed[ compId ][ ( y / BLOCK_SIZE ) * blocksX + x / BLOCK_SIZE ] |
1574 | 0 | || !isFlatBlock( m_kernels, m_mask[ compId ], denoised, x, y, maxStrength, picStats ) ) |
1575 | 0 | { |
1576 | 0 | continue; |
1577 | 0 | } |
1578 | 0 | const double residualEnergy = highFrequencyEnergy( m_kernels, residual.row( y ) + x, residual.width, bitDepth ); |
1579 | 0 | if( residualEnergy > 0.0 ) |
1580 | 0 | { |
1581 | 0 | const double originalEnergy = m_fineEnergy[ compId ][ ( y / BLOCK_SIZE ) * blocksX + x / BLOCK_SIZE ]; |
1582 | 0 | const double ratio = originalEnergy * m_grainWeight / residualEnergy; |
1583 | 0 | ratios.push_back( ratio ); |
1584 | 0 | binRatios[ picStats.mean >> binShift ].push_back( ratio ); |
1585 | 0 | } |
1586 | 0 | } |
1587 | 0 | } |
1588 | 0 | if( (int) ratios.size() < GRAIN_CHANGE_MIN_BLOCKS ) |
1589 | 0 | { |
1590 | 0 | return; // too few blocks to tell: the ratios stay 1 |
1591 | 0 | } |
1592 | 0 | const double pictureRatio = median( ratios ); |
1593 | 0 | for( int i = 0; i < NUM_REPEATED_GRAIN_BINS; i++ ) |
1594 | 0 | { |
1595 | 0 | const double ratio = (int) binRatios[ i ].size() >= MIN_REPEATED_GRAIN_BIN_BLOCKS ? median( binRatios[ i ] ) : pictureRatio; |
1596 | 0 | m_repeatedGrainRatio[ compId ][ i ] = Clip3( 1.0, MAX_REPEATED_GRAIN_RATIO, ratio ); |
1597 | 0 | } |
1598 | 0 | } |
1599 | | |
1600 | | // Mask of the samples that are not part of a flat area: edges found at full, half and quarter resolution, dilated. |
1601 | | void FGAnalyzer::findMask( ComponentID compId ) |
1602 | 0 | { |
1603 | 0 | const int bitDepth = m_bitDepths[ toChannelType( compId ) ]; |
1604 | 0 | const Plane& picture = m_denoised[ compId ]; |
1605 | 0 | Plane& mask = m_mask[ compId ]; |
1606 | |
|
1607 | 0 | Scratch& s = m_scratch; |
1608 | 0 | subsample( picture, s.half, 2 ); |
1609 | 0 | subsample( picture, s.quarter, 4 ); |
1610 | |
|
1611 | 0 | maskForScale( picture, mask, bitDepth, 4 ); |
1612 | 0 | maskForScale( s.half, s.lowMask, bitDepth, 3 ); |
1613 | 0 | combineUpsampled( mask, s.lowMask, 2, s.wide ); |
1614 | 0 | maskForScale( s.quarter, s.lowMask, bitDepth, 2 ); |
1615 | 0 | combineUpsampled( mask, s.lowMask, 4, s.wide ); |
1616 | | |
1617 | | // final dilation to fill the holes, then erosion |
1618 | 0 | morphStep( m_kernels, mask, s.morph, true ); |
1619 | 0 | morphStep( m_kernels, mask, s.morph, true ); |
1620 | 0 | morphStep( m_kernels, mask, s.morph, false ); |
1621 | 0 | } |
1622 | | |
1623 | | void FGAnalyzer::maskForScale( const Plane& picture, Plane& mask, int bitDepth, int numDilations ) |
1624 | 0 | { |
1625 | 0 | Scratch& s = m_scratch; |
1626 | 0 | gradientWithNonMaxSuppression( m_kernels, picture, mask, bitDepth, s.magnitude, s.direction ); |
1627 | 0 | doubleThreshold( m_kernels, mask, bitDepth ); |
1628 | 0 | edgeTracking( m_kernels, mask, bitDepth, s ); |
1629 | 0 | suppressLowIntensity( picture, mask, bitDepth, m_improved ); |
1630 | 0 | for( int i = 0; i < numDilations; i++ ) |
1631 | 0 | { |
1632 | 0 | morphStep( m_kernels, mask, s.morph, true ); |
1633 | 0 | } |
1634 | 0 | } |
1635 | | |
1636 | | // Collects the block statistics of one component and estimates its parameters. |
1637 | | void FGAnalyzer::estimateComponent( ComponentID compId ) |
1638 | 0 | { |
1639 | 0 | if( !m_doAnalysis[ compId ] || ( compId > COMP_Y && !m_compModel[ COMP_Y ].presentFlag ) ) |
1640 | 0 | { |
1641 | 0 | m_compModel[ compId ].presentFlag = false; |
1642 | 0 | m_cutoffPairs[ compId ] = 0; |
1643 | 0 | return; |
1644 | 0 | } |
1645 | | |
1646 | 0 | const int bitDepth = m_bitDepths[ toChannelType( compId ) ]; |
1647 | 0 | const Plane& denoised = m_denoised[ compId ]; |
1648 | 0 | const Plane& grain = m_grain[ compId ]; |
1649 | 0 | const Plane& mask = m_mask[ compId ]; |
1650 | 0 | const int maxStrength = MAX_REAL_SCALE << ( bitDepth - BIT_DEPTH_8 ); |
1651 | |
|
1652 | 0 | static_assert( BLOCK_SIZE == 16, "the block kernels work on 16x16 blocks" ); |
1653 | 0 | std::vector<int> vecMean; |
1654 | 0 | std::vector<int> vecStrength; |
1655 | | |
1656 | | // older pictures count less |
1657 | 0 | for( size_t m = 0; m < m_numDctBlocks[ compId ].size(); m++ ) |
1658 | 0 | { |
1659 | 0 | if( m_numDctBlocks[ compId ][ m ] > 0 ) |
1660 | 0 | { |
1661 | 0 | m_numDctBlocks[ compId ][ m ] *= ACCUMULATION_DECAY; |
1662 | 0 | for( double& v : m_squaredDctSums[ compId ][ m ] ) |
1663 | 0 | { |
1664 | 0 | v *= ACCUMULATION_DECAY; |
1665 | 0 | } |
1666 | 0 | } |
1667 | 0 | } |
1668 | | |
1669 | | // The flat blocks, visited column by column as in VTM; the order matters for the floating point sums of the fit. |
1670 | 0 | struct FlatBlock |
1671 | 0 | { |
1672 | 0 | int x, y, mean; |
1673 | 0 | double stddev; // grain standard deviation |
1674 | 0 | double weight; // variance of m_grain per grain variance |
1675 | 0 | }; |
1676 | 0 | std::vector<FlatBlock> blocks; |
1677 | 0 | for( int x = 0; x + BLOCK_SIZE <= denoised.width; x += BLOCK_SIZE ) |
1678 | 0 | { |
1679 | 0 | for( int y = 0; y + BLOCK_SIZE <= denoised.height; y += BLOCK_SIZE ) |
1680 | 0 | { |
1681 | 0 | BlockStats picStats; |
1682 | 0 | if( !isFlatBlock( m_kernels, mask, denoised, x, y, maxStrength, picStats ) ) |
1683 | 0 | { |
1684 | 0 | continue; |
1685 | 0 | } |
1686 | 0 | if( m_grainWeight > 1 && m_motionFailed[ compId ][ ( y / BLOCK_SIZE ) * ( denoised.width / BLOCK_SIZE ) + x / BLOCK_SIZE ] ) |
1687 | 0 | { |
1688 | 0 | continue; // the motion compensation of the temporal residual failed here (markMotionFailures) |
1689 | 0 | } |
1690 | | // the residual's weight, less the grain it misses because it repeats (measureRepeatedGrain) |
1691 | 0 | const int bin = picStats.mean >> ( bitDepth - REPEATED_GRAIN_BIN_BITS ); |
1692 | 0 | const double weight = m_grainWeight / m_repeatedGrainRatio[ compId ][ bin ]; |
1693 | 0 | blocks.push_back( { x, y, picStats.mean, meanStdDev( m_kernels, grain, x, y ).stddev / std::sqrt( weight ), weight } ); |
1694 | 0 | } |
1695 | 0 | } |
1696 | | |
1697 | | // Where the motion compensation of the temporal residual failed, the residual of a block is much larger than the |
1698 | | // grain of the other blocks of its intensity: such blocks are left out. |
1699 | 0 | std::vector<double> maxVariance( NUM_OUTLIER_BINS, std::numeric_limits<double>::max() ); |
1700 | 0 | if( m_grainWeight > 1 ) |
1701 | 0 | { |
1702 | 0 | const int binShift = bitDepth - 4; |
1703 | 0 | std::vector<std::vector<double>> binVariances( NUM_OUTLIER_BINS ); |
1704 | 0 | for( const FlatBlock& b : blocks ) |
1705 | 0 | { |
1706 | 0 | binVariances[ b.mean >> binShift ].push_back( b.stddev * b.stddev ); |
1707 | 0 | } |
1708 | 0 | for( int i = 0; i < NUM_OUTLIER_BINS; i++ ) |
1709 | 0 | { |
1710 | 0 | std::vector<double>& v = binVariances[ i ]; |
1711 | 0 | if( (int) v.size() >= MIN_OUTLIER_BIN_BLOCKS ) |
1712 | 0 | { |
1713 | 0 | std::nth_element( v.begin(), v.begin() + v.size() / 2, v.end() ); |
1714 | 0 | maxVariance[ i ] = OUTLIER_VARIANCE_RATIO * v[ v.size() / 2 ]; |
1715 | 0 | } |
1716 | 0 | } |
1717 | 0 | } |
1718 | |
|
1719 | 0 | std::vector<const FlatBlock*> grainBlocks; |
1720 | 0 | for( const FlatBlock& b : blocks ) |
1721 | 0 | { |
1722 | 0 | if( b.stddev * b.stddev > maxVariance[ b.mean >> ( bitDepth - 4 ) ] ) |
1723 | 0 | { |
1724 | 0 | continue; // motion compensation failure |
1725 | 0 | } |
1726 | 0 | const int strength = (int) ( 2 * m_strengthScale * b.stddev + 0.5 ); |
1727 | 0 | if( strength >= maxStrength * m_strengthScale ) |
1728 | 0 | { |
1729 | 0 | continue; // too strong to be grain: probably texture or motion left in the grain estimate |
1730 | 0 | } |
1731 | 0 | vecMean.push_back( b.mean ); |
1732 | 0 | vecStrength.push_back( strength ); |
1733 | 0 | grainBlocks.push_back( &b ); |
1734 | 0 | } |
1735 | | |
1736 | | // When the grain of this picture is much stronger or weaker than that of the accumulated data, a new scene began: |
1737 | | // the accumulated data are dropped. Otherwise the second pass of the fit would discard the new scene's points as |
1738 | | // outliers of the old fit for several analyses, and the old grain would stay on. |
1739 | 0 | double storedStrength = 0.0, storedElements = 0.0; |
1740 | 0 | for( size_t i = 0; i < m_storedStrengthIntensity[ compId ].size(); i++ ) |
1741 | 0 | { |
1742 | 0 | storedStrength += m_storedStrengthIntensity [ compId ][ i ]; |
1743 | 0 | storedElements += m_storedElementsPerInterval[ compId ][ i ]; |
1744 | 0 | } |
1745 | 0 | if( m_improved && (int) vecStrength.size() >= GRAIN_CHANGE_MIN_BLOCKS && storedElements > 0.0 ) |
1746 | 0 | { |
1747 | 0 | const double mean = std::accumulate( vecStrength.begin(), vecStrength.end(), 0.0 ) / vecStrength.size(); |
1748 | 0 | const double stored = storedStrength / storedElements; |
1749 | 0 | if( mean > GRAIN_CHANGE_RATIO * stored || stored > GRAIN_CHANGE_RATIO * mean ) |
1750 | 0 | { |
1751 | 0 | resetStatistics( compId ); |
1752 | 0 | } |
1753 | 0 | } |
1754 | |
|
1755 | 0 | SquaredDctSum blockDct( BLOCK_SIZE * BLOCK_SIZE ); |
1756 | 0 | for( const FlatBlock* bp : grainBlocks ) |
1757 | 0 | { |
1758 | 0 | const FlatBlock& b = *bp; |
1759 | 0 | double* dctSum = m_squaredDctSums[ compId ][ b.mean ].data(); |
1760 | 0 | if( m_grainWeight == 1 ) |
1761 | 0 | { |
1762 | 0 | m_kernels.squaredDct16( grain.row( b.y ) + b.x, grain.width, ( 1 << ( bitDepth + 4 ) ) - 1, dctSum ); |
1763 | 0 | } |
1764 | 0 | else |
1765 | 0 | { |
1766 | | // the spectrum in grain units, so that pictures with one or two neighbours add up correctly |
1767 | 0 | std::fill( blockDct.begin(), blockDct.end(), 0.0 ); |
1768 | 0 | m_kernels.squaredDct16( grain.row( b.y ) + b.x, grain.width, ( 1 << ( bitDepth + 4 ) ) - 1, blockDct.data() ); |
1769 | 0 | for( int i = 0; i < BLOCK_SIZE * BLOCK_SIZE; i++ ) |
1770 | 0 | { |
1771 | 0 | dctSum[ i ] += blockDct[ i ] / b.weight; |
1772 | 0 | } |
1773 | 0 | } |
1774 | 0 | m_numDctBlocks[ compId ][ b.mean ]++; |
1775 | 0 | } |
1776 | |
|
1777 | 0 | if( m_improved && isLuma( compId ) ) |
1778 | 0 | { |
1779 | 0 | addSmoothBlockPoints( compId, vecMean, vecStrength ); // after the spectra: these points have no grain to add to them |
1780 | 0 | } |
1781 | 0 | estimateScalingFactors( vecMean, vecStrength, bitDepth, compId ); |
1782 | 0 | if( m_arModel ) |
1783 | 0 | { |
1784 | 0 | fitArFilter( compId ); |
1785 | 0 | } |
1786 | 0 | else |
1787 | 0 | { |
1788 | 0 | estimateCutoffFreq( compId, bitDepth ); |
1789 | 0 | } |
1790 | 0 | } |
1791 | | |
1792 | | // ==================================================================================================================== |
1793 | | // Scaling function |
1794 | | // ==================================================================================================================== |
1795 | | |
1796 | | void FGAnalyzer::estimateScalingFactors( std::vector<int>& dataX, std::vector<int>& dataY, int bitDepth, ComponentID compId ) |
1797 | 0 | { |
1798 | 0 | std::vector<double> coeffs; |
1799 | 0 | std::vector<double> scalingVec; |
1800 | 0 | std::vector<int> quantVec; |
1801 | | |
1802 | | // fit a polynomial to the points; the second pass removes points far from the first fit and stores the data |
1803 | 0 | bool valid = false; |
1804 | 0 | bool stored = false; |
1805 | 0 | for( int i = 0; i < NUM_PASSES; i++ ) |
1806 | 0 | { |
1807 | 0 | valid = fitFunction( dataX, dataY, coeffs, scalingVec, ORDER, bitDepth, i == 1, compId ); |
1808 | 0 | stored = i == 1; |
1809 | 0 | if( !valid ) |
1810 | 0 | { |
1811 | 0 | break; |
1812 | 0 | } |
1813 | 0 | } |
1814 | 0 | if( valid ) |
1815 | 0 | { |
1816 | 0 | valid = lloydMax( scalingVec, quantVec, QUANT_LEVELS, bitDepth ); |
1817 | 0 | } |
1818 | 0 | if( valid ) |
1819 | 0 | { |
1820 | 0 | setEstimatedParameters( quantVec, bitDepth, compId ); |
1821 | 0 | m_failedFits[ compId ] = 0; |
1822 | 0 | return; |
1823 | 0 | } |
1824 | 0 | if( !m_improved ) |
1825 | 0 | { |
1826 | 0 | return; // VTM keeps the previous parameters |
1827 | 0 | } |
1828 | | |
1829 | | // Without a fit, for example because there were too few points, the previous parameters are kept for a while (VTM |
1830 | | // keeps them for good). The stored data age as if a picture without data had been added, and after MAX_FAILED_FITS |
1831 | | // failures in a row the grain is no longer signalled, as it was measured on pictures too long ago: otherwise the |
1832 | | // grain of a grainy scene stays on in the following clean scene when the fit fails there. |
1833 | 0 | if( !stored ) |
1834 | 0 | { |
1835 | 0 | for( auto* data : { &m_storedMeanIntensity[ compId ], &m_storedStrengthIntensity[ compId ], &m_storedElementsPerInterval[ compId ] } ) |
1836 | 0 | { |
1837 | 0 | for( double& v : *data ) |
1838 | 0 | { |
1839 | 0 | v *= ACCUMULATION_DECAY; |
1840 | 0 | } |
1841 | 0 | } |
1842 | 0 | } |
1843 | 0 | if( ++m_failedFits[ compId ] >= MAX_FAILED_FITS ) |
1844 | 0 | { |
1845 | 0 | m_compModel [ compId ].presentFlag = false; |
1846 | 0 | m_cutoffPairs[ compId ] = 0; |
1847 | 0 | } |
1848 | 0 | } |
1849 | | |
1850 | | // Fits a polynomial of the given order to the strength over intensity points, averaged per intensity interval and |
1851 | | // accumulated with the points of the previous pictures. scalingVec receives the function sampled from xmin to xmax, |
1852 | | // followed by xmax and xmin. |
1853 | | bool FGAnalyzer::fitFunction( std::vector<int>& dataX, std::vector<int>& dataY, std::vector<double>& coeffs, std::vector<double>& scalingVec, |
1854 | | int order, int bitDepth, bool secondPass, ComponentID compId ) |
1855 | 0 | { |
1856 | 0 | const int intervalSize = INTERVAL_SIZE << ( ( bitDepth - BIT_DEPTH_8 ) >> 1 ); |
1857 | 0 | const int numIntervals = ( 1 << bitDepth ) / intervalSize; |
1858 | 0 | std::vector<double> meanIntensity( numIntervals, 0.0 ); |
1859 | 0 | std::vector<double> strengthIntensity( numIntervals, 0.0 ); |
1860 | 0 | std::vector<double> elementsPerInterval( numIntervals, 0.0 ); |
1861 | 0 | std::vector<int> tmpDataX; |
1862 | 0 | std::vector<int> tmpDataY; |
1863 | 0 | double xmin = 0.0, xmax = 0.0, ymin = 0.0, ymax = 0.0; |
1864 | 0 | double mn = 0.0, sd = 0.0; |
1865 | |
|
1866 | 0 | if( secondPass ) |
1867 | 0 | { |
1868 | 0 | xmin = scalingVec.back(); |
1869 | 0 | scalingVec.pop_back(); |
1870 | 0 | xmax = scalingVec.back(); |
1871 | 0 | scalingVec.pop_back(); |
1872 | 0 | const int n = (int) dataY.size(); |
1873 | 0 | if( n != 0 ) |
1874 | 0 | { |
1875 | 0 | mn = std::accumulate( dataY.begin(), dataY.end(), 0.0 ) / n; |
1876 | 0 | for( int i = 0; i < n; i++ ) |
1877 | 0 | { |
1878 | 0 | sd += ( dataY[ i ] - mn ) * ( dataY[ i ] - mn ); |
1879 | 0 | } |
1880 | 0 | sd /= n; |
1881 | 0 | sd = std::sqrt( sd ); |
1882 | 0 | } |
1883 | 0 | } |
1884 | |
|
1885 | 0 | for( size_t i = 0; i < dataX.size(); i++ ) |
1886 | 0 | { |
1887 | 0 | if( secondPass ) |
1888 | 0 | { |
1889 | 0 | if( dataX[ i ] >= xmin && dataX[ i ] <= xmax ) |
1890 | 0 | { |
1891 | 0 | const double fitted = scalingVec[ dataX[ i ] - (int) xmin ]; |
1892 | 0 | if( dataY[ i ] < fitted + sd * VAR_SCALE_UP && dataY[ i ] > fitted - sd * VAR_SCALE_DOWN ) |
1893 | 0 | { |
1894 | 0 | const int idx = dataX[ i ] / intervalSize; |
1895 | 0 | meanIntensity[ idx ] += dataX[ i ]; |
1896 | 0 | strengthIntensity[ idx ] += dataY[ i ]; |
1897 | 0 | elementsPerInterval[ idx ]++; |
1898 | 0 | } |
1899 | 0 | } |
1900 | 0 | } |
1901 | 0 | else |
1902 | 0 | { |
1903 | 0 | const int idx = dataX[ i ] / intervalSize; |
1904 | 0 | meanIntensity[ idx ] += dataX[ i ]; |
1905 | 0 | strengthIntensity[ idx ] += dataY[ i ]; |
1906 | 0 | elementsPerInterval[ idx ]++; |
1907 | 0 | } |
1908 | 0 | } |
1909 | | |
1910 | | // the data of the previous pictures, with decreasing weight |
1911 | 0 | if( !m_storedMeanIntensity[ compId ].empty() && !m_storedStrengthIntensity[ compId ].empty() ) |
1912 | 0 | { |
1913 | 0 | for( int i = 0; i < numIntervals; i++ ) |
1914 | 0 | { |
1915 | 0 | elementsPerInterval[ i ] += ACCUMULATION_DECAY * m_storedElementsPerInterval[ compId ][ i ]; |
1916 | 0 | meanIntensity[ i ] += ACCUMULATION_DECAY * m_storedMeanIntensity[ compId ][ i ]; |
1917 | 0 | strengthIntensity[ i ] += ACCUMULATION_DECAY * m_storedStrengthIntensity[ compId ][ i ]; |
1918 | 0 | } |
1919 | 0 | } |
1920 | |
|
1921 | 0 | for( int i = 0; i < numIntervals; i++ ) |
1922 | 0 | { |
1923 | 0 | if( elementsPerInterval[ i ] >= MIN_ELEMENTS_PER_INTERVAL ) |
1924 | 0 | { |
1925 | 0 | tmpDataX.push_back( (int) ( meanIntensity[ i ] / elementsPerInterval[ i ] ) ); |
1926 | 0 | tmpDataY.push_back( (int) ( strengthIntensity[ i ] / elementsPerInterval[ i ] + 0.5 ) ); // VTM truncates |
1927 | 0 | } |
1928 | 0 | } |
1929 | |
|
1930 | 0 | if( secondPass ) |
1931 | 0 | { |
1932 | | // keep the data to improve the estimate of the next pictures |
1933 | 0 | m_storedMeanIntensity[ compId ] = meanIntensity; |
1934 | 0 | m_storedStrengthIntensity[ compId ] = strengthIntensity; |
1935 | 0 | m_storedElementsPerInterval[ compId ] = elementsPerInterval; |
1936 | 0 | } |
1937 | | |
1938 | | // remove single points |
1939 | 0 | for( int i = 0; i < (int) tmpDataX.size(); i++ ) |
1940 | 0 | { |
1941 | 0 | int check = 0; |
1942 | 0 | for( int j = -WINDOW; j <= WINDOW; j++ ) |
1943 | 0 | { |
1944 | 0 | const int idx = i + j; |
1945 | 0 | if( idx >= 0 && idx < (int) tmpDataX.size() && j != 0 ) |
1946 | 0 | { |
1947 | 0 | check += abs( tmpDataX[ i ] / intervalSize - tmpDataX[ idx ] / intervalSize ) <= WINDOW ? 1 : 0; |
1948 | 0 | } |
1949 | 0 | } |
1950 | 0 | if( check < NBRS ) |
1951 | 0 | { |
1952 | 0 | tmpDataX.erase( tmpDataX.begin() + i ); |
1953 | 0 | tmpDataY.erase( tmpDataY.begin() + i ); |
1954 | 0 | i--; |
1955 | 0 | } |
1956 | 0 | } |
1957 | | |
1958 | | // VTM needs order + 1 measured points here. Chroma block means usually fall into only a few intervals around the |
1959 | | // middle of the range, so the chroma fit failed for most content and VTM signalled its default chroma parameters. |
1960 | | // The points added by extendPoints() model the fall-off on both sides of the measured range, which is enough for the |
1961 | | // improved fit when at least two measured points are left. |
1962 | 0 | if( (int) tmpDataX.size() < ( m_improved ? MIN_MEASURED_POINTS : order + 1 ) ) |
1963 | 0 | { |
1964 | 0 | return false; // too few points to fit the function |
1965 | 0 | } |
1966 | 0 | extendPoints( tmpDataX, tmpDataY, bitDepth ); |
1967 | 0 | CHECK( tmpDataX.size() > MAXPAIRS, "Maximum dataset size exceeded." ); |
1968 | 0 | if( (int) tmpDataX.size() < order + 1 ) |
1969 | 0 | { |
1970 | 0 | return false; |
1971 | 0 | } |
1972 | | |
1973 | 0 | xmin = xmax = tmpDataX[ 0 ]; |
1974 | 0 | ymin = ymax = tmpDataY[ 0 ]; |
1975 | 0 | for( size_t i = 0; i < tmpDataX.size(); i++ ) |
1976 | 0 | { |
1977 | 0 | xmin = std::min<double>( xmin, tmpDataX[ i ] ); |
1978 | 0 | xmax = std::max<double>( xmax, tmpDataX[ i ] ); |
1979 | 0 | ymin = std::min<double>( ymin, tmpDataY[ i ] ); |
1980 | 0 | ymax = std::max<double>( ymax, tmpDataY[ i ] ); |
1981 | 0 | } |
1982 | 0 | double xlow = xmax; |
1983 | 0 | double ylow = ymax; |
1984 | |
|
1985 | 0 | const int dataPairs = (int) tmpDataX.size(); |
1986 | 0 | std::vector<double> dataXd( dataPairs + 1 ), dataYd( dataPairs + 1 ); |
1987 | 0 | for( int i = 0; i < dataPairs; i++ ) |
1988 | 0 | { |
1989 | 0 | dataXd[ i + 1 ] = (double) tmpDataX[ i ]; |
1990 | 0 | dataYd[ i + 1 ] = (double) tmpDataY[ i ]; |
1991 | 0 | } |
1992 | 0 | if( secondPass ) |
1993 | 0 | { |
1994 | 0 | std::vector<int>().swap( dataX ); |
1995 | 0 | std::vector<int>().swap( dataY ); |
1996 | 0 | std::vector<double>().swap( coeffs ); |
1997 | 0 | std::vector<double>().swap( scalingVec ); |
1998 | 0 | } |
1999 | |
|
2000 | 0 | for( int i = 1; i <= dataPairs; i++ ) |
2001 | 0 | { |
2002 | 0 | if( dataXd[ i ] < xlow && dataXd[ i ] != 0 ) |
2003 | 0 | { |
2004 | 0 | xlow = dataXd[ i ]; |
2005 | 0 | } |
2006 | 0 | if( dataYd[ i ] < ylow && dataYd[ i ] != 0 ) |
2007 | 0 | { |
2008 | 0 | ylow = dataYd[ i ]; |
2009 | 0 | } |
2010 | 0 | } |
2011 | 0 | const double xscale = ( xlow < .001 && xmax < 1000 ) ? 1 / xlow : ( xmax > 1000 && xlow > .001 ) ? 1 / xmax : 1; |
2012 | 0 | const double yscale = ( ylow < .001 && ymax < 1000 ) ? 1 / ylow : ( ymax > 1000 && ylow > .001 ) ? 1 / ymax : 1; |
2013 | | |
2014 | | // least squares normal equations, solved by Gaussian elimination with partial pivoting (indices from 1) |
2015 | 0 | double a[ MAXORDER + 1 ][ MAXORDER + 1 ] = { { 0 } }; |
2016 | 0 | double B[ MAXORDER + 1 ] = { 0 }, S[ MAXORDER + 1 ] = { 0 }; |
2017 | 0 | double polycoefs[ MAXORDER + 1 ] = { 0 }; |
2018 | 0 | double Y1 = 0; |
2019 | 0 | const double maxVal = std::numeric_limits<double>::max(); |
2020 | 0 | for( int j = 1; j <= dataPairs; j++ ) |
2021 | 0 | { |
2022 | 0 | for( int i = 1; i <= order; i++ ) |
2023 | 0 | { |
2024 | 0 | B[ i ] = B[ i ] + dataYd[ j ] * yscale * ldpow( dataXd[ j ] * xscale, i ); |
2025 | 0 | if( B[ i ] == maxVal ) |
2026 | 0 | { |
2027 | 0 | return false; |
2028 | 0 | } |
2029 | 0 | for( int k = 1; k <= order; k++ ) |
2030 | 0 | { |
2031 | 0 | a[ i ][ k ] = a[ i ][ k ] + ldpow( dataXd[ j ] * xscale, i + k ); |
2032 | 0 | if( a[ i ][ k ] == maxVal ) |
2033 | 0 | { |
2034 | 0 | return false; |
2035 | 0 | } |
2036 | 0 | } |
2037 | 0 | S[ i ] = S[ i ] + ldpow( dataXd[ j ] * xscale, i ); |
2038 | 0 | if( S[ i ] == maxVal ) |
2039 | 0 | { |
2040 | 0 | return false; |
2041 | 0 | } |
2042 | 0 | } |
2043 | 0 | Y1 = Y1 + dataYd[ j ] * yscale; |
2044 | 0 | if( Y1 == maxVal ) |
2045 | 0 | { |
2046 | 0 | return false; |
2047 | 0 | } |
2048 | 0 | } |
2049 | | |
2050 | 0 | for( int i = 1; i <= order; i++ ) |
2051 | 0 | { |
2052 | 0 | for( int j = 1; j <= order; j++ ) |
2053 | 0 | { |
2054 | 0 | a[ i ][ j ] = a[ i ][ j ] - S[ i ] * S[ j ] / (double) dataPairs; |
2055 | 0 | if( a[ i ][ j ] == maxVal ) |
2056 | 0 | { |
2057 | 0 | return false; |
2058 | 0 | } |
2059 | 0 | } |
2060 | 0 | B[ i ] = B[ i ] - Y1 * S[ i ] / (double) dataPairs; |
2061 | 0 | if( B[ i ] == maxVal ) |
2062 | 0 | { |
2063 | 0 | return false; |
2064 | 0 | } |
2065 | 0 | } |
2066 | | |
2067 | 0 | for( int k = 1; k <= order; k++ ) |
2068 | 0 | { |
2069 | 0 | int R = k; |
2070 | 0 | double A1 = 0; |
2071 | 0 | for( int L = k; L <= order; L++ ) |
2072 | 0 | { |
2073 | 0 | const double A2 = std::fabs( a[ L ][ k ] ); |
2074 | 0 | if( A2 > A1 ) |
2075 | 0 | { |
2076 | 0 | A1 = A2; |
2077 | 0 | R = L; |
2078 | 0 | } |
2079 | 0 | } |
2080 | 0 | if( A1 == 0 ) |
2081 | 0 | { |
2082 | 0 | return false; |
2083 | 0 | } |
2084 | 0 | if( R != k ) |
2085 | 0 | { |
2086 | 0 | for( int j = k; j <= order; j++ ) |
2087 | 0 | { |
2088 | 0 | std::swap( a[ R ][ j ], a[ k ][ j ] ); |
2089 | 0 | } |
2090 | 0 | std::swap( B[ R ], B[ k ] ); |
2091 | 0 | } |
2092 | 0 | for( int i = k; i <= order; i++ ) |
2093 | 0 | { |
2094 | 0 | const double m = a[ i ][ k ]; |
2095 | 0 | for( int j = k; j <= order; j++ ) |
2096 | 0 | { |
2097 | 0 | a[ i ][ j ] = i == k ? a[ i ][ j ] / m : a[ i ][ j ] - m * a[ k ][ j ]; |
2098 | 0 | } |
2099 | 0 | B[ i ] = i == k ? B[ i ] / m : B[ i ] - m * B[ k ]; |
2100 | 0 | } |
2101 | 0 | } |
2102 | | |
2103 | 0 | polycoefs[ order ] = B[ order ]; |
2104 | 0 | for( int k = 1; k <= order - 1; k++ ) |
2105 | 0 | { |
2106 | 0 | const int i = order - k; |
2107 | 0 | double S1 = 0; |
2108 | 0 | for( int j = 1; j <= order; j++ ) |
2109 | 0 | { |
2110 | 0 | S1 = S1 + a[ i ][ j ] * polycoefs[ j ]; |
2111 | 0 | if( S1 == maxVal ) |
2112 | 0 | { |
2113 | 0 | return false; |
2114 | 0 | } |
2115 | 0 | } |
2116 | 0 | polycoefs[ i ] = B[ i ] - S1; |
2117 | 0 | } |
2118 | | |
2119 | 0 | double S1 = 0; |
2120 | 0 | for( int i = 1; i <= order; i++ ) |
2121 | 0 | { |
2122 | 0 | S1 = S1 + polycoefs[ i ] * S[ i ] / (double) dataPairs; |
2123 | 0 | if( S1 == maxVal ) |
2124 | 0 | { |
2125 | 0 | return false; |
2126 | 0 | } |
2127 | 0 | } |
2128 | 0 | polycoefs[ 0 ] = Y1 / (double) dataPairs - S1; |
2129 | | |
2130 | | // zero all coefficients smaller than +-1e-11 (avoids -0) |
2131 | 0 | for( int i = 0; i <= order; i++ ) |
2132 | 0 | { |
2133 | 0 | if( std::fabs( polycoefs[ i ] * 100000000000 ) < 1 ) |
2134 | 0 | { |
2135 | 0 | polycoefs[ i ] = 0; |
2136 | 0 | } |
2137 | 0 | } |
2138 | |
|
2139 | 0 | for( int i = 0; i <= order; i++ ) |
2140 | 0 | { |
2141 | 0 | polycoefs[ i ] = ( 1 / yscale ) * polycoefs[ i ] * ldpow( xscale, i ); |
2142 | 0 | coeffs.push_back( polycoefs[ i ] ); |
2143 | 0 | } |
2144 | | |
2145 | | // sample the scaling function from xmin to xmax |
2146 | 0 | for( int i = (int) xmin; i <= (int) xmax; i++ ) |
2147 | 0 | { |
2148 | 0 | double val = coeffs[ 0 ]; |
2149 | 0 | for( size_t j = 1; j < coeffs.size(); j++ ) |
2150 | 0 | { |
2151 | 0 | val += coeffs[ j ] * ldpow( i, (unsigned) j ); |
2152 | 0 | } |
2153 | 0 | scalingVec.push_back( Clip3( 0.0, (double) ( 1 << bitDepth ) - 1, val ) ); |
2154 | 0 | } |
2155 | 0 | scalingVec.push_back( xmax ); |
2156 | 0 | scalingVec.push_back( xmin ); |
2157 | 0 | return true; |
2158 | 0 | } |
2159 | | |
2160 | | // Adds up to four points beyond the lowest and the highest intensity, each a step further and weaker (the improved |
2161 | | // analysis keeps the level on the dark side only, see holdDarkStrength), then drops the points outside the usable |
2162 | | // intensity range. |
2163 | | void FGAnalyzer::extendPoints( std::vector<int>& dataX, std::vector<int>& dataY, int bitDepth ) const |
2164 | 0 | { |
2165 | 0 | const int minInt = bitDepth < 10 ? MIN_INTENSITY >> ( 10 - bitDepth ) : MIN_INTENSITY << ( bitDepth - 10 ); |
2166 | 0 | const int maxInt = bitDepth < 10 ? MAX_INTENSITY >> ( 10 - bitDepth ) : MAX_INTENSITY << ( bitDepth - 10 ); |
2167 | |
|
2168 | 0 | int xmin = dataX[ 0 ], xmax = dataX[ 0 ]; |
2169 | 0 | int ymin = dataY[ 0 ], ymax = dataY[ 0 ]; // strengths at xmin and xmax |
2170 | 0 | for( size_t i = 0; i < dataX.size(); i++ ) |
2171 | 0 | { |
2172 | 0 | if( dataX[ i ] < xmin ) |
2173 | 0 | { |
2174 | 0 | xmin = dataX[ i ]; |
2175 | 0 | ymin = dataY[ i ]; |
2176 | 0 | } |
2177 | 0 | if( dataX[ i ] > xmax ) |
2178 | 0 | { |
2179 | 0 | xmax = dataX[ i ]; |
2180 | 0 | ymax = dataY[ i ]; |
2181 | 0 | } |
2182 | 0 | } |
2183 | |
|
2184 | 0 | int numLeft = MAX_POINTS_TO_EXTEND, numRight = MAX_POINTS_TO_EXTEND; |
2185 | 0 | while( xmin >= POINT_STEP && ymin > m_strengthScale && numLeft > 0 ) |
2186 | 0 | { |
2187 | 0 | xmin -= POINT_STEP; |
2188 | 0 | ymin = m_improved ? ymin : (int) ( ymin / POINT_SCALE ); |
2189 | 0 | dataX.push_back( xmin ); |
2190 | 0 | dataY.push_back( ymin ); |
2191 | 0 | numLeft--; |
2192 | 0 | } |
2193 | 0 | while( xmax + POINT_STEP <= ( 1 << bitDepth ) - 1 && ymax > m_strengthScale && numRight > 0 ) |
2194 | 0 | { |
2195 | 0 | xmax += POINT_STEP; |
2196 | 0 | ymax = (int) ( ymax / POINT_SCALE ); // both analyses: the grain fades out above the brightest measured blocks |
2197 | 0 | dataX.push_back( xmax ); |
2198 | 0 | dataY.push_back( ymax ); |
2199 | 0 | numRight--; |
2200 | 0 | } |
2201 | 0 | for( int i = 0; i < (int) dataX.size(); i++ ) |
2202 | 0 | { |
2203 | 0 | if( dataX[ i ] < minInt || dataX[ i ] > maxInt ) |
2204 | 0 | { |
2205 | 0 | dataX.erase( dataX.begin() + i ); |
2206 | 0 | dataY.erase( dataY.begin() + i ); |
2207 | 0 | i--; |
2208 | 0 | } |
2209 | 0 | } |
2210 | 0 | } |
2211 | | |
2212 | | // Lloyd-Max quantization of the sampled scaling function into numQuantizedLevels levels; quantizedVec receives the |
2213 | | // quantized function for every intensity. |
2214 | | bool FGAnalyzer::lloydMax( std::vector<double>& scalingVec, std::vector<int>& quantizedVec, int numQuantizedLevels, int bitDepth ) const |
2215 | 0 | { |
2216 | 0 | if( scalingVec.size() <= 2 ) |
2217 | 0 | { |
2218 | 0 | return false; // no sampled function (only xmax and xmin) |
2219 | 0 | } |
2220 | | |
2221 | 0 | const int xmin = (int) scalingVec.back(); |
2222 | 0 | scalingVec.pop_back(); |
2223 | 0 | scalingVec.pop_back(); // xmax |
2224 | |
|
2225 | 0 | const double tolerance = 0.0000001; |
2226 | 0 | double ymin = scalingVec[ 0 ], ymax = scalingVec[ 0 ]; |
2227 | 0 | for( double v : scalingVec ) |
2228 | 0 | { |
2229 | 0 | ymin = std::min( ymin, v ); |
2230 | 0 | ymax = std::max( ymax, v ); |
2231 | 0 | } |
2232 | 0 | const double initTraining = ( ymax - ymin ) / numQuantizedLevels; |
2233 | 0 | if( initTraining <= 0 ) |
2234 | 0 | { |
2235 | | // A constant scaling function needs no quantization. VTM returns failure here, so grain of the same strength at |
2236 | | // all measured intensities was never signalled. |
2237 | 0 | quantizedVec.assign( (size_t) 1 << bitDepth, 0 ); |
2238 | 0 | for( size_t i = 0; i < scalingVec.size(); i++ ) |
2239 | 0 | { |
2240 | 0 | quantizedVec[ i + xmin ] = Clip3( 0, ( MAX_STANDARD_DEVIATION * m_strengthScale ) << ( bitDepth - BIT_DEPTH_8 ), (int) ( ymin + .5 ) ); |
2241 | 0 | } |
2242 | 0 | return true; |
2243 | 0 | } |
2244 | | |
2245 | 0 | std::vector<double> codebook( numQuantizedLevels ); |
2246 | 0 | std::vector<double> partition( numQuantizedLevels - 1 ); |
2247 | 0 | const double step = initTraining / 2; |
2248 | 0 | for( int i = 0; i < numQuantizedLevels; i++ ) |
2249 | 0 | { |
2250 | 0 | codebook[ i ] = ymin + i * initTraining + step; |
2251 | 0 | } |
2252 | 0 | for( int i = 0; i < numQuantizedLevels - 1; i++ ) |
2253 | 0 | { |
2254 | 0 | partition[ i ] = ( codebook[ i ] + codebook[ i + 1 ] ) / 2; |
2255 | 0 | } |
2256 | | |
2257 | | // Quantizes the scaling function with the current partition and codebook and returns the mean squared error. |
2258 | 0 | std::vector<double> quantized( scalingVec.size(), 0.0 ); |
2259 | 0 | auto quantize = [ & ]() |
2260 | 0 | { |
2261 | 0 | for( size_t i = 0; i < scalingVec.size(); i++ ) |
2262 | 0 | { |
2263 | 0 | double level = 0.0; |
2264 | 0 | for( size_t j = 0; j < partition.size(); j++ ) |
2265 | 0 | { |
2266 | 0 | level = level + ( scalingVec[ i ] > partition[ j ] ); |
2267 | 0 | } |
2268 | 0 | quantized[ i ] = codebook[ (int) level ]; |
2269 | 0 | } |
2270 | 0 | double distortion = 0.0; |
2271 | 0 | for( size_t i = 0; i < scalingVec.size(); i++ ) |
2272 | 0 | { |
2273 | 0 | distortion += ( scalingVec[ i ] - quantized[ i ] ) * ( scalingVec[ i ] - quantized[ i ] ); |
2274 | 0 | } |
2275 | 0 | return distortion / scalingVec.size(); |
2276 | 0 | }; |
2277 | |
|
2278 | 0 | double distortion = quantize(); |
2279 | 0 | double lastDistortion = 0.0; |
2280 | 0 | const double tolerance2 = std::numeric_limits<double>::epsilon() * ymax; |
2281 | 0 | double relDistortion = distortion > tolerance2 ? std::fabs( distortion - lastDistortion ) / distortion : distortion; |
2282 | |
|
2283 | 0 | while( relDistortion > tolerance && relDistortion > tolerance2 ) |
2284 | 0 | { |
2285 | 0 | for( int i = 0; i < numQuantizedLevels; i++ ) |
2286 | 0 | { |
2287 | 0 | int count = 0; |
2288 | 0 | double sum = 0.0; |
2289 | 0 | for( size_t j = 0; j < quantized.size(); j++ ) |
2290 | 0 | { |
2291 | 0 | if( codebook[ i ] == quantized[ j ] ) |
2292 | 0 | { |
2293 | 0 | count++; |
2294 | 0 | sum += scalingVec[ j ]; |
2295 | 0 | } |
2296 | 0 | } |
2297 | 0 | if( count ) |
2298 | 0 | { |
2299 | 0 | codebook[ i ] = sum / (double) count; |
2300 | 0 | continue; |
2301 | 0 | } |
2302 | | // empty cell: use the mean of the samples in its partition range, or the middle of the range |
2303 | 0 | sum = 0.0; |
2304 | 0 | count = 0; |
2305 | 0 | const bool first = i == 0, last = i == numQuantizedLevels - 1; |
2306 | 0 | for( size_t j = 0; j < quantized.size(); j++ ) |
2307 | 0 | { |
2308 | 0 | const bool inCell = first ? scalingVec[ j ] <= partition[ i ] |
2309 | 0 | : last ? scalingVec[ j ] >= partition[ i - 1 ] |
2310 | 0 | : scalingVec[ j ] >= partition[ i - 1 ] && scalingVec[ j ] <= partition[ i ]; |
2311 | 0 | if( inCell ) |
2312 | 0 | { |
2313 | 0 | count++; |
2314 | 0 | sum += scalingVec[ j ]; |
2315 | 0 | } |
2316 | 0 | } |
2317 | 0 | if( count ) |
2318 | 0 | { |
2319 | 0 | codebook[ i ] = sum / (double) count; |
2320 | 0 | } |
2321 | 0 | else |
2322 | 0 | { |
2323 | 0 | codebook[ i ] = first ? ( partition[ i ] + ymin ) / 2 : last ? ( partition[ i - 1 ] + ymax ) / 2 : ( partition[ i - 1 ] + partition[ i ] ) / 2; |
2324 | 0 | } |
2325 | 0 | } |
2326 | |
|
2327 | 0 | for( int i = 0; i < numQuantizedLevels - 1; i++ ) |
2328 | 0 | { |
2329 | 0 | partition[ i ] = ( codebook[ i ] + codebook[ i + 1 ] ) / 2; |
2330 | 0 | } |
2331 | 0 | std::sort( partition.begin(), partition.end() ); |
2332 | |
|
2333 | 0 | lastDistortion = distortion; |
2334 | 0 | distortion = quantize(); |
2335 | 0 | relDistortion = distortion > tolerance2 ? std::fabs( distortion - lastDistortion ) / distortion : distortion; |
2336 | 0 | } |
2337 | |
|
2338 | 0 | quantizedVec.assign( (size_t) 1 << bitDepth, 0 ); |
2339 | 0 | for( size_t i = 0; i < quantized.size(); i++ ) |
2340 | 0 | { |
2341 | 0 | quantizedVec[ i + xmin ] = Clip3( 0, ( MAX_STANDARD_DEVIATION * m_strengthScale ) << ( bitDepth - BIT_DEPTH_8 ), (int) ( quantized[ i ] + .5 ) ); |
2342 | 0 | } |
2343 | 0 | return true; |
2344 | 0 | } |
2345 | | |
2346 | | // Turns the quantized scaling function into intensity intervals and scaling factors of the SEI message (8-bit |
2347 | | // intensities). The cut-off frequencies are set afterwards. |
2348 | | void FGAnalyzer::setEstimatedParameters( std::vector<int>& quantizedVec, int bitDepth, ComponentID compId ) |
2349 | 0 | { |
2350 | | // strengths below half of VTM's unit count as no grain, as they did in VTM |
2351 | 0 | for( int& q : quantizedVec ) |
2352 | 0 | { |
2353 | 0 | q = q < m_strengthScale / 2 ? 0 : q; |
2354 | 0 | } |
2355 | 0 | if( m_improved ) |
2356 | 0 | { |
2357 | 0 | holdDarkStrength( quantizedVec, bitDepth ); |
2358 | 0 | if( isLuma( compId ) ) |
2359 | 0 | { |
2360 | | // Digital black (letterbox bars, clipped shadows) carries no grain in the source, but the held or extended |
2361 | | // strength reached it: on Beekeeper's bars the synthesis drew grain of std 2.6 (10 bit) where the source has none. |
2362 | | // The analyzer does not know the signal range; limited-range black is 16 << ( bitDepth - 8 ), and for full-range |
2363 | | // content this only drops the 8-bit intensities 10 to 16 (the analysis starts at MIN_INTENSITY). |
2364 | 0 | const int black = std::min<int>( 16 << ( bitDepth - 8 ), (int) quantizedVec.size() - 1 ); |
2365 | 0 | std::fill( quantizedVec.begin(), quantizedVec.begin() + black + 1, 0 ); |
2366 | 0 | } |
2367 | 0 | } |
2368 | |
|
2369 | 0 | std::vector<std::vector<int>> parameters( 3 ); // lower bounds, upper bounds, scaling factors |
2370 | | |
2371 | | // intervals of constant value |
2372 | 0 | parameters[ 0 ].push_back( 0 ); |
2373 | 0 | parameters[ 2 ].push_back( quantizedVec[ 0 ] ); |
2374 | 0 | for( size_t i = 0; i + 1 < quantizedVec.size(); i++ ) |
2375 | 0 | { |
2376 | 0 | if( quantizedVec[ i ] != quantizedVec[ i + 1 ] ) |
2377 | 0 | { |
2378 | 0 | parameters[ 0 ].push_back( (int) i + 1 ); |
2379 | 0 | parameters[ 1 ].push_back( (int) i ); |
2380 | 0 | parameters[ 2 ].push_back( quantizedVec[ i + 1 ] ); |
2381 | 0 | } |
2382 | 0 | } |
2383 | 0 | parameters[ 1 ].push_back( ( 1 << bitDepth ) - 1 ); |
2384 | |
|
2385 | 0 | mergeIntervals( parameters, bitDepth ); |
2386 | 0 | if( isLuma( compId ) ) |
2387 | 0 | { |
2388 | 0 | cutPlateauHoles( parameters, bitDepth ); // after the merging, which could fill a hole again |
2389 | 0 | } |
2390 | 0 | scaleDown( parameters, bitDepth ); |
2391 | | |
2392 | | // the scaling to 8 bits can make intervals overlap: make the bounds strictly increasing |
2393 | 0 | std::vector<int> bounds; |
2394 | 0 | for( size_t i = 0; i < parameters[ 2 ].size(); i++ ) |
2395 | 0 | { |
2396 | 0 | bounds.push_back( parameters[ 0 ][ i ] ); |
2397 | 0 | bounds.push_back( parameters[ 1 ][ i ] ); |
2398 | 0 | } |
2399 | 0 | for( size_t i = 0; i + 1 < bounds.size(); i++ ) |
2400 | 0 | { |
2401 | 0 | if( bounds[ i ] >= bounds[ i + 1 ] ) |
2402 | 0 | { |
2403 | 0 | bounds[ i + 1 ] = bounds[ i ] + 1; |
2404 | 0 | } |
2405 | 0 | } |
2406 | 0 | for( size_t i = 0; i < parameters[ 2 ].size(); i++ ) |
2407 | 0 | { |
2408 | 0 | parameters[ 0 ][ i ] = bounds[ 2 * i ]; |
2409 | 0 | parameters[ 1 ][ i ] = bounds[ 2 * i + 1 ]; |
2410 | 0 | } |
2411 | | |
2412 | | // Intervals with scaling factor 0 are not signalled. The component is signalled again as soon as a later picture |
2413 | | // gives a scaling factor above 0 (in VTM a component stays off for the rest of the sequence once all its scaling |
2414 | | // factors were 0, and then the chroma components are no longer analysed either). |
2415 | 0 | SeiFgc::CompModel& cm = m_compModel[ compId ]; |
2416 | 0 | cm.numIntensityIntervals = (uint8_t) ( parameters[ 2 ].size() - std::count( parameters[ 2 ].begin(), parameters[ 2 ].end(), 0 ) ); |
2417 | 0 | cm.presentFlag = cm.numIntensityIntervals > 0; |
2418 | 0 | if( !cm.presentFlag ) |
2419 | 0 | { |
2420 | 0 | m_cutoffPairs[ compId ] = 0; |
2421 | 0 | return; |
2422 | 0 | } |
2423 | 0 | int j = 0; |
2424 | 0 | for( size_t i = 0; i < parameters[ 2 ].size(); i++ ) |
2425 | 0 | { |
2426 | 0 | if( parameters[ 2 ][ i ] != 0 ) |
2427 | 0 | { |
2428 | 0 | auto& iv = cm.intensityValues[ j++ ]; |
2429 | 0 | iv.intensityIntervalLowerBound = (uint8_t) parameters[ 0 ][ i ]; |
2430 | 0 | iv.intensityIntervalUpperBound = (uint8_t) parameters[ 1 ][ i ]; |
2431 | 0 | iv.compModelValue[ 0 ] = parameters[ 2 ][ i ]; |
2432 | 0 | iv.compModelValue[ 1 ] = -1; // cut-off frequencies are estimated later |
2433 | 0 | iv.compModelValue[ 2 ] = -1; |
2434 | 0 | } |
2435 | 0 | } |
2436 | 0 | } |
2437 | | |
2438 | | // The scaling function only covers the intensities with flat blocks, plus a few extension points. VTM lets it fall off |
2439 | | // by a factor of 1.25 per extension point and signals no grain beyond, but on the dark side film grain goes on there: |
2440 | | // on Beekeeper the darkest intensities have the strongest grain of the scene, and they got half of it. The improved |
2441 | | // analysis keeps the level of the dark extension points (extendPoints()) and here holds the first strength down to |
2442 | | // MIN_INTENSITY (setEstimatedParameters() then clears digital black). The bright side keeps VTM's fall-off: above the |
2443 | | // brightest flat blocks the grain of a PQ or gamma-coded film fades (Beekeeper HDR at 8-bit 161-192: source fine grain |
2444 | | // 0.37 against 0.28 coded, where a held strength synthesized 1.8-2.3x what the coding removed). |
2445 | | void FGAnalyzer::holdDarkStrength( std::vector<int>& quantizedVec, int bitDepth ) const |
2446 | 0 | { |
2447 | 0 | const int minInt = bitDepth < 10 ? MIN_INTENSITY >> ( 10 - bitDepth ) : MIN_INTENSITY << ( bitDepth - 10 ); |
2448 | 0 | const auto firstGrain = std::find_if( quantizedVec.begin(), quantizedVec.end(), []( int q ) { return q > 0; } ); |
2449 | 0 | if( firstGrain == quantizedVec.end() ) |
2450 | 0 | { |
2451 | 0 | return; // no grain |
2452 | 0 | } |
2453 | 0 | const int first = (int) ( firstGrain - quantizedVec.begin() ); |
2454 | 0 | for( int i = minInt; i < first; i++ ) |
2455 | 0 | { |
2456 | 0 | quantizedVec[ i ] = quantizedVec[ first ]; |
2457 | 0 | } |
2458 | 0 | } |
2459 | | |
2460 | | // Merges intervals narrower than 2 (at 8 bits) into the neighbour with the closer scaling factor. |
2461 | | void FGAnalyzer::mergeIntervals( std::vector<std::vector<int>>& parameters, int bitDepth ) const |
2462 | 0 | { |
2463 | 0 | for( int i = 0; i < (int) parameters[ 2 ].size(); i++ ) |
2464 | 0 | { |
2465 | 0 | const int width = parameters[ 1 ][ i ] - parameters[ 0 ][ i ]; |
2466 | 0 | if( width >= ( 2 << ( bitDepth - BIT_DEPTH_8 ) ) ) |
2467 | 0 | { |
2468 | 0 | continue; |
2469 | 0 | } |
2470 | 0 | const int last = (int) parameters[ 2 ].size() - 1; |
2471 | 0 | const int diffRight = ( i == last || parameters[ 2 ][ i + 1 ] == 0 ) ? std::numeric_limits<int>::max() : abs( parameters[ 2 ][ i ] - parameters[ 2 ][ i + 1 ] ); |
2472 | 0 | const int diffLeft = ( i == 0 || parameters[ 2 ][ i - 1 ] == 0 ) ? std::numeric_limits<int>::max() : abs( parameters[ 2 ][ i ] - parameters[ 2 ][ i - 1 ] ); |
2473 | | // VTM merges to the right when both neighbours are unusable; at the last interval there is no right neighbour. |
2474 | 0 | const bool mergeLeft = diffLeft < diffRight || ( i == last && i > 0 ); |
2475 | 0 | if( !mergeLeft && i == last ) |
2476 | 0 | { |
2477 | 0 | continue; // a single interval cannot be merged |
2478 | 0 | } |
2479 | 0 | const int n = mergeLeft ? i - 1 : i + 1; |
2480 | 0 | const int otherWidth = parameters[ 1 ][ n ] - parameters[ 0 ][ n ]; |
2481 | | // the scales weighted by the interval widths; two intervals of one intensity each (width 0) weigh the same |
2482 | 0 | const int newScale = otherWidth + width > 0 |
2483 | 0 | ? ( otherWidth * parameters[ 2 ][ n ] + width * parameters[ 2 ][ i ] ) / ( otherWidth + width ) |
2484 | 0 | : ( parameters[ 2 ][ n ] + parameters[ 2 ][ i ] ) / 2; |
2485 | 0 | if( mergeLeft ) |
2486 | 0 | { |
2487 | 0 | parameters[ 1 ][ i - 1 ] = parameters[ 1 ][ i ]; |
2488 | 0 | parameters[ 2 ][ i - 1 ] = newScale; |
2489 | 0 | for( auto& p : parameters ) |
2490 | 0 | { |
2491 | 0 | p.erase( p.begin() + i ); |
2492 | 0 | } |
2493 | 0 | } |
2494 | 0 | else |
2495 | 0 | { |
2496 | 0 | parameters[ 1 ][ i ] = parameters[ 1 ][ i + 1 ]; |
2497 | 0 | parameters[ 2 ][ i ] = newScale; |
2498 | 0 | for( auto& p : parameters ) |
2499 | 0 | { |
2500 | 0 | p.erase( p.begin() + i + 1 ); |
2501 | 0 | } |
2502 | 0 | } |
2503 | 0 | i--; |
2504 | 0 | } |
2505 | 0 | } |
2506 | | |
2507 | | // The synthesis chooses the grain by the intensity of each 8x8 block alone, so a grain-free plateau (a clipped highlight: |
2508 | | // on bk_1191 constant blocks at 10-bit 657, a fifth to two fifths of the blocks at 8-bit 163-165) gets the grain of the |
2509 | | // grainy blocks at its intensities. The 8-bit values v8 - 1 .. v8 + 1 around every plateau (findPlateaus) get no grain: |
2510 | | // intervals inside are cleared, intervals reaching in are cut back, an interval spanning it is split. Three values, so |
2511 | | // that the decoded plateau's 8x8 averages stay inside despite the coding error. The grainy blocks at those intensities |
2512 | | // lose their grain too: grain put back short beats grain drawn on a clean highlight. |
2513 | | void FGAnalyzer::cutPlateauHoles( std::vector<std::vector<int>>& parameters, int bitDepth ) const |
2514 | 0 | { |
2515 | 0 | const int shift = bitDepth - BIT_DEPTH_8; |
2516 | 0 | for( int plateau : m_plateaus ) |
2517 | 0 | { |
2518 | 0 | const int v8 = plateau >> shift; |
2519 | 0 | const int holeLow = ( v8 - 1 ) << shift, holeHigh = ( ( v8 + 2 ) << shift ) - 1; |
2520 | 0 | for( size_t i = 0; i < parameters[ 2 ].size(); i++ ) |
2521 | 0 | { |
2522 | 0 | const int lower = parameters[ 0 ][ i ], upper = parameters[ 1 ][ i ], scale = parameters[ 2 ][ i ]; |
2523 | 0 | if( scale == 0 || upper < holeLow || lower > holeHigh ) |
2524 | 0 | { |
2525 | 0 | continue; |
2526 | 0 | } |
2527 | | // The part below the hole ends at the 8-bit value v8 - 2. setEstimatedParameters makes the bounds strictly |
2528 | | // increasing after scaleDown, which raises the part's lower bound by one where the previous interval ends in the |
2529 | | // same 8-bit value (lower bound rounded up here). A part left with a single value there would become |
2530 | | // [v8 - 2, v8 - 1]: grain inside the hole. Such a part is left out. |
2531 | 0 | const int lowestBelow = ( lower + ( 1 << shift ) - 1 ) >> shift; |
2532 | 0 | const bool keepBelow = lowestBelow < v8 - 2; |
2533 | 0 | if( lower >= holeLow && upper <= holeHigh ) |
2534 | 0 | { |
2535 | 0 | parameters[ 2 ][ i ] = 0; |
2536 | 0 | } |
2537 | 0 | else if( lower < holeLow && upper > holeHigh ) |
2538 | 0 | { |
2539 | 0 | if( !keepBelow ) |
2540 | 0 | { |
2541 | 0 | parameters[ 0 ][ i ] = holeHigh + 1; |
2542 | 0 | continue; |
2543 | 0 | } |
2544 | 0 | parameters[ 1 ][ i ] = holeLow - 1; |
2545 | 0 | parameters[ 0 ].insert( parameters[ 0 ].begin() + i + 1, holeHigh + 1 ); |
2546 | 0 | parameters[ 1 ].insert( parameters[ 1 ].begin() + i + 1, upper ); |
2547 | 0 | parameters[ 2 ].insert( parameters[ 2 ].begin() + i + 1, scale ); |
2548 | 0 | i++; |
2549 | 0 | } |
2550 | 0 | else if( lower < holeLow ) |
2551 | 0 | { |
2552 | 0 | if( keepBelow ) |
2553 | 0 | { |
2554 | 0 | parameters[ 1 ][ i ] = holeLow - 1; |
2555 | 0 | } |
2556 | 0 | else |
2557 | 0 | { |
2558 | 0 | parameters[ 2 ][ i ] = 0; |
2559 | 0 | } |
2560 | 0 | } |
2561 | 0 | else |
2562 | 0 | { |
2563 | 0 | parameters[ 0 ][ i ] = holeHigh + 1; |
2564 | 0 | } |
2565 | 0 | } |
2566 | 0 | } |
2567 | 0 | } |
2568 | | |
2569 | | // Scales intensities to 8 bits and the scaling factors to the SEI representation. |
2570 | | void FGAnalyzer::scaleDown( std::vector<std::vector<int>>& parameters, int bitDepth ) const |
2571 | 0 | { |
2572 | 0 | for( size_t i = 0; i < parameters[ 2 ].size(); i++ ) |
2573 | 0 | { |
2574 | | // the intensities to 8 bits; the strengths stay as they are, getSignalledParameters() converts them |
2575 | 0 | parameters[ 0 ][ i ] >>= ( bitDepth - BIT_DEPTH_8 ); |
2576 | 0 | parameters[ 1 ][ i ] >>= ( bitDepth - BIT_DEPTH_8 ); |
2577 | 0 | } |
2578 | 0 | } |
2579 | | |
2580 | | // ==================================================================================================================== |
2581 | | // Cut-off frequencies |
2582 | | // ==================================================================================================================== |
2583 | | |
2584 | | // The cut-off pair whose synthesized grain has the spectrum closest to the measured one, for the improved analysis: |
2585 | | // the horizontal and vertical marginals of the mean squared DCT (without the DC coefficient), normalized, against those |
2586 | | // of the synthesis (GRAIN_SPECTRUM_MARGINALS), by the sum of squared differences. AN0237's estimator instead takes, |
2587 | | // per direction, the frequency where the marginal falls closest to a fixed fraction of its low-frequency level, which |
2588 | | // reads about one step too high on grain of the model itself (9/9 for grain synthesized with 8/8, 13/6 for 12/5), and |
2589 | | // the horizontal and vertical cut-offs together decide the shape of both marginals, which a per-direction rule cannot |
2590 | | // take into account. For 4:2:0 chroma the measured spectrum is that of the chroma plane, where the |
2591 | | // synthesis doubles the signalled cut-offs; the result is returned at chroma plane resolution like AN0237's, twice the |
2592 | | // signalled pair, which getSignalledParameters() halves. |
2593 | | void FGAnalyzer::fitCutoffPair( const std::vector<double>& meanSq, bool chroma420, int& horizontal, int& vertical ) const |
2594 | 0 | { |
2595 | 0 | constexpr int N = BLOCK_SIZE; |
2596 | 0 | double measured[ 2 ][ N ] = { { 0 } }; // horizontal and vertical marginal |
2597 | 0 | double total = 0.0; |
2598 | 0 | for( int x = 0; x < N; x++ ) |
2599 | 0 | { |
2600 | 0 | for( int y = 0; y < N; y++ ) |
2601 | 0 | { |
2602 | 0 | const double p = x || y ? meanSq[ x * N + y ] : 0.0; |
2603 | 0 | measured[ 0 ][ x ] += p; |
2604 | 0 | measured[ 1 ][ y ] += p; |
2605 | 0 | total += p; |
2606 | 0 | } |
2607 | 0 | } |
2608 | 0 | horizontal = vertical = -1; |
2609 | 0 | if( total <= 0.0 ) |
2610 | 0 | { |
2611 | 0 | return; |
2612 | 0 | } |
2613 | 0 | for( int k = 0; k < N; k++ ) |
2614 | 0 | { |
2615 | 0 | measured[ 0 ][ k ] /= total; |
2616 | 0 | measured[ 1 ][ k ] /= total; |
2617 | 0 | } |
2618 | |
|
2619 | 0 | const int table = chroma420 ? 1 : 0; |
2620 | 0 | double bestError = std::numeric_limits<double>::max(); |
2621 | 0 | for( int h = 0; h < NUM_CUTOFFS; h++ ) |
2622 | 0 | { |
2623 | 0 | for( int v = 0; v < NUM_CUTOFFS; v++ ) |
2624 | 0 | { |
2625 | 0 | double error = 0.0; |
2626 | 0 | for( int d = 0; d < 2; d++ ) |
2627 | 0 | { |
2628 | 0 | for( int k = 0; k < N; k++ ) |
2629 | 0 | { |
2630 | 0 | const double diff = measured[ d ][ k ] - GRAIN_SPECTRUM_MARGINALS[ table ][ h ][ v ][ d ][ k ]; |
2631 | 0 | error += diff * diff; |
2632 | 0 | } |
2633 | 0 | } |
2634 | 0 | if( error < bestError ) |
2635 | 0 | { |
2636 | 0 | bestError = error; |
2637 | 0 | horizontal = h + 2; |
2638 | 0 | vertical = v + 2; |
2639 | 0 | } |
2640 | 0 | } |
2641 | 0 | } |
2642 | 0 | if( chroma420 ) |
2643 | 0 | { |
2644 | 0 | horizontal *= 2; |
2645 | 0 | vertical *= 2; |
2646 | 0 | } |
2647 | 0 | } |
2648 | | |
2649 | | static int lostGrainGroup( int k ); // the u + v group of a coefficient, defined with the lost-grain fit |
2650 | | static double lostGrainHorizontalShare( int k ); // its share in the direction "horizontal frequency higher" |
2651 | | |
2652 | | // The power of a 16x16 grain spectrum ([ vertical * 16 + horizontal ], sum in total) per u + v group of the lost-grain |
2653 | | // fit (1-2, 3-5, 6-8, 9-12, 13-30) and direction (0: the horizontal frequency is the higher one, 1: the vertical one; |
2654 | | // the diagonal counts half in each), as shares of the total. |
2655 | | struct ArBandPower |
2656 | | { |
2657 | | double p[ FGAnalyzer::LostGrainPower::GROUPS ][ FGAnalyzer::LostGrainPower::DIRECTIONS ] = {}; |
2658 | | }; |
2659 | | |
2660 | | static ArBandPower arBandPower( const double* spectrum, double total ) |
2661 | 0 | { |
2662 | 0 | constexpr int N = 16; |
2663 | 0 | ArBandPower bands; |
2664 | 0 | for( int v = 0; v < N; v++ ) |
2665 | 0 | { |
2666 | 0 | for( int h = v ? 0 : 1; h < N; h++ ) |
2667 | 0 | { |
2668 | 0 | const int k = h * N + v; // the lost-grain fit's index: horizontal * 16 + vertical |
2669 | 0 | const double share = lostGrainHorizontalShare( k ); |
2670 | 0 | bands.p[ lostGrainGroup( k ) ][ 0 ] += share * spectrum[ v * N + h ] / total; |
2671 | 0 | bands.p[ lostGrainGroup( k ) ][ 1 ] += ( 1.0 - share ) * spectrum[ v * N + h ] / total; |
2672 | 0 | } |
2673 | 0 | } |
2674 | 0 | return bands; |
2675 | 0 | } |
2676 | | |
2677 | | // How well grain with the band powers model, at the best share of the measured grain's power (returned in powerScale, |
2678 | | // AR_MIN_POWER_SCALE to 1: never more grain power than measured), matches the measured band powers: the sum of the |
2679 | | // squared log ratios over the bands from u + v = 3, overshoot weighted (AR_OVERSHOOT_WEIGHT); the lowest band |
2680 | | // (u + v = 1, 2) counts only where the model exceeds it, as in the lost-grain fit (it holds what is left of the picture |
2681 | | // in the flat blocks as well as grain). The sum is convex in the logarithm of the share, so a ternary search finds it. |
2682 | | static double arBandCost( const ArBandPower& measured, const ArBandPower& model, double& powerScale ) |
2683 | 0 | { |
2684 | 0 | constexpr int GROUPS = FGAnalyzer::LostGrainPower::GROUPS, DIRECTIONS = FGAnalyzer::LostGrainPower::DIRECTIONS; |
2685 | 0 | double logRatio[ GROUPS * DIRECTIONS ]; // log( model / measured ) of the bands that count |
2686 | 0 | bool lowest [ GROUPS * DIRECTIONS ]; |
2687 | 0 | int bands = 0; |
2688 | 0 | for( int g = 0; g < GROUPS; g++ ) |
2689 | 0 | { |
2690 | 0 | for( int d = 0; d < DIRECTIONS; d++ ) |
2691 | 0 | { |
2692 | 0 | if( measured.p[ g ][ d ] > 0.0 && model.p[ g ][ d ] > 0.0 ) |
2693 | 0 | { |
2694 | 0 | logRatio[ bands ] = std::log( model.p[ g ][ d ] / measured.p[ g ][ d ] ); |
2695 | 0 | lowest[ bands++ ] = g == 0; |
2696 | 0 | } |
2697 | 0 | } |
2698 | 0 | } |
2699 | 0 | auto mismatch = [ & ]( double logScale ) |
2700 | 0 | { |
2701 | 0 | double sum = 0.0; |
2702 | 0 | for( int i = 0; i < bands; i++ ) |
2703 | 0 | { |
2704 | 0 | const double r = logScale + logRatio[ i ]; |
2705 | 0 | sum += r > 0.0 ? AR_OVERSHOOT_WEIGHT * r * r : lowest[ i ] ? 0.0 : r * r; |
2706 | 0 | } |
2707 | 0 | return sum; |
2708 | 0 | }; |
2709 | 0 | double low = std::log( AR_MIN_POWER_SCALE ), high = 0.0; |
2710 | 0 | for( int i = 0; i < 40; i++ ) |
2711 | 0 | { |
2712 | 0 | const double a = low + ( high - low ) / 3.0, b = high - ( high - low ) / 3.0; |
2713 | 0 | if( mismatch( a ) <= mismatch( b ) ) |
2714 | 0 | { |
2715 | 0 | high = b; |
2716 | 0 | } |
2717 | 0 | else |
2718 | 0 | { |
2719 | 0 | low = a; |
2720 | 0 | } |
2721 | 0 | } |
2722 | 0 | powerScale = std::exp( ( low + high ) / 2.0 ); |
2723 | 0 | return mismatch( ( low + high ) / 2.0 ); |
2724 | 0 | } |
2725 | | |
2726 | | // Fits the AR filter of a component to the spectrum of its grain, accumulated over all intensities, by Nelder-Mead from |
2727 | | // the previous filter, or for the first fit from two starts. The filter and the share of the measured grain power it is |
2728 | | // given (ArFilter::powerScale) are those whose grain best matches the measured power per frequency band and direction |
2729 | | // (arBandCost), the yardstick of the fit to the grain the coding lost. The L1 distance between the normalized spectra, |
2730 | | // used before, is decided by the few large coefficients at the lowest frequencies and left the finest band too strong: |
2731 | | // on the measured spectrum of nocturne_grain its best filter has 1.51 times the measured power at u + v 13-30 and |
2732 | | // 0.83-0.97 times in the bands below, the band fit 0.98 and 0.92-1.03 (gangster_chase: 1.08 and 0.88-1.07 against |
2733 | | // 0.98-1.02). Where no filter of the model has the grain's shape (Top Gun's coarse grain: the L1 fit gives 0.71, 1.58, |
2734 | | // 2.63 and 1.46 times the measured power in the four bands), the band fit lowers the power instead of exceeding it |
2735 | | // (0.37, 0.82, 1.43 and 0.81 at 0.55 of the measured power). Encoded, nocturne_grain's synthesized grain went from |
2736 | | // 1.54-2.18 times the power the coding lost at u + v 13-30 to 0.83-1.19 (0.56-0.90 to 0.64-0.97 in the bands below), and |
2737 | | // the finest band of the decoded picture with grain from 1.24-1.48 of the source's to 0.91-1.09. |
2738 | | // Filters that are not stable (arFilterStable) or whose variance gain exceeds AR_MAX_GAIN are excluded. For chroma the |
2739 | | // model spectrum is the one vvdec synthesizes, the analytic spectrum times AR_SYNTHESIS_RATIO_CHROMA, renormalized (the |
2740 | | // fixed pattern of the luma synthesis follows the analytic spectrum). |
2741 | | void FGAnalyzer::fitArFilter( ComponentID compId ) |
2742 | 0 | { |
2743 | 0 | constexpr int N = BLOCK_SIZE; |
2744 | 0 | const SeiFgc::CompModel& cm = m_compModel[ compId ]; |
2745 | 0 | if( !cm.presentFlag ) |
2746 | 0 | { |
2747 | 0 | return; |
2748 | 0 | } |
2749 | 0 | double measured[ N * N ] = { 0 }; // [ vertical * N + horizontal ] |
2750 | 0 | double total = 0.0; |
2751 | 0 | for( const SquaredDctSum& s : m_squaredDctSums[ compId ] ) |
2752 | 0 | { |
2753 | 0 | for( int x = 0; x < N; x++ ) |
2754 | 0 | { |
2755 | 0 | for( int y = 0; y < N; y++ ) |
2756 | 0 | { |
2757 | 0 | measured[ y * N + x ] += x || y ? s[ x * N + y ] : 0.0; |
2758 | 0 | } |
2759 | 0 | } |
2760 | 0 | } |
2761 | 0 | for( double v : measured ) |
2762 | 0 | { |
2763 | 0 | total += v; |
2764 | 0 | } |
2765 | 0 | if( total <= 0.0 ) |
2766 | 0 | { |
2767 | 0 | return; |
2768 | 0 | } |
2769 | 0 | for( double& v : measured ) |
2770 | 0 | { |
2771 | 0 | v /= total; |
2772 | 0 | } |
2773 | |
|
2774 | 0 | const ArBandPower measuredBands = arBandPower( measured, 1.0 ); |
2775 | 0 | double powerScale = 1.0; // of the filter the fit evaluated last |
2776 | 0 | static const ArSpectrum arSpectrum; |
2777 | 0 | const float* ratio = compId == COMP_Y ? nullptr : &AR_SYNTHESIS_RATIO_CHROMA[ 0 ][ 0 ]; // [ vertical * N + horizontal ] |
2778 | 0 | double model[ N * N ]; |
2779 | 0 | std::vector<double> scratch( ArSpectrum::SCRATCH_SIZE ); |
2780 | 0 | auto error = [ & ]( const double p[ 4 ] ) |
2781 | 0 | { |
2782 | 0 | const double a1 = p[ 0 ], a3 = p[ 1 ], a5 = p[ 2 ], r = p[ 3 ]; |
2783 | 0 | if( r < 0.0 || !arFilterStable( a1, a1 * r, a3 * r, a5, a5 * r * r, AR_STABILITY_MARGIN ) ) |
2784 | 0 | { |
2785 | 0 | return std::numeric_limits<double>::max(); |
2786 | 0 | } |
2787 | 0 | double gain = 0.0; |
2788 | 0 | arSpectrum.compute( a1, a3, a5, r, model, scratch, &gain ); |
2789 | 0 | if( gain > AR_MAX_GAIN ) |
2790 | 0 | { |
2791 | 0 | return std::numeric_limits<double>::max(); |
2792 | 0 | } |
2793 | 0 | double sum = 1.0; // the analytic spectrum is normalized; the one weighted by the ratio is renormalized |
2794 | 0 | if( ratio ) |
2795 | 0 | { |
2796 | 0 | sum = 0.0; |
2797 | 0 | for( int i = 0; i < N * N; i++ ) |
2798 | 0 | { |
2799 | 0 | model[ i ] *= ratio[ i ]; |
2800 | 0 | sum += model[ i ]; |
2801 | 0 | } |
2802 | 0 | } |
2803 | 0 | return arBandCost( measuredBands, arBandPower( model, sum ), powerScale ); |
2804 | 0 | }; |
2805 | |
|
2806 | 0 | ArFilter& f = m_arFilter[ compId ]; |
2807 | | // the starts: the previous filter, or for the first fit a mild low-pass and one whose spectrum falls off toward the |
2808 | | // finest frequencies (the fit can have more than one minimum) |
2809 | 0 | const double starts[ 3 ][ 4 ] = { { f.a1, f.a3, f.a5, f.r }, { 0.3, 0.0, 0.0, 1.0 }, { 0.7, -0.1, -0.25, 0.9 } }; |
2810 | 0 | double best[ 4 ] = { 0 }, bestError = std::numeric_limits<double>::max(); |
2811 | 0 | for( int s = f.valid ? 0 : 1; s < ( f.valid ? 1 : 3 ); s++ ) |
2812 | 0 | { |
2813 | | // Nelder-Mead on the four parameters. The simplex is the start and, per parameter, the start moved by the first of |
2814 | | // these steps that gives a valid filter: a start at the edge of the valid filters (the previous picture's fit often |
2815 | | // is) may have no valid neighbour at the first step, and the search then never left it (Top Gun: the same filter in |
2816 | | // all seven analysed pictures). |
2817 | 0 | static constexpr double FIRST_STEPS[] = { 0.15, -0.15, 0.075, -0.075, 0.0375, -0.0375 }; |
2818 | 0 | double pts[ 5 ][ 4 ], vals[ 5 ]; |
2819 | 0 | std::copy( starts[ s ], starts[ s ] + 4, pts[ 0 ] ); |
2820 | 0 | vals[ 0 ] = error( pts[ 0 ] ); |
2821 | 0 | for( int j = 0; j < 4; j++ ) |
2822 | 0 | { |
2823 | 0 | for( double step : FIRST_STEPS ) |
2824 | 0 | { |
2825 | 0 | std::copy( starts[ s ], starts[ s ] + 4, pts[ j + 1 ] ); |
2826 | 0 | pts[ j + 1 ][ j ] += step; |
2827 | 0 | vals[ j + 1 ] = error( pts[ j + 1 ] ); |
2828 | 0 | if( vals[ j + 1 ] < std::numeric_limits<double>::max() ) |
2829 | 0 | { |
2830 | 0 | break; |
2831 | 0 | } |
2832 | 0 | } |
2833 | 0 | } |
2834 | 0 | for( int it = 0; it < AR_FIT_ITERATIONS; it++ ) |
2835 | 0 | { |
2836 | 0 | int order[ 5 ] = { 0, 1, 2, 3, 4 }; |
2837 | 0 | std::sort( order, order + 5, [ & ]( int a, int b ) { return vals[ a ] < vals[ b ]; } ); |
2838 | 0 | const int worst = order[ 4 ], second = order[ 3 ], bestIdx = order[ 0 ]; |
2839 | 0 | if( vals[ worst ] - vals[ bestIdx ] < AR_FIT_TOLERANCE ) |
2840 | 0 | { |
2841 | 0 | break; // converged |
2842 | 0 | } |
2843 | 0 | double c[ 4 ] = { 0 }, xr[ 4 ], xe[ 4 ], xc[ 4 ]; |
2844 | 0 | for( int i = 0; i < 5; i++ ) |
2845 | 0 | { |
2846 | 0 | for( int j = 0; j < 4 && i != worst; j++ ) |
2847 | 0 | { |
2848 | 0 | c[ j ] += pts[ i ][ j ] / 4; |
2849 | 0 | } |
2850 | 0 | } |
2851 | 0 | for( int j = 0; j < 4; j++ ) |
2852 | 0 | { |
2853 | 0 | xr[ j ] = c[ j ] + ( c[ j ] - pts[ worst ][ j ] ); |
2854 | 0 | } |
2855 | 0 | const double fr = error( xr ); |
2856 | 0 | if( fr < vals[ bestIdx ] ) |
2857 | 0 | { |
2858 | 0 | for( int j = 0; j < 4; j++ ) |
2859 | 0 | { |
2860 | 0 | xe[ j ] = c[ j ] + 2 * ( c[ j ] - pts[ worst ][ j ] ); |
2861 | 0 | } |
2862 | 0 | const double fe = error( xe ); |
2863 | 0 | std::copy( fe < fr ? xe : xr, ( fe < fr ? xe : xr ) + 4, pts[ worst ] ); |
2864 | 0 | vals[ worst ] = std::min( fe, fr ); |
2865 | 0 | } |
2866 | 0 | else if( fr < vals[ second ] ) |
2867 | 0 | { |
2868 | 0 | std::copy( xr, xr + 4, pts[ worst ] ); |
2869 | 0 | vals[ worst ] = fr; |
2870 | 0 | } |
2871 | 0 | else |
2872 | 0 | { |
2873 | 0 | for( int j = 0; j < 4; j++ ) |
2874 | 0 | { |
2875 | 0 | xc[ j ] = c[ j ] + 0.5 * ( pts[ worst ][ j ] - c[ j ] ); |
2876 | 0 | } |
2877 | 0 | const double fc = error( xc ); |
2878 | 0 | if( fc < vals[ worst ] ) |
2879 | 0 | { |
2880 | 0 | std::copy( xc, xc + 4, pts[ worst ] ); |
2881 | 0 | vals[ worst ] = fc; |
2882 | 0 | } |
2883 | 0 | else |
2884 | 0 | { |
2885 | 0 | for( int i = 0; i < 5; i++ ) |
2886 | 0 | { |
2887 | 0 | if( i == bestIdx ) |
2888 | 0 | { |
2889 | 0 | continue; |
2890 | 0 | } |
2891 | 0 | for( int j = 0; j < 4; j++ ) |
2892 | 0 | { |
2893 | 0 | pts[ i ][ j ] = pts[ bestIdx ][ j ] + 0.5 * ( pts[ i ][ j ] - pts[ bestIdx ][ j ] ); |
2894 | 0 | } |
2895 | 0 | vals[ i ] = error( pts[ i ] ); |
2896 | 0 | } |
2897 | 0 | } |
2898 | 0 | } |
2899 | 0 | } |
2900 | 0 | for( int i = 0; i < 5; i++ ) |
2901 | 0 | { |
2902 | 0 | if( vals[ i ] < bestError ) |
2903 | 0 | { |
2904 | 0 | bestError = vals[ i ]; |
2905 | 0 | std::copy( pts[ i ], pts[ i ] + 4, best ); |
2906 | 0 | } |
2907 | 0 | } |
2908 | 0 | } |
2909 | 0 | if( bestError == std::numeric_limits<double>::max() ) |
2910 | 0 | { |
2911 | 0 | return; |
2912 | 0 | } |
2913 | 0 | f.a1 = best[ 0 ]; |
2914 | 0 | f.a3 = best[ 1 ]; |
2915 | 0 | f.a5 = best[ 2 ]; |
2916 | 0 | f.r = best[ 3 ]; |
2917 | 0 | error( best ); // sets powerScale to the best filter's |
2918 | 0 | f.powerScale = powerScale; |
2919 | 0 | f.nonDcShare = arSpectrum.compute( f.a1, f.a3, f.a5, f.r, model, scratch ); |
2920 | 0 | f.valid = true; |
2921 | 0 | } |
2922 | | |
2923 | | FGAnalyzer::ArGrain FGAnalyzer::arGrain( const std::vector<int>& modelValues, int log2ScaleFactor, int bitDepth, bool luma ) |
2924 | 0 | { |
2925 | 0 | constexpr int N = BLOCK_SIZE; |
2926 | 0 | const double one = 1 << log2ScaleFactor; |
2927 | 0 | const int coef[ 6 ] = { 0, modelValues[ 1 ], 0, modelValues[ 3 ], modelValues[ 4 ], modelValues[ 5 ] }; |
2928 | |
|
2929 | 0 | static const ArSpectrum arSpectrum; |
2930 | 0 | double model[ N * N ]; |
2931 | 0 | std::vector<double> scratch( ArSpectrum::SCRATCH_SIZE ); |
2932 | 0 | const double nonDcShare = arSpectrum.compute( coef[ 1 ] / one, coef[ 3 ] / one, coef[ 5 ] / one, coef[ 4 ] / one, model, scratch ); |
2933 | 0 | double sum = 1.0; // as in fitArFilter: the chroma spectrum is the one vvdec synthesizes |
2934 | 0 | if( !luma ) |
2935 | 0 | { |
2936 | 0 | const float* ratio = &AR_SYNTHESIS_RATIO_CHROMA[ 0 ][ 0 ]; // [ vertical * N + horizontal ] |
2937 | 0 | sum = 0.0; |
2938 | 0 | for( int i = 0; i < N * N; i++ ) |
2939 | 0 | { |
2940 | 0 | model[ i ] *= ratio[ i ]; |
2941 | 0 | sum += model[ i ]; |
2942 | 0 | } |
2943 | 0 | } |
2944 | 0 | const ArBandPower bands = arBandPower( model, sum ); |
2945 | |
|
2946 | 0 | ArGrain grain; |
2947 | 0 | grain.stddevPerScale = std::ldexp( AR_PATTERN_STDDEV[ luma ? 0 : 1 ] * std::sqrt( arEnergy( coef, log2ScaleFactor ) ), -( log2ScaleFactor + 10 - bitDepth ) ); |
2948 | 0 | for( int g = 0; g < LostGrainPower::GROUPS; g++ ) |
2949 | 0 | { |
2950 | 0 | for( int d = 0; d < LostGrainPower::DIRECTIONS; d++ ) |
2951 | 0 | { |
2952 | 0 | grain.bandPower[ g ][ d ] = N * N * nonDcShare * bands.p[ g ][ d ]; |
2953 | 0 | } |
2954 | 0 | } |
2955 | 0 | return grain; |
2956 | 0 | } |
2957 | | |
2958 | | // Estimates horizontal and vertical cut-off frequencies per intensity interval from the accumulated squared DCT of the |
2959 | | // grain, then fills missing values, limits the spread and the number of different pairs. |
2960 | | void FGAnalyzer::estimateCutoffFreq( ComponentID compId, int bitDepth ) |
2961 | 0 | { |
2962 | 0 | SeiFgc::CompModel& cm = m_compModel[ compId ]; |
2963 | 0 | if( !cm.presentFlag ) |
2964 | 0 | { |
2965 | 0 | m_cutoffPairs[ compId ] = 0; |
2966 | 0 | return; |
2967 | 0 | } |
2968 | 0 | constexpr int N = BLOCK_SIZE; |
2969 | 0 | const int intervals = cm.numIntensityIntervals; |
2970 | | |
2971 | | // intensity interval of every 8-bit intensity |
2972 | 0 | int intensityInterval[ MAX_NUM_INTENSITIES ]; |
2973 | 0 | std::fill_n( intensityInterval, MAX_NUM_INTENSITIES, -1 ); |
2974 | 0 | for( int i = 0; i < intervals; i++ ) |
2975 | 0 | { |
2976 | 0 | for( int v = cm.intensityValues[ i ].intensityIntervalLowerBound; v <= cm.intensityValues[ i ].intensityIntervalUpperBound; v++ ) |
2977 | 0 | { |
2978 | 0 | intensityInterval[ v ] = i; |
2979 | 0 | } |
2980 | 0 | } |
2981 | |
|
2982 | 0 | const std::vector<SquaredDctSum>& blocks = m_squaredDctSums[ compId ]; |
2983 | 0 | const std::vector<double>& numEl = m_numDctBlocks[ compId ]; |
2984 | 0 | std::vector<double> blocksPerInterval( intervals, 0.0 ); |
2985 | 0 | for( size_t i = 0; i < blocks.size(); i++ ) |
2986 | 0 | { |
2987 | 0 | const int idx = intensityInterval[ i >> ( bitDepth - BIT_DEPTH_8 ) ]; |
2988 | 0 | if( idx != -1 ) |
2989 | 0 | { |
2990 | 0 | blocksPerInterval[ idx ] += numEl[ i ]; |
2991 | 0 | } |
2992 | 0 | } |
2993 | | |
2994 | | // mean squared DCT per interval, and its row and column averages without the DC coefficient |
2995 | 0 | std::vector<std::vector<double>> meanSq( intervals, std::vector<double>( N * N, 0.0 ) ); |
2996 | 0 | std::vector<std::vector<double>> rowMean( intervals, std::vector<double>( N, 0.0 ) ); // per horizontal frequency |
2997 | 0 | std::vector<std::vector<double>> colMean( intervals, std::vector<double>( N, 0.0 ) ); // per vertical frequency |
2998 | 0 | for( int x = 0; x < N; x++ ) |
2999 | 0 | { |
3000 | 0 | for( int y = 0; y < N; y++ ) |
3001 | 0 | { |
3002 | 0 | for( size_t i = 0; i < blocks.size(); i++ ) |
3003 | 0 | { |
3004 | 0 | const int idx = intensityInterval[ i >> ( bitDepth - BIT_DEPTH_8 ) ]; |
3005 | 0 | if( idx != -1 ) |
3006 | 0 | { |
3007 | 0 | meanSq[ idx ][ x * N + y ] += blocks[ i ][ x * N + y ]; |
3008 | 0 | } |
3009 | 0 | } |
3010 | 0 | for( int i = 0; i < intervals; i++ ) |
3011 | 0 | { |
3012 | 0 | if( blocksPerInterval[ i ] >= MIN_BLOCK_WEIGHT ) |
3013 | 0 | { |
3014 | 0 | meanSq[ i ][ x * N + y ] /= blocksPerInterval[ i ]; |
3015 | 0 | rowMean[ i ][ x ] += ( x != 0 || y != 0 ) ? meanSq[ i ][ x * N + y ] : 0.0; |
3016 | 0 | colMean[ i ][ y ] += ( x != 0 || y != 0 ) ? meanSq[ i ][ x * N + y ] : 0.0; |
3017 | 0 | } |
3018 | 0 | } |
3019 | 0 | } |
3020 | 0 | } |
3021 | |
|
3022 | 0 | int avgCutoffHorizontal = 0, avgCutoffVertical = 0; |
3023 | 0 | int numCutoffHorizontal = 0, numCutoffVertical = 0; |
3024 | 0 | cm.numModelValues = 3; // always signal all three values |
3025 | 0 | for( int i = 0; i < intervals; i++ ) |
3026 | 0 | { |
3027 | 0 | auto& iv = cm.intensityValues[ i ]; |
3028 | 0 | if( blocksPerInterval[ i ] < MIN_BLOCK_WEIGHT ) |
3029 | 0 | { |
3030 | 0 | iv.compModelValue[ 1 ] = -1; |
3031 | 0 | iv.compModelValue[ 2 ] = -1; |
3032 | 0 | continue; |
3033 | 0 | } |
3034 | 0 | for( int x = 0; x < N; x++ ) |
3035 | 0 | { |
3036 | 0 | rowMean[ i ][ x ] /= x == 0 ? N - 1 : N; |
3037 | 0 | colMean[ i ][ x ] /= x == 0 ? N - 1 : N; |
3038 | 0 | } |
3039 | | // rowMean is indexed by the horizontal frequency, colMean by the vertical one. VTM takes the vertical cut-off from |
3040 | | // rowMean and the horizontal one from colMean, so its grain comes out rotated by 90 degrees (comp_model_value[1] |
3041 | | // is the horizontal cut-off, for VTM's own synthesis as well). |
3042 | 0 | int cutoffHorizontal = -1, cutoffVertical = -1; |
3043 | 0 | if( m_improved ) |
3044 | 0 | { |
3045 | 0 | fitCutoffPair( meanSq[ i ], compId != COMP_Y && m_chromaFormat == CHROMA_420, cutoffHorizontal, cutoffVertical ); |
3046 | 0 | } |
3047 | 0 | else |
3048 | 0 | { |
3049 | 0 | cutoffHorizontal = cutoffFrequency( rowMean[ i ] ); |
3050 | 0 | cutoffVertical = cutoffFrequency( colMean[ i ] ); |
3051 | 0 | } |
3052 | 0 | const int intervalWidth = iv.intensityIntervalUpperBound - iv.intensityIntervalLowerBound; |
3053 | 0 | if( cutoffHorizontal != -1 ) |
3054 | 0 | { |
3055 | 0 | iv.compModelValue[ 1 ] = cutoffHorizontal; |
3056 | 0 | avgCutoffHorizontal += intervalWidth * cutoffHorizontal; |
3057 | 0 | numCutoffHorizontal += intervalWidth; |
3058 | 0 | } |
3059 | 0 | if( cutoffVertical != -1 ) |
3060 | 0 | { |
3061 | 0 | iv.compModelValue[ 2 ] = cutoffVertical; |
3062 | 0 | avgCutoffVertical += intervalWidth * cutoffVertical; |
3063 | 0 | numCutoffVertical += intervalWidth; |
3064 | 0 | } |
3065 | 0 | } |
3066 | |
|
3067 | 0 | avgCutoffHorizontal = numCutoffHorizontal ? avgCutoffHorizontal / numCutoffHorizontal : -1; |
3068 | 0 | if( numCutoffVertical ) |
3069 | 0 | { |
3070 | 0 | avgCutoffVertical = avgCutoffVertical / numCutoffVertical; |
3071 | 0 | } |
3072 | 0 | else |
3073 | 0 | { |
3074 | 0 | avgCutoffVertical = -1; // VTM master sets avgCutoffHorizontal here, losing the valid horizontal average |
3075 | 0 | } |
3076 | |
|
3077 | 0 | replaceCutoff( compId, avgCutoffHorizontal, avgCutoffVertical ); |
3078 | 0 | limitCutoff( compId, avgCutoffHorizontal, avgCutoffVertical ); |
3079 | 0 | limitCutoffConsecutive( compId ); |
3080 | 0 | if( !cm.presentFlag ) |
3081 | 0 | { |
3082 | 0 | m_cutoffPairs[ compId ] = 0; |
3083 | 0 | return; |
3084 | 0 | } |
3085 | | |
3086 | | // limit the number of different cut-off pairs to what the synthesis supports, shared by the components |
3087 | 0 | std::vector<CutoffPair> pairs( intervals ); |
3088 | 0 | for( int i = 0; i < intervals; i++ ) |
3089 | 0 | { |
3090 | 0 | pairs[ i ].p = { cm.intensityValues[ i ].compModelValue[ 1 ], cm.intensityValues[ i ].compModelValue[ 2 ] }; |
3091 | 0 | pairs[ i ].w = cm.intensityValues[ i ].intensityIntervalUpperBound - cm.intensityValues[ i ].intensityIntervalLowerBound; |
3092 | 0 | } |
3093 | 0 | const int numLumaPairs = MAX_CUTOFF_PAIRS - 2 + !m_doAnalysis[ COMP_Cb ] + !m_doAnalysis[ COMP_Cr ]; |
3094 | 0 | int maxUnique = numLumaPairs; |
3095 | 0 | if( compId == COMP_Cb ) |
3096 | 0 | { |
3097 | 0 | maxUnique = 1 + !m_doAnalysis[ COMP_Cr ] + ( numLumaPairs - m_cutoffPairs[ COMP_Y ] ) / ( m_doAnalysis[ COMP_Cb ] + m_doAnalysis[ COMP_Cr ] ); |
3098 | 0 | } |
3099 | 0 | else if( compId == COMP_Cr ) |
3100 | 0 | { |
3101 | 0 | maxUnique = MAX_CUTOFF_PAIRS - m_cutoffPairs[ COMP_Y ] - m_cutoffPairs[ COMP_Cb ]; |
3102 | 0 | } |
3103 | 0 | m_cutoffPairs[ compId ] = limitCutoffPairs( pairs, maxUnique ); |
3104 | 0 | for( int i = 0; i < intervals; i++ ) |
3105 | 0 | { |
3106 | 0 | cm.intensityValues[ i ].compModelValue[ 1 ] = pairs[ i ].p.first; |
3107 | 0 | cm.intensityValues[ i ].compModelValue[ 2 ] = pairs[ i ].p.second; |
3108 | 0 | } |
3109 | 0 | } |
3110 | | |
3111 | | // Cut-off frequency of a 16-sample row or column average: the smoothed average is compared with a threshold derived |
3112 | | // from its low frequencies; the frequency closest to the threshold is the cut-off. Returns -1 when no cut-off is found. |
3113 | | int FGAnalyzer::cutoffFrequency( const std::vector<double>& mean ) const |
3114 | 0 | { |
3115 | 0 | constexpr int NUM = 13; // cut-off frequencies 2 to 14 |
3116 | 0 | constexpr int a = 6; |
3117 | 0 | constexpr int w[ NUM ] = { 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; |
3118 | |
|
3119 | 0 | double sum[ NUM ]; |
3120 | 0 | for( int j = 2; j < 15; j++ ) |
3121 | 0 | { |
3122 | 0 | sum[ j - 2 ] = ( TAP_FILTER[ 0 ] * mean[ j - 1 ] + TAP_FILTER[ 1 ] * mean[ j ] + TAP_FILTER[ 2 ] * mean[ j + 1 ] ) / NORM_TAP; |
3123 | 0 | } |
3124 | 0 | double target = 0; |
3125 | 0 | for( int j = 0; j < NUM; j++ ) |
3126 | 0 | { |
3127 | 0 | target += w[ j ] * sum[ j ]; |
3128 | 0 | } |
3129 | 0 | target /= a; |
3130 | |
|
3131 | 0 | double bestDiff = std::numeric_limits<double>::max(); |
3132 | 0 | int bestIdx = -1; |
3133 | 0 | for( int j = 0; j < NUM; j++ ) |
3134 | 0 | { |
3135 | 0 | const double d = std::fabs( sum[ j ] - target ); |
3136 | 0 | if( d < bestDiff || ( d == bestDiff && j > bestIdx ) ) // the larger index when equally close |
3137 | 0 | { |
3138 | 0 | bestDiff = d; |
3139 | 0 | bestIdx = j; |
3140 | 0 | } |
3141 | 0 | } |
3142 | 0 | if( bestIdx == -1 || ( bestIdx == NUM - 1 && target < sum[ NUM - 1 ] && bestDiff > target / 2 ) ) |
3143 | 0 | { |
3144 | 0 | return -1; |
3145 | 0 | } |
3146 | 0 | return Clip3( 2, 14, bestIdx + 2 ); // RDD 5 range |
3147 | 0 | } |
3148 | | |
3149 | | // Replaces missing cut-offs (-1) with the averages; one missing average is replaced by the other. |
3150 | | void FGAnalyzer::replaceCutoff( ComponentID compId, int& replacementH, int& replacementV ) |
3151 | 0 | { |
3152 | 0 | SeiFgc::CompModel& cm = m_compModel[ compId ]; |
3153 | 0 | if( !cm.presentFlag ) |
3154 | 0 | { |
3155 | 0 | return; |
3156 | 0 | } |
3157 | 0 | if( replacementH == -1 && replacementV == -1 ) |
3158 | 0 | { |
3159 | 0 | cm.presentFlag = false; |
3160 | 0 | return; |
3161 | 0 | } |
3162 | 0 | if( replacementH == -1 ) |
3163 | 0 | { |
3164 | 0 | replacementH = replacementV; |
3165 | 0 | } |
3166 | 0 | else if( replacementV == -1 ) |
3167 | 0 | { |
3168 | 0 | replacementV = replacementH; |
3169 | 0 | } |
3170 | 0 | for( int i = 0; i < cm.numIntensityIntervals; i++ ) |
3171 | 0 | { |
3172 | 0 | auto& v = cm.intensityValues[ i ].compModelValue; |
3173 | 0 | if( v[ 1 ] == -1 ) |
3174 | 0 | { |
3175 | 0 | v[ 1 ] = replacementH; |
3176 | 0 | } |
3177 | 0 | if( v[ 2 ] == -1 ) |
3178 | 0 | { |
3179 | 0 | v[ 2 ] = replacementV; |
3180 | 0 | } |
3181 | 0 | } |
3182 | 0 | } |
3183 | | |
3184 | | // Limits every cut-off to the average +-2. |
3185 | | void FGAnalyzer::limitCutoff( ComponentID compId, int avgH, int avgV ) |
3186 | 0 | { |
3187 | 0 | SeiFgc::CompModel& cm = m_compModel[ compId ]; |
3188 | 0 | if( !cm.presentFlag ) |
3189 | 0 | { |
3190 | 0 | return; |
3191 | 0 | } |
3192 | 0 | constexpr int delta = 2; |
3193 | 0 | for( int i = 0; i < cm.numIntensityIntervals; i++ ) |
3194 | 0 | { |
3195 | 0 | auto& v = cm.intensityValues[ i ].compModelValue; |
3196 | 0 | v[ 1 ] = Clip3( avgH - delta, avgH + delta, v[ 1 ] ); |
3197 | 0 | v[ 2 ] = Clip3( avgV - delta, avgV + delta, v[ 2 ] ); |
3198 | 0 | } |
3199 | 0 | } |
3200 | | |
3201 | | // Smooths the cut-offs over consecutive intervals with a [1 2 1] filter ([3 1] at the ends), in place as in VTM. |
3202 | | // A single interval has no neighbour to smooth with: the [3 1] end filter would read the unused second interval's |
3203 | | // values (0 from init, or stale ones from an earlier picture) and lower the cut-offs, below 2 at worst. |
3204 | | void FGAnalyzer::limitCutoffConsecutive( ComponentID compId ) |
3205 | 0 | { |
3206 | 0 | SeiFgc::CompModel& cm = m_compModel[ compId ]; |
3207 | 0 | if( !cm.presentFlag || cm.numIntensityIntervals < 2 ) |
3208 | 0 | { |
3209 | 0 | return; |
3210 | 0 | } |
3211 | 0 | const int n = cm.numIntensityIntervals; |
3212 | 0 | for( int i = 0; i < n; i++ ) |
3213 | 0 | { |
3214 | 0 | for( int k = 1; k <= 2; k++ ) |
3215 | 0 | { |
3216 | 0 | int& cur = cm.intensityValues[ i ].compModelValue[ k ]; |
3217 | 0 | if( i == 0 ) |
3218 | 0 | { |
3219 | 0 | cur = ( 3 * cur + cm.intensityValues[ i + 1 ].compModelValue[ k ] + 2 ) / 4; |
3220 | 0 | } |
3221 | 0 | else if( i == n - 1 ) |
3222 | 0 | { |
3223 | 0 | cur = ( cm.intensityValues[ i - 1 ].compModelValue[ k ] + 3 * cur + 2 ) / 4; |
3224 | 0 | } |
3225 | 0 | else |
3226 | 0 | { |
3227 | 0 | cur = ( cm.intensityValues[ i - 1 ].compModelValue[ k ] + 2 * cur + cm.intensityValues[ i + 1 ].compModelValue[ k ] + 2 ) / 4; |
3228 | 0 | } |
3229 | 0 | } |
3230 | 0 | } |
3231 | 0 | } |
3232 | | |
3233 | | // Reduces the number of different cut-off pairs to maxUnique with a weighted k-medoids clustering (Manhattan distance, |
3234 | | // weights are interval widths) and maps every interval to its medoid. Returns the number of different pairs. |
3235 | | int FGAnalyzer::limitCutoffPairs( std::vector<CutoffPair>& pairs, int maxUnique ) const |
3236 | 0 | { |
3237 | 0 | const int s = (int) pairs.size(); |
3238 | 0 | if( s == 0 ) |
3239 | 0 | { |
3240 | 0 | return 0; |
3241 | 0 | } |
3242 | | |
3243 | | // distinct pairs in order of first appearance, with summed weights and the intervals using them |
3244 | 0 | std::vector<CutoffPair> nodes; |
3245 | 0 | for( int i = 0; i < s; i++ ) |
3246 | 0 | { |
3247 | 0 | auto it = std::find_if( nodes.begin(), nodes.end(), [ & ]( const CutoffPair& n ) { return n.p == pairs[ i ].p; } ); |
3248 | 0 | if( it == nodes.end() ) |
3249 | 0 | { |
3250 | 0 | nodes.push_back( CutoffPair() ); |
3251 | 0 | nodes.back().p = pairs[ i ].p; |
3252 | 0 | nodes.back().w = pairs[ i ].w; |
3253 | 0 | nodes.back().idx.push_back( i ); |
3254 | 0 | } |
3255 | 0 | else |
3256 | 0 | { |
3257 | 0 | it->w += pairs[ i ].w; |
3258 | 0 | it->idx.push_back( i ); |
3259 | 0 | } |
3260 | 0 | } |
3261 | 0 | const int numNodes = (int) nodes.size(); |
3262 | 0 | if( numNodes <= maxUnique ) |
3263 | 0 | { |
3264 | 0 | return numNodes; |
3265 | 0 | } |
3266 | | |
3267 | 0 | std::vector<std::vector<int>> dist( numNodes, std::vector<int>( numNodes, 0 ) ); |
3268 | 0 | for( int u = 0; u < numNodes; u++ ) |
3269 | 0 | { |
3270 | 0 | for( int v = u + 1; v < numNodes; v++ ) |
3271 | 0 | { |
3272 | 0 | dist[ u ][ v ] = dist[ v ][ u ] = abs( nodes[ u ].p.first - nodes[ v ].p.first ) + abs( nodes[ u ].p.second - nodes[ v ].p.second ); |
3273 | 0 | } |
3274 | 0 | } |
3275 | | |
3276 | | // start with the heaviest pair, then add heavy pairs far from the medoids chosen so far |
3277 | 0 | std::vector<int> md; |
3278 | 0 | int first = 0; |
3279 | 0 | for( int u = 1; u < numNodes; u++ ) |
3280 | 0 | { |
3281 | 0 | if( nodes[ u ].w > nodes[ first ].w ) |
3282 | 0 | { |
3283 | 0 | first = u; |
3284 | 0 | } |
3285 | 0 | } |
3286 | 0 | md.push_back( first ); |
3287 | 0 | auto isMedoid = [ & ]( int u ) { return std::find( md.begin(), md.end(), u ) != md.end(); }; |
3288 | 0 | while( (int) md.size() < maxUnique ) |
3289 | 0 | { |
3290 | 0 | long long bestScore = -1; |
3291 | 0 | int bestU = -1; |
3292 | 0 | for( int u = 0; u < numNodes; u++ ) |
3293 | 0 | { |
3294 | 0 | if( isMedoid( u ) ) |
3295 | 0 | { |
3296 | 0 | continue; |
3297 | 0 | } |
3298 | 0 | int dmin = std::numeric_limits<int>::max(); |
3299 | 0 | for( int m : md ) |
3300 | 0 | { |
3301 | 0 | dmin = std::min( dmin, dist[ u ][ m ] ); |
3302 | 0 | } |
3303 | 0 | const long long score = 1LL * nodes[ u ].w * dmin; |
3304 | 0 | if( score > bestScore ) |
3305 | 0 | { |
3306 | 0 | bestScore = score; |
3307 | 0 | bestU = u; |
3308 | 0 | } |
3309 | 0 | } |
3310 | 0 | if( bestU < 0 ) |
3311 | 0 | { |
3312 | 0 | break; |
3313 | 0 | } |
3314 | 0 | md.push_back( bestU ); |
3315 | 0 | } |
3316 | |
|
3317 | 0 | std::vector<int> assignTo( numNodes, -1 ); |
3318 | 0 | auto assignAll = [ & ]() |
3319 | 0 | { |
3320 | 0 | for( int u = 0; u < numNodes; u++ ) |
3321 | 0 | { |
3322 | 0 | int bestM = md.front(); |
3323 | 0 | int bestD = dist[ u ][ bestM ]; |
3324 | 0 | for( int m : md ) |
3325 | 0 | { |
3326 | 0 | const int d = dist[ u ][ m ]; |
3327 | 0 | if( d < bestD || ( d == bestD && m < bestM ) ) |
3328 | 0 | { |
3329 | 0 | bestD = d; |
3330 | 0 | bestM = m; |
3331 | 0 | } |
3332 | 0 | } |
3333 | 0 | assignTo[ u ] = bestM; |
3334 | 0 | } |
3335 | 0 | }; |
3336 | 0 | assignAll(); |
3337 | | |
3338 | | // swap a medoid with a non-medoid while that lowers the total weighted distance (at most 15 times) |
3339 | 0 | bool improved = true; |
3340 | 0 | for( int iter = 0; improved && iter < 15; iter++ ) |
3341 | 0 | { |
3342 | 0 | improved = false; |
3343 | 0 | long long bestDelta = 0; |
3344 | 0 | int bestOut = -1, bestIn = -1; |
3345 | 0 | std::vector<char> isM( numNodes, 0 ); |
3346 | 0 | for( int m : md ) |
3347 | 0 | { |
3348 | 0 | isM[ m ] = 1; |
3349 | 0 | } |
3350 | 0 | for( int mOut : md ) |
3351 | 0 | { |
3352 | 0 | for( int o = 0; o < numNodes; o++ ) |
3353 | 0 | { |
3354 | 0 | if( isM[ o ] ) |
3355 | 0 | { |
3356 | 0 | continue; |
3357 | 0 | } |
3358 | 0 | long long delta = 0; |
3359 | 0 | for( int u = 0; u < numNodes; u++ ) |
3360 | 0 | { |
3361 | 0 | const int duOld = dist[ u ][ assignTo[ u ] ]; |
3362 | 0 | const int dToO = dist[ u ][ o ]; |
3363 | 0 | int duNew; |
3364 | 0 | if( assignTo[ u ] == mOut ) |
3365 | 0 | { |
3366 | 0 | int dAlt = std::numeric_limits<int>::max(); |
3367 | 0 | for( int m : md ) |
3368 | 0 | { |
3369 | 0 | if( m != mOut ) |
3370 | 0 | { |
3371 | 0 | dAlt = std::min( dAlt, dist[ u ][ m ] ); |
3372 | 0 | } |
3373 | 0 | } |
3374 | 0 | duNew = std::min( dAlt, dToO ); |
3375 | 0 | } |
3376 | 0 | else |
3377 | 0 | { |
3378 | 0 | duNew = std::min( duOld, dToO ); |
3379 | 0 | } |
3380 | 0 | delta += 1LL * nodes[ u ].w * ( duNew - duOld ); |
3381 | 0 | } |
3382 | 0 | if( delta < bestDelta ) |
3383 | 0 | { |
3384 | 0 | bestDelta = delta; |
3385 | 0 | bestOut = mOut; |
3386 | 0 | bestIn = o; |
3387 | 0 | } |
3388 | 0 | } |
3389 | 0 | } |
3390 | 0 | if( bestDelta < 0 ) |
3391 | 0 | { |
3392 | 0 | *std::find( md.begin(), md.end(), bestOut ) = bestIn; |
3393 | 0 | assignAll(); |
3394 | 0 | improved = true; |
3395 | 0 | } |
3396 | 0 | } |
3397 | |
|
3398 | 0 | for( int u = 0; u < numNodes; u++ ) |
3399 | 0 | { |
3400 | 0 | for( int idx : nodes[ u ].idx ) |
3401 | 0 | { |
3402 | 0 | pairs[ idx ].p = nodes[ assignTo[ u ] ].p; |
3403 | 0 | } |
3404 | 0 | } |
3405 | 0 | return (int) md.size(); |
3406 | 0 | } |
3407 | | |
3408 | | // ==================================================================================================================== |
3409 | | // The film grain SEI scaled to the grain the coding lost |
3410 | | // ==================================================================================================================== |
3411 | | |
3412 | | // Units: squaredDct16 is orthonormal, so the AC power of a block is 256 x its sample variance at the coded bit depth. |
3413 | | // The fit uses the blocks where grain shows: in every band of 8-bit block means (LOST_GRAIN_BAND_EDGES) the 30 % with the |
3414 | | // least power in the five lowest AC coefficients (u + v = 1, 2), the smoothest areas. The former flat test (u + v = 1, 2 |
3415 | | // power at most 4x the mean of u + v >= 4) kept a noise-dominated minority (gangster_chase: 1-6k blocks per band in 178 |
3416 | | // pictures, against 15-87k smooth ones) that loses 2-3x more fine grain per block, so the fit put back 1.07-1.25x the fine |
3417 | | // grain the smooth areas lost. Blocks darker than the first edge (digital black) or from the last one (white) are not fitted. |
3418 | | static constexpr int LOST_GRAIN_BAND_EDGES[] = { 18, 33, 65, 97, 129, 161, 238 }; |
3419 | | static constexpr int LOST_GRAIN_NUM_BANDS = sizeof( LOST_GRAIN_BAND_EDGES ) / sizeof( LOST_GRAIN_BAND_EDGES[ 0 ] ) - 1; |
3420 | | |
3421 | | // The band of an 8-bit block mean, -1: not fitted. |
3422 | | static int lostGrainBand( int mean8 ) |
3423 | 0 | { |
3424 | 0 | if( mean8 < LOST_GRAIN_BAND_EDGES[ 0 ] || mean8 >= LOST_GRAIN_BAND_EDGES[ LOST_GRAIN_NUM_BANDS ] ) |
3425 | 0 | { |
3426 | 0 | return -1; |
3427 | 0 | } |
3428 | 0 | int band = 0; |
3429 | 0 | while( mean8 >= LOST_GRAIN_BAND_EDGES[ band + 1 ] ) |
3430 | 0 | { |
3431 | 0 | band++; |
3432 | 0 | } |
3433 | 0 | return band; |
3434 | 0 | } |
3435 | | |
3436 | | // The power of a 16x16 block in the five lowest AC coefficients of squaredDct16, [u][v] with u + v = 1, 2 (u the |
3437 | | // horizontal frequency), without computing the other 251. It equals the sum of those five outputs of squaredDct16 bit |
3438 | | // for bit: a coefficient depends only on its own row of the horizontal stage, and the integer sums, the rounding, the |
3439 | | // clipping and the order of the five additions are those of fgaSquaredDct16Core, which the SIMD kernels match exactly. |
3440 | | static double lowFrequencyPower16( const Pel* src, int stride, int maxRange ) |
3441 | 0 | { |
3442 | 0 | constexpr int N = 16; |
3443 | 0 | constexpr int NUM_HORIZONTAL = 3; // the horizontal frequencies 0 .. 2 hold the five coefficients |
3444 | 0 | constexpr int LOW[ 5 ][ 2 ] = { { 0, 1 }, { 0, 2 }, { 1, 0 }, { 1, 1 }, { 2, 0 } }; // (u, v), in squaredDct16's order |
3445 | 0 | const TMatrixCoeff* tr = g_trCoreDCT2P16[ TRANSFORM_FORWARD ][ 0 ]; |
3446 | 0 | int horizontal[ NUM_HORIZONTAL ][ N ]; // [horizontal frequency][row] |
3447 | 0 | for( int u = 0; u < NUM_HORIZONTAL; u++ ) |
3448 | 0 | { |
3449 | 0 | for( int y = 0; y < N; y++ ) |
3450 | 0 | { |
3451 | 0 | const Pel* row = src + y * stride; |
3452 | 0 | int acc = 0; |
3453 | 0 | for( int k = 0; k < N; k++ ) |
3454 | 0 | { |
3455 | 0 | acc += tr[ u * N + k ] * row[ k ]; |
3456 | 0 | } |
3457 | 0 | horizontal[ u ][ y ] = ( acc + 128 ) >> 8; |
3458 | 0 | } |
3459 | 0 | } |
3460 | 0 | double low = 0.0; |
3461 | 0 | for( const auto& uv : LOW ) |
3462 | 0 | { |
3463 | 0 | int acc = 0; |
3464 | 0 | for( int k = 0; k < N; k++ ) |
3465 | 0 | { |
3466 | 0 | acc += horizontal[ uv[ 0 ] ][ k ] * tr[ uv[ 1 ] * N + k ]; |
3467 | 0 | } |
3468 | 0 | const int64_t c = Clip3( -maxRange, maxRange, ( acc + 128 ) >> 8 ); |
3469 | 0 | low += (double) ( c * c ); |
3470 | 0 | } |
3471 | 0 | return low; |
3472 | 0 | } |
3473 | | |
3474 | | void FGAnalyzer::lostGrainSpectra( const CPelBuf& org, const CPelBuf& rec, int bitDepth, std::vector<LostGrainSpectrum>& spectra ) const |
3475 | 0 | { |
3476 | 0 | constexpr int N = 16; // squaredDct16's block size |
3477 | 0 | const int maxRange = ( 1 << ( bitDepth + 4 ) ) - 1; |
3478 | | |
3479 | | // pass 1: every block's mean and low-frequency power, listed per band |
3480 | 0 | struct Block |
3481 | 0 | { |
3482 | 0 | int x, y, mean8; |
3483 | 0 | }; |
3484 | 0 | std::vector<Block> blocks; |
3485 | 0 | std::vector<std::pair<double, size_t>> bandBlocks[ LOST_GRAIN_NUM_BANDS ]; // (low-frequency power, index in blocks) |
3486 | 0 | for( int y = 0; y + N <= (int) org.height; y += N ) |
3487 | 0 | { |
3488 | 0 | for( int x = 0; x + N <= (int) org.width; x += N ) |
3489 | 0 | { |
3490 | 0 | const Pel* o = org.bufAt( x, y ); |
3491 | 0 | int64_t sum = 0; |
3492 | 0 | for( int j = 0; j < N; j++ ) |
3493 | 0 | { |
3494 | 0 | for( int i = 0; i < N; i++ ) |
3495 | 0 | { |
3496 | 0 | sum += o[ j * org.stride + i ]; |
3497 | 0 | } |
3498 | 0 | } |
3499 | 0 | const int mean8 = std::min( 255, (int) ( ( sum + N * N / 2 ) / ( N * N ) ) >> ( bitDepth - BIT_DEPTH_8 ) ); |
3500 | 0 | const int band = lostGrainBand( mean8 ); |
3501 | 0 | if( band < 0 ) |
3502 | 0 | { |
3503 | 0 | continue; |
3504 | 0 | } |
3505 | 0 | const double low = lowFrequencyPower16( o, org.stride, maxRange ); |
3506 | 0 | bandBlocks[ band ].push_back( { low, blocks.size() } ); |
3507 | 0 | blocks.push_back( { x, y, mean8 } ); |
3508 | 0 | } |
3509 | 0 | } |
3510 | | |
3511 | | // the smoothest 30 % of every band (the index breaks ties, so the choice does not depend on the sort) |
3512 | 0 | std::vector<uint8_t> selected( blocks.size(), 0 ); |
3513 | 0 | for( auto& candidates : bandBlocks ) |
3514 | 0 | { |
3515 | 0 | const size_t keep = candidates.size() * 3 / 10; |
3516 | 0 | std::nth_element( candidates.begin(), candidates.begin() + keep, candidates.end() ); |
3517 | 0 | for( size_t k = 0; k < keep; k++ ) |
3518 | 0 | { |
3519 | 0 | selected[ candidates[ k ].second ] = 1; |
3520 | 0 | } |
3521 | 0 | } |
3522 | | |
3523 | | // pass 2: the spectra of the selected blocks of the original and the reconstruction per 8-bit block mean, summed in |
3524 | | // picture order |
3525 | 0 | int slot[ 256 ]; // per 8-bit block mean: its entry in spectra, -1: none yet |
3526 | 0 | std::fill_n( slot, 256, -1 ); |
3527 | 0 | spectra.clear(); |
3528 | 0 | for( size_t i = 0; i < blocks.size(); i++ ) |
3529 | 0 | { |
3530 | 0 | if( !selected[ i ] ) |
3531 | 0 | { |
3532 | 0 | continue; |
3533 | 0 | } |
3534 | 0 | const Block& b = blocks[ i ]; |
3535 | 0 | double so[ N * N ] = {}, sr[ N * N ] = {}; |
3536 | 0 | m_kernels.squaredDct16( org.bufAt( b.x, b.y ), org.stride, maxRange, so ); |
3537 | 0 | m_kernels.squaredDct16( rec.bufAt( b.x, b.y ), rec.stride, maxRange, sr ); |
3538 | 0 | if( slot[ b.mean8 ] < 0 ) |
3539 | 0 | { |
3540 | 0 | slot[ b.mean8 ] = (int) spectra.size(); |
3541 | 0 | spectra.emplace_back(); |
3542 | 0 | spectra.back().mean8 = b.mean8; |
3543 | 0 | } |
3544 | 0 | LostGrainSpectrum& s = spectra[ slot[ b.mean8 ] ]; |
3545 | 0 | for( int k = 1; k < N * N; k++ ) |
3546 | 0 | { |
3547 | 0 | s.orig[ k ] += so[ k ]; |
3548 | 0 | s.reco[ k ] += sr[ k ]; |
3549 | 0 | } |
3550 | 0 | s.blocks++; |
3551 | 0 | } |
3552 | 0 | std::sort( spectra.begin(), spectra.end(), []( const LostGrainSpectrum& a, const LostGrainSpectrum& b ) { return a.mean8 < b.mean8; } ); |
3553 | 0 | } |
3554 | | |
3555 | | // The synthesized grain of scaling factor s at cut-offs (h, w): standard deviation sigma = s x PATTERN_STDDEV / |
3556 | | // 2^(l + 14 - bitDepth), of which a 16x16 block keeps BLOCK_VARIANCE_SHARE of the variance, spread over the coefficients |
3557 | | // like the product of the synthesis's horizontal and vertical marginals (GRAIN_SPECTRUM_MARGINALS: the synthesis |
3558 | | // band-limits a rectangle, so its spectrum is close to separable). |
3559 | | int FGAnalyzer::equalPowerScale( int s, bool chroma420, int h0, int w0, int h, int w ) |
3560 | 0 | { |
3561 | 0 | const int table = chroma420 ? 1 : 0; |
3562 | 0 | h0 = Clip3( 2, 14, h0 ); w0 = Clip3( 2, 14, w0 ); h = Clip3( 2, 14, h ); w = Clip3( 2, 14, w ); |
3563 | 0 | const double amp0 = PATTERN_STDDEV[ table ][ h0 - 2 ][ w0 - 2 ] * std::sqrt( BLOCK_VARIANCE_SHARE[ table ][ h0 - 2 ][ w0 - 2 ] ); |
3564 | 0 | const double amp = PATTERN_STDDEV[ table ][ h - 2 ][ w - 2 ] * std::sqrt( BLOCK_VARIANCE_SHARE[ table ][ h - 2 ][ w - 2 ] ); |
3565 | 0 | return std::min( MAX_STANDARD_DEVIATION, (int) ( s * amp0 / amp + 0.5 ) ); |
3566 | 0 | } |
3567 | | |
3568 | | int FGAnalyzer::lostGrainCapScale( int s0, bool chroma420, int h0, int w0, int h, int w ) |
3569 | 0 | { |
3570 | | // never above MAX_SCALING_FACTOR, like every scaling factor the analyzer signals (vvdec's x86 synthesis sign-extends 128 and up) |
3571 | 0 | return std::min( MAX_SCALING_FACTOR, (int) ( equalPowerScale( s0, chroma420, h0, w0, h, w ) * std::sqrt( LOST_GRAIN_CAP_POWER ) + 0.5 ) ); |
3572 | 0 | } |
3573 | | |
3574 | | // The u + v frequency groups of the fit: 1-2, 3-5, 6-8, 9-12, 13-30 (the group of DCT coefficient k of a 16x16 block). |
3575 | | static constexpr int LOST_GRAIN_GROUP_END[ FGAnalyzer::LostGrainPower::GROUPS ] = { 2, 5, 8, 12, 30 }; |
3576 | | |
3577 | | static int lostGrainGroup( int k ) |
3578 | 0 | { |
3579 | 0 | const int f = k / 16 + k % 16; |
3580 | 0 | int g = 0; |
3581 | 0 | while( f > LOST_GRAIN_GROUP_END[ g ] ) |
3582 | 0 | { |
3583 | 0 | g++; |
3584 | 0 | } |
3585 | 0 | return g; |
3586 | 0 | } |
3587 | | |
3588 | | // The fit also tells the two directions apart: the share of coefficient k (u = k / 16 horizontal, v = k % 16 vertical |
3589 | | // frequency) in direction 0 (u > v: detail that varies along x); the diagonal (u == v) counts half in each. Grain whose |
3590 | | // cut-offs (h, w) are swapped has the same power per u + v group, so a fit by u + v alone picks the shift (dh, dw) or its |
3591 | | // transpose by chance and can synthesize grain stretched across the lost grain's direction (streaks): on the fast preset's |
3592 | | // q23 film scan bk_1191 the coding lost fine-band grain at x / y 0.47-0.93 and the synthesis put it back at 1.39-1.89. |
3593 | | static double lostGrainHorizontalShare( int k ) |
3594 | 0 | { |
3595 | 0 | const int u = k / 16, v = k % 16; |
3596 | 0 | return u > v ? 1.0 : u < v ? 0.0 : 0.5; |
3597 | 0 | } |
3598 | | |
3599 | | FGAnalyzer::LostGrainPower FGAnalyzer::lostGrainPower( const double orig[ 256 ], const double reco[ 256 ], int blocks ) |
3600 | 0 | { |
3601 | 0 | LostGrainPower p; |
3602 | 0 | p.blocks = blocks; |
3603 | 0 | if( blocks <= 0 ) |
3604 | 0 | { |
3605 | 0 | return p; |
3606 | 0 | } |
3607 | 0 | for( int k = 1; k < 256; k++ ) |
3608 | 0 | { |
3609 | 0 | const int g = lostGrainGroup( k ); |
3610 | 0 | const double wx = lostGrainHorizontalShare( k ); |
3611 | 0 | p.orig[ g ][ 0 ] += wx * orig[ k ] / blocks; |
3612 | 0 | p.orig[ g ][ 1 ] += ( 1.0 - wx ) * orig[ k ] / blocks; |
3613 | 0 | p.reco[ g ][ 0 ] += wx * reco[ k ] / blocks; |
3614 | 0 | p.reco[ g ][ 1 ] += ( 1.0 - wx ) * reco[ k ] / blocks; |
3615 | 0 | } |
3616 | 0 | return p; |
3617 | 0 | } |
3618 | | |
3619 | | // The fit compares the reconstruction plus the synthesis with the original per u + v group of the 16x16 DCT. The lowest |
3620 | | // group (u + v = 1, 2) is not fitted: there the coding ADDS power (blocking, ringing; nocturne_grain at q23 reconstructs more |
3621 | | // than the original), so a fit including it pulls the scale down while the fine band stays short. It only limits the |
3622 | | // synthesis: coarse grain lifts it too (on Top Gun's dark intervals the synthesis about doubled its power), which reads as |
3623 | | // grain the coding never lost. |
3624 | | static constexpr int LOST_GRAIN_FIRST_FITTED_GROUP = 1; |
3625 | | // Grain put back beyond what the coding lost counts this many times more than grain missing (the coded picture keeps some |
3626 | | // grain of its own at high rates, so too much is worse than too little); the same weight applies to lifting the lowest group. |
3627 | | static constexpr double LOST_GRAIN_OVERSHOOT_WEIGHT = 4.0; |
3628 | | |
3629 | | // The fit's cost of synthesized grain of variance var whose power per unit variance per group and direction is |
3630 | | // synthPower: the lowest group's lift above the larger of the original's and the reconstruction's power, then the squared |
3631 | | // log ratios of reconstruction plus synthesis to the original over the fitted groups, both directions, overshoot weighted. |
3632 | | static double lostGrainCost( const FGAnalyzer::LostGrainPower& power, double var, |
3633 | | const double synthPower[][ FGAnalyzer::LostGrainPower::DIRECTIONS ] ) |
3634 | 0 | { |
3635 | 0 | double cost = 0.0; |
3636 | 0 | for( int d = 0; d < FGAnalyzer::LostGrainPower::DIRECTIONS; d++ ) |
3637 | 0 | { |
3638 | 0 | const double floor0 = std::max( power.orig[ 0 ][ d ], power.reco[ 0 ][ d ] ); |
3639 | 0 | if( floor0 > 0 ) |
3640 | 0 | { |
3641 | 0 | const double r = std::log( ( power.reco[ 0 ][ d ] + var * synthPower[ 0 ][ d ] + 1e-9 ) / floor0 ); |
3642 | 0 | cost += r > 0 ? LOST_GRAIN_OVERSHOOT_WEIGHT * r * r : 0.0; |
3643 | 0 | } |
3644 | 0 | } |
3645 | 0 | for( int g = LOST_GRAIN_FIRST_FITTED_GROUP; g < FGAnalyzer::LostGrainPower::GROUPS; g++ ) |
3646 | 0 | { |
3647 | 0 | for( int d = 0; d < FGAnalyzer::LostGrainPower::DIRECTIONS; d++ ) |
3648 | 0 | { |
3649 | 0 | if( power.orig[ g ][ d ] > 0 ) |
3650 | 0 | { |
3651 | 0 | const double r = std::log( ( power.reco[ g ][ d ] + var * synthPower[ g ][ d ] + 1e-9 ) / power.orig[ g ][ d ] ); |
3652 | 0 | cost += ( r > 0 ? LOST_GRAIN_OVERSHOOT_WEIGHT : 1.0 ) * r * r; |
3653 | 0 | } |
3654 | 0 | } |
3655 | 0 | } |
3656 | 0 | return cost; |
3657 | 0 | } |
3658 | | |
3659 | | FGAnalyzer::LostGrainShape FGAnalyzer::lostGrainShape( bool chroma420, int h, int w ) |
3660 | 0 | { |
3661 | 0 | constexpr int N = 16; |
3662 | 0 | const int table = chroma420 ? 1 : 0; |
3663 | 0 | h = Clip3( 2, 14, h ); w = Clip3( 2, 14, w ); |
3664 | 0 | const auto& m = GRAIN_SPECTRUM_MARGINALS[ table ][ h - 2 ][ w - 2 ]; |
3665 | 0 | double shapeSum = 0.0; |
3666 | 0 | for( int k = 1; k < N * N; k++ ) |
3667 | 0 | { |
3668 | 0 | shapeSum += m[ 0 ][ k / N ] * m[ 1 ][ k % N ]; |
3669 | 0 | } |
3670 | 0 | LostGrainShape shape; |
3671 | 0 | shape.patternStddev = PATTERN_STDDEV[ table ][ h - 2 ][ w - 2 ]; |
3672 | 0 | shape.blockShare = BLOCK_VARIANCE_SHARE[ table ][ h - 2 ][ w - 2 ]; |
3673 | | // per group and direction: the synthesis's power per unit grain variance |
3674 | 0 | const double share = shape.blockShare; |
3675 | 0 | for( int k = 1; k < N * N; k++ ) |
3676 | 0 | { |
3677 | 0 | const double p = N * N * share * m[ 0 ][ k / N ] * m[ 1 ][ k % N ] / shapeSum; |
3678 | 0 | const double wx = lostGrainHorizontalShare( k ); |
3679 | 0 | shape.power[ lostGrainGroup( k ) ][ 0 ] += wx * p; |
3680 | 0 | shape.power[ lostGrainGroup( k ) ][ 1 ] += ( 1.0 - wx ) * p; |
3681 | 0 | } |
3682 | 0 | return shape; |
3683 | 0 | } |
3684 | | |
3685 | | double FGAnalyzer::lostGrainFit( const LostGrainPower& power, int bitDepth, bool chroma420, int log2ScaleFactor, int s0, int h0, |
3686 | | int w0, const LostGrainShape& shape, int& scale ) |
3687 | 0 | { |
3688 | 0 | scale = s0; |
3689 | 0 | if( power.blocks <= 0 || s0 <= 0 ) |
3690 | 0 | { |
3691 | 0 | return -1.0; |
3692 | 0 | } |
3693 | 0 | const int table = chroma420 ? 1 : 0; |
3694 | 0 | h0 = Clip3( 2, 14, h0 ); w0 = Clip3( 2, 14, w0 ); |
3695 | 0 | const double unit = 1.0 / double( 1 << ( log2ScaleFactor + 14 - bitDepth ) ); |
3696 | 0 | const double sigma0 = s0 * PATTERN_STDDEV[ table ][ h0 - 2 ][ w0 - 2 ] * unit; |
3697 | 0 | const double power0 = sigma0 * sigma0 * BLOCK_VARIANCE_SHARE[ table ][ h0 - 2 ][ w0 - 2 ]; // the analyzer's grain |
3698 | 0 | const double share = shape.blockShare; |
3699 | 0 | const double sigmaUnit = shape.patternStddev * unit; |
3700 | 0 | double best = -1.0; |
3701 | 0 | for( int s = 0; s <= MAX_STANDARD_DEVIATION; s++ ) |
3702 | 0 | { |
3703 | 0 | const double var = ( s * sigmaUnit ) * ( s * sigmaUnit ); |
3704 | 0 | if( var * share > power0 * LOST_GRAIN_CAP_POWER * ( 1.0 + 1e-9 ) ) |
3705 | 0 | { |
3706 | 0 | break; |
3707 | 0 | } |
3708 | 0 | const double cost = lostGrainCost( power, var, shape.power ); |
3709 | 0 | if( best < 0 || cost < best ) |
3710 | 0 | { |
3711 | 0 | best = cost; |
3712 | 0 | scale = s; |
3713 | 0 | } |
3714 | 0 | } |
3715 | 0 | return best; |
3716 | 0 | } |
3717 | | |
3718 | | int FGAnalyzer::lostGrainCapScaleAr( int s0 ) |
3719 | 0 | { |
3720 | 0 | return std::min( MAX_SCALING_FACTOR, (int) ( s0 * std::sqrt( LOST_GRAIN_CAP_POWER ) + 0.5 ) ); |
3721 | 0 | } |
3722 | | |
3723 | | // The synthesis rounds the grain it adds to whole sample values. Gaussian grain of standard deviation stddev (in sample |
3724 | | // units), rounded, is gain times the grain plus an error that is not correlated with it and is close to white (Bussgang's |
3725 | | // decomposition): from two sample units on the gain is 1 and the error's variance 1 / 12; below, the sums over the whole |
3726 | | // values n give both. Weak grain is mostly this white error: on Top Gun (grain of 0.95 sample units at 10 bits) the |
3727 | | // synthesized grain measured 0.37 / 0.19 / 0.15 / 0.28 of its power in the bands u + v 3-5 / 6-8 / 9-12 / 13-30 at a |
3728 | | // standard deviation of 0.74-0.76 there; the filter alone gives 0.44 / 0.21 / 0.15 / 0.19 at 0.68, with the rounding |
3729 | | // 0.39 / 0.20 / 0.16 / 0.26 at 0.74. The error's power at the finest frequencies there (0.054 per sample) is more than |
3730 | | // the coding lost (0.032), which a fit without it cannot see. |
3731 | | static void roundedGrain( double stddev, double& gain, double& errorVariance ) |
3732 | 0 | { |
3733 | 0 | gain = 1.0; |
3734 | 0 | errorVariance = 1.0 / 12.0; |
3735 | 0 | if( stddev >= 2.0 ) |
3736 | 0 | { |
3737 | 0 | return; |
3738 | 0 | } |
3739 | 0 | if( stddev <= 0.0 ) |
3740 | 0 | { |
3741 | 0 | gain = errorVariance = 0.0; |
3742 | 0 | return; |
3743 | 0 | } |
3744 | 0 | constexpr int MAX_VALUE = 14; // beyond 6 standard deviations of the largest stddev handled here |
3745 | 0 | constexpr double SQRT_2PI = 2.5066282746310002; |
3746 | 0 | double outputVariance = 0.0; |
3747 | 0 | gain = 0.0; |
3748 | 0 | for( int n = 1; n <= MAX_VALUE; n++ ) |
3749 | 0 | { |
3750 | 0 | const double low = ( n - 0.5 ) / stddev, high = ( n + 0.5 ) / stddev; // the values rounded to +-n, in stddev units |
3751 | 0 | outputVariance += n * n * ( std::erf( high / std::sqrt( 2.0 ) ) - std::erf( low / std::sqrt( 2.0 ) ) ); |
3752 | 0 | gain += 2.0 * n * ( std::exp( -0.5 * low * low ) - std::exp( -0.5 * high * high ) ) / ( stddev * SQRT_2PI ); |
3753 | 0 | } |
3754 | 0 | errorVariance = std::max( 0.0, outputVariance - gain * gain * stddev * stddev ); |
3755 | 0 | } |
3756 | | |
3757 | | // The most a band of reconstruction plus synthesis may exceed the original's power in the fit of the auto-regressive |
3758 | | // model: 1.1 times in amplitude. |
3759 | | static constexpr double LOST_GRAIN_AR_MAX_OVERSHOOT = 1.1 * 1.1; |
3760 | | |
3761 | | double FGAnalyzer::lostGrainFitAr( const LostGrainPower& power, const ArGrain& grain, int s0, int& scale ) |
3762 | 0 | { |
3763 | 0 | scale = s0; |
3764 | 0 | if( power.blocks <= 0 || s0 <= 0 ) |
3765 | 0 | { |
3766 | 0 | return -1.0; |
3767 | 0 | } |
3768 | | // the number of coefficients per group and direction: the rounding error has the same power in every coefficient |
3769 | 0 | double coefficients[ LostGrainPower::GROUPS ][ LostGrainPower::DIRECTIONS ] = {}; |
3770 | 0 | for( int k = 1; k < BLOCK_SIZE * BLOCK_SIZE; k++ ) |
3771 | 0 | { |
3772 | 0 | coefficients[ lostGrainGroup( k ) ][ 0 ] += lostGrainHorizontalShare( k ); |
3773 | 0 | coefficients[ lostGrainGroup( k ) ][ 1 ] += 1.0 - lostGrainHorizontalShare( k ); |
3774 | 0 | } |
3775 | 0 | const int cap = lostGrainCapScaleAr( s0 ); |
3776 | 0 | double best = -1.0; |
3777 | 0 | for( int s = 0; s <= cap; s++ ) |
3778 | 0 | { |
3779 | 0 | double gain, errorVariance; |
3780 | 0 | roundedGrain( s * grain.stddevPerScale, gain, errorVariance ); |
3781 | 0 | const double variance = gain * gain * s * grain.stddevPerScale * s * grain.stddevPerScale; // of the filtered part |
3782 | 0 | double synthesized[ LostGrainPower::GROUPS ][ LostGrainPower::DIRECTIONS ]; |
3783 | 0 | for( int g = 0; g < LostGrainPower::GROUPS; g++ ) |
3784 | 0 | { |
3785 | 0 | for( int d = 0; d < LostGrainPower::DIRECTIONS; d++ ) |
3786 | 0 | { |
3787 | 0 | synthesized[ g ][ d ] = variance * grain.bandPower[ g ][ d ] + errorVariance * coefficients[ g ][ d ]; |
3788 | 0 | } |
3789 | 0 | } |
3790 | | // The cost alone lets a band end far above the original where the coding lost mostly coarse grain: the filter's grain |
3791 | | // has the same shape at every strength, so more of it at the coarse frequencies is also more at the finest (Top Gun's |
3792 | | // sky: the decoded picture with grain had 1.47-1.49 of the source's finest band, to lift u + v 3-5 from 0.37-0.39 of |
3793 | | // the source's to 0.43-0.44). So no band from u + v = 3 may end more than LOST_GRAIN_AR_MAX_OVERSHOOT above the |
3794 | | // original's power; a little above is accepted where the cost finds the bands better matched on average. Bands where |
3795 | | // the reconstruction alone is above the original do not count: no grain can change that. |
3796 | | // The synthesized power grows with the scaling factor, so the search ends at the first one that exceeds. |
3797 | 0 | bool exceeds = false; |
3798 | 0 | for( int g = LOST_GRAIN_FIRST_FITTED_GROUP; g < LostGrainPower::GROUPS && s > 0; g++ ) |
3799 | 0 | { |
3800 | 0 | for( int d = 0; d < LostGrainPower::DIRECTIONS; d++ ) |
3801 | 0 | { |
3802 | 0 | exceeds = exceeds || ( power.reco[ g ][ d ] <= power.orig[ g ][ d ] |
3803 | 0 | && power.reco[ g ][ d ] + synthesized[ g ][ d ] > LOST_GRAIN_AR_MAX_OVERSHOOT * power.orig[ g ][ d ] ); |
3804 | 0 | } |
3805 | 0 | } |
3806 | 0 | if( exceeds ) |
3807 | 0 | { |
3808 | 0 | break; |
3809 | 0 | } |
3810 | 0 | const double cost = lostGrainCost( power, 1.0, synthesized ); |
3811 | 0 | if( best < 0 || cost < best ) |
3812 | 0 | { |
3813 | 0 | best = cost; |
3814 | 0 | scale = s; |
3815 | 0 | } |
3816 | 0 | } |
3817 | 0 | return best; |
3818 | 0 | } |
3819 | | |
3820 | | } // namespace vvenc |