1 // ****************************************************************************
2 // * This file is part of the HqMAME project. It is distributed under         *
3 // * GNU General Public License: http://www.gnu.org/licenses/gpl.html         *
4 // * Copyright (C) Zenju (zenju AT gmx DOT de) - All Rights Reserved          *
5 // *                                                                          *
6 // * Additionally and as a special exception, the author gives permission     *
7 // * to link the code of this program with the MAME library (or with modified *
8 // * versions of MAME that use the same license as MAME), and distribute      *
9 // * linked combinations including the two. You must obey the GNU General     *
10 // * Public License in all respects for all of the code used other than MAME. *
11 // * If you modify this file, you may extend this exception to your version   *
12 // * of the file, but you are not obligated to do so. If you do not wish to   *
13 // * do so, delete this exception statement from your version.                *
14 // ****************************************************************************
15 
16 #include "xbrz.h"
17 #include <cmath>
18 #include <cassert>
19 #include <algorithm>
20 #include <limits>
21 #include <vector>
22 
23 namespace
24 {
25 template <uint32_t N> inline
getByte(uint32_t val)26 unsigned char getByte(uint32_t val) { return static_cast<unsigned char>((val >> (8 * N)) & 0xff); }
27 
28 // adjusted for RGBA
29 // - Durante
getRed(uint32_t pix)30 inline unsigned char getRed  (uint32_t pix) { return getByte<0>(pix); }
getGreen(uint32_t pix)31 inline unsigned char getGreen(uint32_t pix) { return getByte<1>(pix); }
getBlue(uint32_t pix)32 inline unsigned char getBlue (uint32_t pix) { return getByte<2>(pix); }
getAlpha(uint32_t pix)33 inline unsigned char getAlpha(uint32_t pix) { return getByte<3>(pix); }
34 
makePixel(unsigned char r,unsigned char g,unsigned char b)35 inline uint32_t makePixel(                 unsigned char r, unsigned char g, unsigned char b) { return             (b << 16) | (g << 8) | r; }
makePixel(unsigned char a,unsigned char r,unsigned char g,unsigned char b)36 inline uint32_t makePixel(unsigned char a, unsigned char r, unsigned char g, unsigned char b) { return (a << 24) | (b << 16) | (g << 8) | r; }
37 
38 
39 template <unsigned int M, unsigned int N> inline
gradientRGB(uint32_t pixFront,uint32_t pixBack)40 uint32_t gradientRGB(uint32_t pixFront, uint32_t pixBack) //blend front color with opacity M / N over opaque background: http://en.wikipedia.org/wiki/Alpha_compositing#Alpha_blending
41 {
42 	static_assert(0 < M && M < N && N <= 1000, "");
43 
44 	auto calcColor = [](unsigned char colFront, unsigned char colBack) -> unsigned char { return (colFront * M + colBack * (N - M)) / N; };
45 
46 	return makePixel(calcColor(getRed  (pixFront), getRed  (pixBack)),
47 					 calcColor(getGreen(pixFront), getGreen(pixBack)),
48 					 calcColor(getBlue (pixFront), getBlue (pixBack)));
49 }
50 
51 
52 template <unsigned int M, unsigned int N> inline
gradientARGB(uint32_t pixFront,uint32_t pixBack)53 uint32_t gradientARGB(uint32_t pixFront, uint32_t pixBack) //find intermediate color between two colors with alpha channels (=> NO alpha blending!!!)
54 {
55 	static_assert(0 < M && M < N && N <= 1000, "");
56 
57 	const unsigned int weightFront = getAlpha(pixFront) * M;
58 	const unsigned int weightBack  = getAlpha(pixBack) * (N - M);
59 	const unsigned int weightSum   = weightFront + weightBack;
60 	if (weightSum == 0)
61 		return 0;
62 
63 	auto calcColor = [=](unsigned char colFront, unsigned char colBack)
64 	{
65 		return static_cast<unsigned char>((colFront * weightFront + colBack * weightBack) / weightSum);
66 	};
67 
68 	return makePixel(static_cast<unsigned char>(weightSum / N),
69 					 calcColor(getRed  (pixFront), getRed  (pixBack)),
70 					 calcColor(getGreen(pixFront), getGreen(pixBack)),
71 					 calcColor(getBlue (pixFront), getBlue (pixBack)));
72 }
73 
74 
75 //inline
76 //double fastSqrt(double n)
77 //{
78 //    __asm //speeds up xBRZ by about 9% compared to std::sqrt which internally uses the same assembler instructions but adds some "fluff"
79 //    {
80 //        fld n
81 //        fsqrt
82 //    }
83 //}
84 //
85 
86 
byteAdvance(uint32_t * ptr,int bytes)87 uint32_t*       byteAdvance(      uint32_t* ptr, int bytes) { return reinterpret_cast<      uint32_t*>(reinterpret_cast<      char*>(ptr) + bytes); }
byteAdvance(const uint32_t * ptr,int bytes)88 const uint32_t* byteAdvance(const uint32_t* ptr, int bytes) { return reinterpret_cast<const uint32_t*>(reinterpret_cast<const char*>(ptr) + bytes); }
89 
90 
91 //fill block  with the given color
92 inline
fillBlock(uint32_t * trg,int pitch,uint32_t col,int blockWidth,int blockHeight)93 void fillBlock(uint32_t* trg, int pitch, uint32_t col, int blockWidth, int blockHeight)
94 {
95 	//for (int y = 0; y < blockHeight; ++y, trg = byteAdvance(trg, pitch))
96 	//	std::fill(trg, trg + blockWidth, col);
97 
98 	for (int y = 0; y < blockHeight; ++y, trg = byteAdvance(trg, pitch))
99 		for (int x = 0; x < blockWidth; ++x)
100 			trg[x] = col;
101 }
102 
103 inline
fillBlock(uint32_t * trg,int pitch,uint32_t col,int n)104 void fillBlock(uint32_t* trg, int pitch, uint32_t col, int n) { fillBlock(trg, pitch, col, n, n); }
105 
106 
107 #ifdef _MSC_VER
108 #define FORCE_INLINE __forceinline
109 #elif defined __GNUC__
110 #define FORCE_INLINE __attribute__((always_inline)) inline
111 #else
112 #define FORCE_INLINE inline
113 #endif
114 
115 
116 enum RotationDegree //clock-wise
117 {
118 	ROT_0,
119 	ROT_90,
120 	ROT_180,
121 	ROT_270
122 };
123 
124 //calculate input matrix coordinates after rotation at compile time
125 template <RotationDegree rotDeg, size_t I, size_t J, size_t N>
126 struct MatrixRotation;
127 
128 template <size_t I, size_t J, size_t N>
129 struct MatrixRotation<ROT_0, I, J, N>
130 {
131 	static const size_t I_old = I;
132 	static const size_t J_old = J;
133 };
134 
135 template <RotationDegree rotDeg, size_t I, size_t J, size_t N> //(i, j) = (row, col) indices, N = size of (square) matrix
136 struct MatrixRotation
137 {
138 	static const size_t I_old = N - 1 - MatrixRotation<static_cast<RotationDegree>(rotDeg - 1), I, J, N>::J_old; //old coordinates before rotation!
139 	static const size_t J_old =	        MatrixRotation<static_cast<RotationDegree>(rotDeg - 1), I, J, N>::I_old; //
140 };
141 
142 
143 template <size_t N, RotationDegree rotDeg>
144 class OutputMatrix
145 {
146 public:
OutputMatrix(uint32_t * out,int outWidth)147 	OutputMatrix(uint32_t* out, int outWidth) : //access matrix area, top-left at position "out" for image with given width
148 		out_(out),
149 		outWidth_(outWidth) {}
150 
151 	template <size_t I, size_t J>
ref() const152 	uint32_t& ref() const
153 	{
154 		static const size_t I_old = MatrixRotation<rotDeg, I, J, N>::I_old;
155 		static const size_t J_old = MatrixRotation<rotDeg, I, J, N>::J_old;
156 		return *(out_ + J_old + I_old * outWidth_);
157 	}
158 
159 private:
160 	uint32_t* out_;
161 	const int outWidth_;
162 };
163 
164 
165 template <class T> inline
square(T value)166 T square(T value) { return value * value; }
167 
168 
169 
170 inline
distRGB(uint32_t pix1,uint32_t pix2)171 double distRGB(uint32_t pix1, uint32_t pix2)
172 {
173 	const double r_diff = static_cast<int>(getRed  (pix1)) - getRed  (pix2);
174 	const double g_diff = static_cast<int>(getGreen(pix1)) - getGreen(pix2);
175 	const double b_diff = static_cast<int>(getBlue (pix1)) - getBlue (pix2);
176 
177 	//euklidean RGB distance
178 	return std::sqrt(square(r_diff) + square(g_diff) + square(b_diff));
179 }
180 
181 
182 inline
distYCbCr(uint32_t pix1,uint32_t pix2,double lumaWeight)183 double distYCbCr(uint32_t pix1, uint32_t pix2, double lumaWeight)
184 {
185 	//http://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion
186 	//YCbCr conversion is a matrix multiplication => take advantage of linearity by subtracting first!
187 	const int r_diff = static_cast<int>(getRed  (pix1)) - getRed  (pix2); //we may delay division by 255 to after matrix multiplication
188 	const int g_diff = static_cast<int>(getGreen(pix1)) - getGreen(pix2); //
189 	const int b_diff = static_cast<int>(getBlue (pix1)) - getBlue (pix2); //substraction for int is noticeable faster than for double!
190 
191 	//const double k_b = 0.0722; //ITU-R BT.709 conversion
192 	//const double k_r = 0.2126; //
193 	const double k_b = 0.0593; //ITU-R BT.2020 conversion
194 	const double k_r = 0.2627; //
195 	const double k_g = 1 - k_b - k_r;
196 
197 	const double scale_b = 0.5 / (1 - k_b);
198 	const double scale_r = 0.5 / (1 - k_r);
199 
200 	const double y   = k_r * r_diff + k_g * g_diff + k_b * b_diff; //[!], analog YCbCr!
201 	const double c_b = scale_b * (b_diff - y);
202 	const double c_r = scale_r * (r_diff - y);
203 
204 	//we skip division by 255 to have similar range like other distance functions
205 	return std::sqrt(square(lumaWeight * y) + square(c_b) + square(c_r));
206 }
207 
208 
209 struct DistYCbCrBuffer //30% perf boost compared to distYCbCr()!
210 {
211 public:
dist__anon189d792b0111::DistYCbCrBuffer212 	static double dist(uint32_t pix1, uint32_t pix2)
213 	{
214 #if defined _MSC_VER && _MSC_VER < 1900
215 #error function scope static initialization is not yet thread-safe!
216 #endif
217 		static const DistYCbCrBuffer inst;
218 		return inst.distImpl(pix1, pix2);
219 	}
220 
221 private:
DistYCbCrBuffer__anon189d792b0111::DistYCbCrBuffer222 	DistYCbCrBuffer() : buffer(256 * 256 * 256)
223 	{
224 		for (uint32_t i = 0; i < 256 * 256 * 256; ++i) //startup time: 114 ms on Intel Core i5 (four cores)
225 		{
226 			const int r_diff = getByte<2>(i) * 2 - 255;
227 			const int g_diff = getByte<1>(i) * 2 - 255;
228 			const int b_diff = getByte<0>(i) * 2 - 255;
229 
230 			const double k_b = 0.0593; //ITU-R BT.2020 conversion
231 			const double k_r = 0.2627; //
232 			const double k_g = 1 - k_b - k_r;
233 
234 			const double scale_b = 0.5 / (1 - k_b);
235 			const double scale_r = 0.5 / (1 - k_r);
236 
237 			const double y   = k_r * r_diff + k_g * g_diff + k_b * b_diff; //[!], analog YCbCr!
238 			const double c_b = scale_b * (b_diff - y);
239 			const double c_r = scale_r * (r_diff - y);
240 
241 			buffer[i] = static_cast<float>(std::sqrt(square(y) + square(c_b) + square(c_r)));
242 		}
243 	}
244 
distImpl__anon189d792b0111::DistYCbCrBuffer245 	double distImpl(uint32_t pix1, uint32_t pix2) const
246 	{
247 		//if (pix1 == pix2) -> 8% perf degradation!
248 		//	return 0;
249 		//if (pix1 > pix2)
250 		//	  std::swap(pix1, pix2); -> 30% perf degradation!!!
251 
252 		const int r_diff = static_cast<int>(getRed  (pix1)) - getRed  (pix2);
253 		const int g_diff = static_cast<int>(getGreen(pix1)) - getGreen(pix2);
254 		const int b_diff = static_cast<int>(getBlue (pix1)) - getBlue (pix2);
255 
256 		return buffer[(((r_diff + 255) / 2) << 16) | //slightly reduce precision (division by 2) to squeeze value into single byte
257 					  (((g_diff + 255) / 2) <<  8) |
258 					  (( b_diff + 255) / 2)];
259 	}
260 
261 	std::vector<float> buffer; //consumes 64 MB memory; using double is only 2% faster, but takes 128 MB
262 };
263 
264 
265 enum BlendType
266 {
267 	BLEND_NONE = 0,
268 	BLEND_NORMAL,   //a normal indication to blend
269 	BLEND_DOMINANT, //a strong indication to blend
270 	//attention: BlendType must fit into the value range of 2 bit!!!
271 };
272 
273 struct BlendResult
274 {
275 	BlendType
276 	/**/blend_f, blend_g,
277 	/**/blend_j, blend_k;
278 };
279 
280 
281 struct Kernel_4x4 //kernel for preprocessing step
282 {
283 	uint32_t
284 	/**/a, b, c, d,
285 	/**/e, f, g, h,
286 	/**/i, j, k, l,
287 	/**/m, n, o, p;
288 };
289 
290 /*
291 input kernel area naming convention:
292 -----------------
293 | A | B | C | D |
294 ----|---|---|---|
295 | E | F | G | H |   //evaluate the four corners between F, G, J, K
296 ----|---|---|---|   //input pixel is at position F
297 | I | J | K | L |
298 ----|---|---|---|
299 | M | N | O | P |
300 -----------------
301 */
302 template <class ColorDistance>
303 FORCE_INLINE //detect blend direction
preProcessCorners(const Kernel_4x4 & ker,const xbrz::ScalerCfg & cfg)304 BlendResult preProcessCorners(const Kernel_4x4& ker, const xbrz::ScalerCfg& cfg) //result: F, G, J, K corners of "GradientType"
305 {
306 	BlendResult result = {};
307 
308 	if ((ker.f == ker.g &&
309 		 ker.j == ker.k) ||
310 		(ker.f == ker.j &&
311 		 ker.g == ker.k))
312 		return result;
313 
314 	auto dist = [&](uint32_t pix1, uint32_t pix2) { return ColorDistance::dist(pix1, pix2, cfg.luminanceWeight); };
315 
316 	const int weight = 4;
317 	double jg = dist(ker.i, ker.f) + dist(ker.f, ker.c) + dist(ker.n, ker.k) + dist(ker.k, ker.h) + weight * dist(ker.j, ker.g);
318 	double fk = dist(ker.e, ker.j) + dist(ker.j, ker.o) + dist(ker.b, ker.g) + dist(ker.g, ker.l) + weight * dist(ker.f, ker.k);
319 
320 	if (jg < fk) //test sample: 70% of values max(jg, fk) / min(jg, fk) are between 1.1 and 3.7 with median being 1.8
321 	{
322 		const bool dominantGradient = cfg.dominantDirectionThreshold * jg < fk;
323 		if (ker.f != ker.g && ker.f != ker.j)
324 			result.blend_f = dominantGradient ? BLEND_DOMINANT : BLEND_NORMAL;
325 
326 		if (ker.k != ker.j && ker.k != ker.g)
327 			result.blend_k = dominantGradient ? BLEND_DOMINANT : BLEND_NORMAL;
328 	}
329 	else if (fk < jg)
330 	{
331 		const bool dominantGradient = cfg.dominantDirectionThreshold * fk < jg;
332 		if (ker.j != ker.f && ker.j != ker.k)
333 			result.blend_j = dominantGradient ? BLEND_DOMINANT : BLEND_NORMAL;
334 
335 		if (ker.g != ker.f && ker.g != ker.k)
336 			result.blend_g = dominantGradient ? BLEND_DOMINANT : BLEND_NORMAL;
337 	}
338 	return result;
339 }
340 
341 struct Kernel_3x3
342 {
343 	uint32_t
344 	/**/a,  b,  c,
345 	/**/d,  e,  f,
346 	/**/g,  h,  i;
347 };
348 
349 #define DEF_GETTER(x) template <RotationDegree rotDeg> uint32_t inline get_##x(const Kernel_3x3& ker) { return ker.x; }
350 //we cannot and NEED NOT write "ker.##x" since ## concatenates preprocessor tokens but "." is not a token
DEF_GETTER(b)351 DEF_GETTER(a) DEF_GETTER(b) DEF_GETTER(c)
352 DEF_GETTER(d) DEF_GETTER(e) DEF_GETTER(f)
353 DEF_GETTER(g) DEF_GETTER(h) DEF_GETTER(i)
354 #undef DEF_GETTER
355 
356 #define DEF_GETTER(x, y) template <> inline uint32_t get_##x<ROT_90>(const Kernel_3x3& ker) { return ker.y; }
357 DEF_GETTER(a, g) DEF_GETTER(b, d) DEF_GETTER(c, a)
358 DEF_GETTER(d, h) DEF_GETTER(e, e) DEF_GETTER(f, b)
359 DEF_GETTER(g, i) DEF_GETTER(h, f) DEF_GETTER(i, c)
360 #undef DEF_GETTER
361 
362 #define DEF_GETTER(x, y) template <> inline uint32_t get_##x<ROT_180>(const Kernel_3x3& ker) { return ker.y; }
363 DEF_GETTER(a, i) DEF_GETTER(b, h) DEF_GETTER(c, g)
364 DEF_GETTER(d, f) DEF_GETTER(e, e) DEF_GETTER(f, d)
365 DEF_GETTER(g, c) DEF_GETTER(h, b) DEF_GETTER(i, a)
366 #undef DEF_GETTER
367 
368 #define DEF_GETTER(x, y) template <> inline uint32_t get_##x<ROT_270>(const Kernel_3x3& ker) { return ker.y; }
369 DEF_GETTER(a, c) DEF_GETTER(b, f) DEF_GETTER(c, i)
370 DEF_GETTER(d, b) DEF_GETTER(e, e) DEF_GETTER(f, h)
371 DEF_GETTER(g, a) DEF_GETTER(h, d) DEF_GETTER(i,	g)
372 #undef DEF_GETTER
373 
374 
375 //compress four blend types into a single byte
376 inline BlendType getTopL   (unsigned char b) { return static_cast<BlendType>(0x3 & b); }
getTopR(unsigned char b)377 inline BlendType getTopR   (unsigned char b) { return static_cast<BlendType>(0x3 & (b >> 2)); }
getBottomR(unsigned char b)378 inline BlendType getBottomR(unsigned char b) { return static_cast<BlendType>(0x3 & (b >> 4)); }
getBottomL(unsigned char b)379 inline BlendType getBottomL(unsigned char b) { return static_cast<BlendType>(0x3 & (b >> 6)); }
380 
setTopL(unsigned char & b,BlendType bt)381 inline void setTopL   (unsigned char& b, BlendType bt) { b |= bt; } //buffer is assumed to be initialized before preprocessing!
setTopR(unsigned char & b,BlendType bt)382 inline void setTopR   (unsigned char& b, BlendType bt) { b |= (bt << 2); }
setBottomR(unsigned char & b,BlendType bt)383 inline void setBottomR(unsigned char& b, BlendType bt) { b |= (bt << 4); }
setBottomL(unsigned char & b,BlendType bt)384 inline void setBottomL(unsigned char& b, BlendType bt) { b |= (bt << 6); }
385 
blendingNeeded(unsigned char b)386 inline bool blendingNeeded(unsigned char b) { return b != 0; }
387 
388 template <RotationDegree rotDeg> inline
rotateBlendInfo(unsigned char b)389 unsigned char rotateBlendInfo(unsigned char b) { return b; }
rotateBlendInfo(unsigned char b)390 template <> inline unsigned char rotateBlendInfo<ROT_90 >(unsigned char b) { return ((b << 2) | (b >> 6)) & 0xff; }
rotateBlendInfo(unsigned char b)391 template <> inline unsigned char rotateBlendInfo<ROT_180>(unsigned char b) { return ((b << 4) | (b >> 4)) & 0xff; }
rotateBlendInfo(unsigned char b)392 template <> inline unsigned char rotateBlendInfo<ROT_270>(unsigned char b) { return ((b << 6) | (b >> 2)) & 0xff; }
393 
394 
395 #ifdef _DEBUG
396 int debugPixelX = -1;
397 int debugPixelY = 84;
398 bool breakIntoDebugger = false;
399 #endif
400 
401 
402 /*
403 input kernel area naming convention:
404 -------------
405 | A | B | C |
406 ----|---|---|
407 | D | E | F | //input pixel is at position E
408 ----|---|---|
409 | G | H | I |
410 -------------
411 */
412 template <class Scaler, class ColorDistance, RotationDegree rotDeg>
413 FORCE_INLINE //perf: quite worth it!
blendPixel(const Kernel_3x3 & ker,uint32_t * target,int trgWidth,unsigned char blendInfo,const xbrz::ScalerCfg & cfg)414 void blendPixel(const Kernel_3x3& ker,
415 				uint32_t* target, int trgWidth,
416 				unsigned char blendInfo, //result of preprocessing all four corners of pixel "e"
417 				const xbrz::ScalerCfg& cfg)
418 {
419 #define a get_a<rotDeg>(ker)
420 #define b get_b<rotDeg>(ker)
421 #define c get_c<rotDeg>(ker)
422 #define d get_d<rotDeg>(ker)
423 #define e get_e<rotDeg>(ker)
424 #define f get_f<rotDeg>(ker)
425 #define g get_g<rotDeg>(ker)
426 #define h get_h<rotDeg>(ker)
427 #define i get_i<rotDeg>(ker)
428 
429 #if defined(_DEBUG) && defined(_WIN32)
430 	if (breakIntoDebugger)
431 		__debugbreak(); //__asm int 3;
432 #endif
433 
434 	const unsigned char blend = rotateBlendInfo<rotDeg>(blendInfo);
435 
436 	if (getBottomR(blend) >= BLEND_NORMAL)
437 	{
438 		auto eq   = [&](uint32_t pix1, uint32_t pix2) { return ColorDistance::dist(pix1, pix2, cfg.luminanceWeight) < cfg.equalColorTolerance; };
439 		auto dist = [&](uint32_t pix1, uint32_t pix2) { return ColorDistance::dist(pix1, pix2, cfg.luminanceWeight); };
440 
441 		const bool doLineBlend = [&]() -> bool
442 		{
443 			if (getBottomR(blend) >= BLEND_DOMINANT)
444 				return true;
445 
446 			//make sure there is no second blending in an adjacent rotation for this pixel: handles insular pixels, mario eyes
447 			if (getTopR(blend) != BLEND_NONE && !eq(e, g)) //but support double-blending for 90?corners
448 				return false;
449 			if (getBottomL(blend) != BLEND_NONE && !eq(e, c))
450 				return false;
451 
452 			//no full blending for L-shapes; blend corner only (handles "mario mushroom eyes")
453 			if (!eq(e, i) && eq(g, h) && eq(h , i) && eq(i, f) && eq(f, c))
454 				return false;
455 
456 			return true;
457 		}();
458 
459 		const uint32_t px = dist(e, f) <= dist(e, h) ? f : h; //choose most similar color
460 
461 		OutputMatrix<Scaler::scale, rotDeg> out(target, trgWidth);
462 
463 		if (doLineBlend)
464 		{
465 			const double fg = dist(f, g); //test sample: 70% of values max(fg, hc) / min(fg, hc) are between 1.1 and 3.7 with median being 1.9
466 			const double hc = dist(h, c); //
467 
468 			const bool haveShallowLine = cfg.steepDirectionThreshold * fg <= hc && e != g && d != g;
469 			const bool haveSteepLine   = cfg.steepDirectionThreshold * hc <= fg && e != c && b != c;
470 
471 			if (haveShallowLine)
472 			{
473 				if (haveSteepLine)
474 					Scaler::blendLineSteepAndShallow(px, out);
475 				else
476 					Scaler::blendLineShallow(px, out);
477 			}
478 			else
479 			{
480 				if (haveSteepLine)
481 					Scaler::blendLineSteep(px, out);
482 				else
483 					Scaler::blendLineDiagonal(px,out);
484 			}
485 		}
486 		else
487 			Scaler::blendCorner(px, out);
488 	}
489 
490 #undef a
491 #undef b
492 #undef c
493 #undef d
494 #undef e
495 #undef f
496 #undef g
497 #undef h
498 #undef i
499 }
500 
501 
502 template <class Scaler, class ColorDistance> //scaler policy: see "Scaler2x" reference implementation
scaleImage(const uint32_t * src,uint32_t * trg,int srcWidth,int srcHeight,const xbrz::ScalerCfg & cfg,int yFirst,int yLast)503 void scaleImage(const uint32_t* src, uint32_t* trg, int srcWidth, int srcHeight, const xbrz::ScalerCfg& cfg, int yFirst, int yLast)
504 {
505 	yFirst = std::max(yFirst, 0);
506 	yLast  = std::min(yLast, srcHeight);
507 	if (yFirst >= yLast || srcWidth <= 0)
508 		return;
509 
510 	const int trgWidth = srcWidth * Scaler::scale;
511 
512 	//"use" space at the end of the image as temporary buffer for "on the fly preprocessing": we even could use larger area of
513 	//"sizeof(uint32_t) * srcWidth * (yLast - yFirst)" bytes without risk of accidental overwriting before accessing
514 	const int bufferSize = srcWidth;
515 	unsigned char* preProcBuffer = reinterpret_cast<unsigned char*>(trg + yLast * Scaler::scale * trgWidth) - bufferSize;
516 	std::fill(preProcBuffer, preProcBuffer + bufferSize, 0);
517 	static_assert(BLEND_NONE == 0, "");
518 
519 	//initialize preprocessing buffer for first row of current stripe: detect upper left and right corner blending
520 	//this cannot be optimized for adjacent processing stripes; we must not allow for a memory race condition!
521 	if (yFirst > 0)
522 	{
523 		const int y = yFirst - 1;
524 
525 		const uint32_t* s_m1 = src + srcWidth * std::max(y - 1, 0);
526 		const uint32_t* s_0  = src + srcWidth * y; //center line
527 		const uint32_t* s_p1 = src + srcWidth * std::min(y + 1, srcHeight - 1);
528 		const uint32_t* s_p2 = src + srcWidth * std::min(y + 2, srcHeight - 1);
529 
530 		for (int x = 0; x < srcWidth; ++x)
531 		{
532 			const int x_m1 = std::max(x - 1, 0);
533 			const int x_p1 = std::min(x + 1, srcWidth - 1);
534 			const int x_p2 = std::min(x + 2, srcWidth - 1);
535 
536 			Kernel_4x4 ker = {}; //perf: initialization is negligible
537 			ker.a = s_m1[x_m1]; //read sequentially from memory as far as possible
538 			ker.b = s_m1[x];
539 			ker.c = s_m1[x_p1];
540 			ker.d = s_m1[x_p2];
541 
542 			ker.e = s_0[x_m1];
543 			ker.f = s_0[x];
544 			ker.g = s_0[x_p1];
545 			ker.h = s_0[x_p2];
546 
547 			ker.i = s_p1[x_m1];
548 			ker.j = s_p1[x];
549 			ker.k = s_p1[x_p1];
550 			ker.l = s_p1[x_p2];
551 
552 			ker.m = s_p2[x_m1];
553 			ker.n = s_p2[x];
554 			ker.o = s_p2[x_p1];
555 			ker.p = s_p2[x_p2];
556 
557 			const BlendResult res = preProcessCorners<ColorDistance>(ker, cfg);
558 			/*
559 			preprocessing blend result:
560 			---------
561 			| F | G |   //evalute corner between F, G, J, K
562 			----|---|   //input pixel is at position F
563 			| J | K |
564 			---------
565 			*/
566 			setTopR(preProcBuffer[x], res.blend_j);
567 
568 			if (x + 1 < bufferSize)
569 				setTopL(preProcBuffer[x + 1], res.blend_k);
570 		}
571 	}
572 	//------------------------------------------------------------------------------------
573 
574 	for (int y = yFirst; y < yLast; ++y)
575 	{
576 		uint32_t* out = trg + Scaler::scale * y * trgWidth; //consider MT "striped" access
577 
578 		const uint32_t* s_m1 = src + srcWidth * std::max(y - 1, 0);
579 		const uint32_t* s_0  = src + srcWidth * y; //center line
580 		const uint32_t* s_p1 = src + srcWidth * std::min(y + 1, srcHeight - 1);
581 		const uint32_t* s_p2 = src + srcWidth * std::min(y + 2, srcHeight - 1);
582 
583 		unsigned char blend_xy1 = 0; //corner blending for current (x, y + 1) position
584 
585 		for (int x = 0; x < srcWidth; ++x, out += Scaler::scale)
586 		{
587 #ifdef _DEBUG
588 			breakIntoDebugger = debugPixelX == x && debugPixelY == y;
589 #endif
590 			//all those bounds checks have only insignificant impact on performance!
591 			const int x_m1 = std::max(x - 1, 0); //perf: prefer array indexing to additional pointers!
592 			const int x_p1 = std::min(x + 1, srcWidth - 1);
593 			const int x_p2 = std::min(x + 2, srcWidth - 1);
594 
595 			Kernel_4x4 ker4 = {}; //perf: initialization is negligible
596 
597 			ker4.a = s_m1[x_m1]; //read sequentially from memory as far as possible
598 			ker4.b = s_m1[x];
599 			ker4.c = s_m1[x_p1];
600 			ker4.d = s_m1[x_p2];
601 
602 			ker4.e = s_0[x_m1];
603 			ker4.f = s_0[x];
604 			ker4.g = s_0[x_p1];
605 			ker4.h = s_0[x_p2];
606 
607 			ker4.i = s_p1[x_m1];
608 			ker4.j = s_p1[x];
609 			ker4.k = s_p1[x_p1];
610 			ker4.l = s_p1[x_p2];
611 
612 			ker4.m = s_p2[x_m1];
613 			ker4.n = s_p2[x];
614 			ker4.o = s_p2[x_p1];
615 			ker4.p = s_p2[x_p2];
616 
617 			//evaluate the four corners on bottom-right of current pixel
618 			unsigned char blend_xy = 0; //for current (x, y) position
619 			{
620 				const BlendResult res = preProcessCorners<ColorDistance>(ker4, cfg);
621 				/*
622 				preprocessing blend result:
623 				---------
624 				| F | G |   //evalute corner between F, G, J, K
625 				----|---|   //current input pixel is at position F
626 				| J | K |
627 				---------
628 				*/
629 				blend_xy = preProcBuffer[x];
630 				setBottomR(blend_xy, res.blend_f); //all four corners of (x, y) have been determined at this point due to processing sequence!
631 
632 				setTopR(blend_xy1, res.blend_j); //set 2nd known corner for (x, y + 1)
633 				preProcBuffer[x] = blend_xy1; //store on current buffer position for use on next row
634 
635 				blend_xy1 = 0;
636 				setTopL(blend_xy1, res.blend_k); //set 1st known corner for (x + 1, y + 1) and buffer for use on next column
637 
638 				if (x + 1 < bufferSize) //set 3rd known corner for (x + 1, y)
639 					setBottomL(preProcBuffer[x + 1], res.blend_g);
640 			}
641 
642 			//fill block of size scale * scale with the given color
643 			fillBlock(out, trgWidth * sizeof(uint32_t), ker4.f, Scaler::scale); //place *after* preprocessing step, to not overwrite the results while processing the the last pixel!
644 
645 			//blend four corners of current pixel
646 			if (blendingNeeded(blend_xy)) //good 5% perf-improvement
647 			{
648 				Kernel_3x3 ker3 = {}; //perf: initialization is negligible
649 
650 				ker3.a = ker4.a;
651 				ker3.b = ker4.b;
652 				ker3.c = ker4.c;
653 
654 				ker3.d = ker4.e;
655 				ker3.e = ker4.f;
656 				ker3.f = ker4.g;
657 
658 				ker3.g = ker4.i;
659 				ker3.h = ker4.j;
660 				ker3.i = ker4.k;
661 
662 				blendPixel<Scaler, ColorDistance, ROT_0  >(ker3, out, trgWidth, blend_xy, cfg);
663 				blendPixel<Scaler, ColorDistance, ROT_90 >(ker3, out, trgWidth, blend_xy, cfg);
664 				blendPixel<Scaler, ColorDistance, ROT_180>(ker3, out, trgWidth, blend_xy, cfg);
665 				blendPixel<Scaler, ColorDistance, ROT_270>(ker3, out, trgWidth, blend_xy, cfg);
666 			}
667 		}
668 	}
669 }
670 
671 //------------------------------------------------------------------------------------
672 
673 template <class ColorGradient>
674 struct Scaler2x : public ColorGradient
675 {
676 	static const int scale = 2;
677 
678 	template <unsigned int M, unsigned int N> //bring template function into scope for GCC
alphaGrad__anon189d792b0111::Scaler2x679 	static void alphaGrad(uint32_t& pixBack, uint32_t pixFront) { ColorGradient::template alphaGrad<M, N>(pixBack, pixFront); }
680 
681 
682 	template <class OutputMatrix>
blendLineShallow__anon189d792b0111::Scaler2x683 	static void blendLineShallow(uint32_t col, OutputMatrix& out)
684 	{
685 		alphaGrad<1, 4>(out.template ref<scale - 1, 0>(), col);
686 		alphaGrad<3, 4>(out.template ref<scale - 1, 1>(), col);
687 	}
688 
689 	template <class OutputMatrix>
blendLineSteep__anon189d792b0111::Scaler2x690 	static void blendLineSteep(uint32_t col, OutputMatrix& out)
691 	{
692 		alphaGrad<1, 4>(out.template ref<0, scale - 1>(), col);
693 		alphaGrad<3, 4>(out.template ref<1, scale - 1>(), col);
694 	}
695 
696 	template <class OutputMatrix>
blendLineSteepAndShallow__anon189d792b0111::Scaler2x697 	static void blendLineSteepAndShallow(uint32_t col, OutputMatrix& out)
698 	{
699 		alphaGrad<1, 4>(out.template ref<1, 0>(), col);
700 		alphaGrad<1, 4>(out.template ref<0, 1>(), col);
701 		alphaGrad<5, 6>(out.template ref<1, 1>(), col); //[!] fixes 7/8 used in xBR
702 	}
703 
704 	template <class OutputMatrix>
blendLineDiagonal__anon189d792b0111::Scaler2x705 	static void blendLineDiagonal(uint32_t col, OutputMatrix& out)
706 	{
707 		alphaGrad<1, 2>(out.template ref<1, 1>(), col);
708 	}
709 
710 	template <class OutputMatrix>
blendCorner__anon189d792b0111::Scaler2x711 	static void blendCorner(uint32_t col, OutputMatrix& out)
712 	{
713 		//model a round corner
714 		alphaGrad<21, 100>(out.template ref<1, 1>(), col); //exact: 1 - pi/4 = 0.2146018366
715 	}
716 };
717 
718 
719 template <class ColorGradient>
720 struct Scaler3x : public ColorGradient
721 {
722 	static const int scale = 3;
723 
724 	template <unsigned int M, unsigned int N> //bring template function into scope for GCC
alphaGrad__anon189d792b0111::Scaler3x725 	static void alphaGrad(uint32_t& pixBack, uint32_t pixFront) { ColorGradient::template alphaGrad<M, N>(pixBack, pixFront); }
726 
727 
728 	template <class OutputMatrix>
blendLineShallow__anon189d792b0111::Scaler3x729 	static void blendLineShallow(uint32_t col, OutputMatrix& out)
730 	{
731 		alphaGrad<1, 4>(out.template ref<scale - 1, 0>(), col);
732 		alphaGrad<1, 4>(out.template ref<scale - 2, 2>(), col);
733 
734 		alphaGrad<3, 4>(out.template ref<scale - 1, 1>(), col);
735 		out.template ref<scale - 1, 2>() = col;
736 	}
737 
738 	template <class OutputMatrix>
blendLineSteep__anon189d792b0111::Scaler3x739 	static void blendLineSteep(uint32_t col, OutputMatrix& out)
740 	{
741 		alphaGrad<1, 4>(out.template ref<0, scale - 1>(), col);
742 		alphaGrad<1, 4>(out.template ref<2, scale - 2>(), col);
743 
744 		alphaGrad<3, 4>(out.template ref<1, scale - 1>(), col);
745 		out.template ref<2, scale - 1>() = col;
746 	}
747 
748 	template <class OutputMatrix>
blendLineSteepAndShallow__anon189d792b0111::Scaler3x749 	static void blendLineSteepAndShallow(uint32_t col, OutputMatrix& out)
750 	{
751 		alphaGrad<1, 4>(out.template ref<2, 0>(), col);
752 		alphaGrad<1, 4>(out.template ref<0, 2>(), col);
753 		alphaGrad<3, 4>(out.template ref<2, 1>(), col);
754 		alphaGrad<3, 4>(out.template ref<1, 2>(), col);
755 		out.template ref<2, 2>() = col;
756 	}
757 
758 	template <class OutputMatrix>
blendLineDiagonal__anon189d792b0111::Scaler3x759 	static void blendLineDiagonal(uint32_t col, OutputMatrix& out)
760 	{
761 		alphaGrad<1, 8>(out.template ref<1, 2>(), col); //conflict with other rotations for this odd scale
762 		alphaGrad<1, 8>(out.template ref<2, 1>(), col);
763 		alphaGrad<7, 8>(out.template ref<2, 2>(), col); //
764 	}
765 
766 	template <class OutputMatrix>
blendCorner__anon189d792b0111::Scaler3x767 	static void blendCorner(uint32_t col, OutputMatrix& out)
768 	{
769 		//model a round corner
770 		alphaGrad<45, 100>(out.template ref<2, 2>(), col); //exact: 0.4545939598
771 		//alphaGrad<7, 256>(out.template ref<2, 1>(), col); //0.02826017254 -> negligible + avoid conflicts with other rotations for this odd scale
772 		//alphaGrad<7, 256>(out.template ref<1, 2>(), col); //0.02826017254
773 	}
774 };
775 
776 
777 template <class ColorGradient>
778 struct Scaler4x : public ColorGradient
779 {
780 	static const int scale = 4;
781 
782 	template <unsigned int M, unsigned int N> //bring template function into scope for GCC
alphaGrad__anon189d792b0111::Scaler4x783 	static void alphaGrad(uint32_t& pixBack, uint32_t pixFront) { ColorGradient::template alphaGrad<M, N>(pixBack, pixFront); }
784 
785 
786 	template <class OutputMatrix>
blendLineShallow__anon189d792b0111::Scaler4x787 	static void blendLineShallow(uint32_t col, OutputMatrix& out)
788 	{
789 		alphaGrad<1, 4>(out.template ref<scale - 1, 0>(), col);
790 		alphaGrad<1, 4>(out.template ref<scale - 2, 2>(), col);
791 
792 		alphaGrad<3, 4>(out.template ref<scale - 1, 1>(), col);
793 		alphaGrad<3, 4>(out.template ref<scale - 2, 3>(), col);
794 
795 		out.template ref<scale - 1, 2>() = col;
796 		out.template ref<scale - 1, 3>() = col;
797 	}
798 
799 	template <class OutputMatrix>
blendLineSteep__anon189d792b0111::Scaler4x800 	static void blendLineSteep(uint32_t col, OutputMatrix& out)
801 	{
802 		alphaGrad<1, 4>(out.template ref<0, scale - 1>(), col);
803 		alphaGrad<1, 4>(out.template ref<2, scale - 2>(), col);
804 
805 		alphaGrad<3, 4>(out.template ref<1, scale - 1>(), col);
806 		alphaGrad<3, 4>(out.template ref<3, scale - 2>(), col);
807 
808 		out.template ref<2, scale - 1>() = col;
809 		out.template ref<3, scale - 1>() = col;
810 	}
811 
812 	template <class OutputMatrix>
blendLineSteepAndShallow__anon189d792b0111::Scaler4x813 	static void blendLineSteepAndShallow(uint32_t col, OutputMatrix& out)
814 	{
815 		alphaGrad<3, 4>(out.template ref<3, 1>(), col);
816 		alphaGrad<3, 4>(out.template ref<1, 3>(), col);
817 		alphaGrad<1, 4>(out.template ref<3, 0>(), col);
818 		alphaGrad<1, 4>(out.template ref<0, 3>(), col);
819 
820 		alphaGrad<1, 3>(out.template ref<2, 2>(), col); //[!] fixes 1/4 used in xBR
821 
822 		out.template ref<3, 3>() = col;
823 		out.template ref<3, 2>() = col;
824 		out.template ref<2, 3>() = col;
825 	}
826 
827 	template <class OutputMatrix>
blendLineDiagonal__anon189d792b0111::Scaler4x828 	static void blendLineDiagonal(uint32_t col, OutputMatrix& out)
829 	{
830 		alphaGrad<1, 2>(out.template ref<scale - 1, scale / 2    >(), col);
831 		alphaGrad<1, 2>(out.template ref<scale - 2, scale / 2 + 1>(), col);
832 		out.template ref<scale - 1, scale - 1>() = col;
833 	}
834 
835 	template <class OutputMatrix>
blendCorner__anon189d792b0111::Scaler4x836 	static void blendCorner(uint32_t col, OutputMatrix& out)
837 	{
838 		//model a round corner
839 		alphaGrad<68, 100>(out.template ref<3, 3>(), col); //exact: 0.6848532563
840 		alphaGrad< 9, 100>(out.template ref<3, 2>(), col); //0.08677704501
841 		alphaGrad< 9, 100>(out.template ref<2, 3>(), col); //0.08677704501
842 	}
843 };
844 
845 
846 template <class ColorGradient>
847 struct Scaler5x : public ColorGradient
848 {
849 	static const int scale = 5;
850 
851 	template <unsigned int M, unsigned int N> //bring template function into scope for GCC
alphaGrad__anon189d792b0111::Scaler5x852 	static void alphaGrad(uint32_t& pixBack, uint32_t pixFront) { ColorGradient::template alphaGrad<M, N>(pixBack, pixFront); }
853 
854 
855 	template <class OutputMatrix>
blendLineShallow__anon189d792b0111::Scaler5x856 	static void blendLineShallow(uint32_t col, OutputMatrix& out)
857 	{
858 		alphaGrad<1, 4>(out.template ref<scale - 1, 0>(), col);
859 		alphaGrad<1, 4>(out.template ref<scale - 2, 2>(), col);
860 		alphaGrad<1, 4>(out.template ref<scale - 3, 4>(), col);
861 
862 		alphaGrad<3, 4>(out.template ref<scale - 1, 1>(), col);
863 		alphaGrad<3, 4>(out.template ref<scale - 2, 3>(), col);
864 
865 		out.template ref<scale - 1, 2>() = col;
866 		out.template ref<scale - 1, 3>() = col;
867 		out.template ref<scale - 1, 4>() = col;
868 		out.template ref<scale - 2, 4>() = col;
869 	}
870 
871 	template <class OutputMatrix>
blendLineSteep__anon189d792b0111::Scaler5x872 	static void blendLineSteep(uint32_t col, OutputMatrix& out)
873 	{
874 		alphaGrad<1, 4>(out.template ref<0, scale - 1>(), col);
875 		alphaGrad<1, 4>(out.template ref<2, scale - 2>(), col);
876 		alphaGrad<1, 4>(out.template ref<4, scale - 3>(), col);
877 
878 		alphaGrad<3, 4>(out.template ref<1, scale - 1>(), col);
879 		alphaGrad<3, 4>(out.template ref<3, scale - 2>(), col);
880 
881 		out.template ref<2, scale - 1>() = col;
882 		out.template ref<3, scale - 1>() = col;
883 		out.template ref<4, scale - 1>() = col;
884 		out.template ref<4, scale - 2>() = col;
885 	}
886 
887 	template <class OutputMatrix>
blendLineSteepAndShallow__anon189d792b0111::Scaler5x888 	static void blendLineSteepAndShallow(uint32_t col, OutputMatrix& out)
889 	{
890 		alphaGrad<1, 4>(out.template ref<0, scale - 1>(), col);
891 		alphaGrad<1, 4>(out.template ref<2, scale - 2>(), col);
892 		alphaGrad<3, 4>(out.template ref<1, scale - 1>(), col);
893 
894 		alphaGrad<1, 4>(out.template ref<scale - 1, 0>(), col);
895 		alphaGrad<1, 4>(out.template ref<scale - 2, 2>(), col);
896 		alphaGrad<3, 4>(out.template ref<scale - 1, 1>(), col);
897 
898 		alphaGrad<2, 3>(out.template ref<3, 3>(), col);
899 
900 		out.template ref<2, scale - 1>() = col;
901 		out.template ref<3, scale - 1>() = col;
902 		out.template ref<4, scale - 1>() = col;
903 
904 		out.template ref<scale - 1, 2>() = col;
905 		out.template ref<scale - 1, 3>() = col;
906 	}
907 
908 	template <class OutputMatrix>
blendLineDiagonal__anon189d792b0111::Scaler5x909 	static void blendLineDiagonal(uint32_t col, OutputMatrix& out)
910 	{
911 		alphaGrad<1, 8>(out.template ref<scale - 1, scale / 2    >(), col); //conflict with other rotations for this odd scale
912 		alphaGrad<1, 8>(out.template ref<scale - 2, scale / 2 + 1>(), col);
913 		alphaGrad<1, 8>(out.template ref<scale - 3, scale / 2 + 2>(), col); //
914 
915 		alphaGrad<7, 8>(out.template ref<4, 3>(), col);
916 		alphaGrad<7, 8>(out.template ref<3, 4>(), col);
917 
918 		out.template ref<4, 4>() = col;
919 	}
920 
921 	template <class OutputMatrix>
blendCorner__anon189d792b0111::Scaler5x922 	static void blendCorner(uint32_t col, OutputMatrix& out)
923 	{
924 		//model a round corner
925 		alphaGrad<86, 100>(out.template ref<4, 4>(), col); //exact: 0.8631434088
926 		alphaGrad<23, 100>(out.template ref<4, 3>(), col); //0.2306749731
927 		alphaGrad<23, 100>(out.template ref<3, 4>(), col); //0.2306749731
928 		//alphaGrad<1, 64>(out.template ref<4, 2>(), col); //0.01676812367 -> negligible + avoid conflicts with other rotations for this odd scale
929 		//alphaGrad<1, 64>(out.template ref<2, 4>(), col); //0.01676812367
930 	}
931 };
932 
933 
934 template <class ColorGradient>
935 struct Scaler6x : public ColorGradient
936 {
937 	static const int scale = 6;
938 
939 	template <unsigned int M, unsigned int N> //bring template function into scope for GCC
alphaGrad__anon189d792b0111::Scaler6x940 	static void alphaGrad(uint32_t& pixBack, uint32_t pixFront) { ColorGradient::template alphaGrad<M, N>(pixBack, pixFront); }
941 
942 
943 	template <class OutputMatrix>
blendLineShallow__anon189d792b0111::Scaler6x944 	static void blendLineShallow(uint32_t col, OutputMatrix& out)
945 	{
946 		alphaGrad<1, 4>(out.template ref<scale - 1, 0>(), col);
947 		alphaGrad<1, 4>(out.template ref<scale - 2, 2>(), col);
948 		alphaGrad<1, 4>(out.template ref<scale - 3, 4>(), col);
949 
950 		alphaGrad<3, 4>(out.template ref<scale - 1, 1>(), col);
951 		alphaGrad<3, 4>(out.template ref<scale - 2, 3>(), col);
952 		alphaGrad<3, 4>(out.template ref<scale - 3, 5>(), col);
953 
954 		out.template ref<scale - 1, 2>() = col;
955 		out.template ref<scale - 1, 3>() = col;
956 		out.template ref<scale - 1, 4>() = col;
957 		out.template ref<scale - 1, 5>() = col;
958 
959 		out.template ref<scale - 2, 4>() = col;
960 		out.template ref<scale - 2, 5>() = col;
961 	}
962 
963 	template <class OutputMatrix>
blendLineSteep__anon189d792b0111::Scaler6x964 	static void blendLineSteep(uint32_t col, OutputMatrix& out)
965 	{
966 		alphaGrad<1, 4>(out.template ref<0, scale - 1>(), col);
967 		alphaGrad<1, 4>(out.template ref<2, scale - 2>(), col);
968 		alphaGrad<1, 4>(out.template ref<4, scale - 3>(), col);
969 
970 		alphaGrad<3, 4>(out.template ref<1, scale - 1>(), col);
971 		alphaGrad<3, 4>(out.template ref<3, scale - 2>(), col);
972 		alphaGrad<3, 4>(out.template ref<5, scale - 3>(), col);
973 
974 		out.template ref<2, scale - 1>() = col;
975 		out.template ref<3, scale - 1>() = col;
976 		out.template ref<4, scale - 1>() = col;
977 		out.template ref<5, scale - 1>() = col;
978 
979 		out.template ref<4, scale - 2>() = col;
980 		out.template ref<5, scale - 2>() = col;
981 	}
982 
983 	template <class OutputMatrix>
blendLineSteepAndShallow__anon189d792b0111::Scaler6x984 	static void blendLineSteepAndShallow(uint32_t col, OutputMatrix& out)
985 	{
986 		alphaGrad<1, 4>(out.template ref<0, scale - 1>(), col);
987 		alphaGrad<1, 4>(out.template ref<2, scale - 2>(), col);
988 		alphaGrad<3, 4>(out.template ref<1, scale - 1>(), col);
989 		alphaGrad<3, 4>(out.template ref<3, scale - 2>(), col);
990 
991 		alphaGrad<1, 4>(out.template ref<scale - 1, 0>(), col);
992 		alphaGrad<1, 4>(out.template ref<scale - 2, 2>(), col);
993 		alphaGrad<3, 4>(out.template ref<scale - 1, 1>(), col);
994 		alphaGrad<3, 4>(out.template ref<scale - 2, 3>(), col);
995 
996 		out.template ref<2, scale - 1>() = col;
997 		out.template ref<3, scale - 1>() = col;
998 		out.template ref<4, scale - 1>() = col;
999 		out.template ref<5, scale - 1>() = col;
1000 
1001 		out.template ref<4, scale - 2>() = col;
1002 		out.template ref<5, scale - 2>() = col;
1003 
1004 		out.template ref<scale - 1, 2>() = col;
1005 		out.template ref<scale - 1, 3>() = col;
1006 	}
1007 
1008 	template <class OutputMatrix>
blendLineDiagonal__anon189d792b0111::Scaler6x1009 	static void blendLineDiagonal(uint32_t col, OutputMatrix& out)
1010 	{
1011 		alphaGrad<1, 2>(out.template ref<scale - 1, scale / 2    >(), col);
1012 		alphaGrad<1, 2>(out.template ref<scale - 2, scale / 2 + 1>(), col);
1013 		alphaGrad<1, 2>(out.template ref<scale - 3, scale / 2 + 2>(), col);
1014 
1015 		out.template ref<scale - 2, scale - 1>() = col;
1016 		out.template ref<scale - 1, scale - 1>() = col;
1017 		out.template ref<scale - 1, scale - 2>() = col;
1018 	}
1019 
1020 	template <class OutputMatrix>
blendCorner__anon189d792b0111::Scaler6x1021 	static void blendCorner(uint32_t col, OutputMatrix& out)
1022 	{
1023 		//model a round corner
1024 		alphaGrad<97, 100>(out.template ref<5, 5>(), col); //exact: 0.9711013910
1025 		alphaGrad<42, 100>(out.template ref<4, 5>(), col); //0.4236372243
1026 		alphaGrad<42, 100>(out.template ref<5, 4>(), col); //0.4236372243
1027 		alphaGrad< 6, 100>(out.template ref<5, 3>(), col); //0.05652034508
1028 		alphaGrad< 6, 100>(out.template ref<3, 5>(), col); //0.05652034508
1029 	}
1030 };
1031 
1032 //------------------------------------------------------------------------------------
1033 
1034 struct ColorDistanceRGB
1035 {
dist__anon189d792b0111::ColorDistanceRGB1036 	static double dist(uint32_t pix1, uint32_t pix2, double luminanceWeight)
1037 	{
1038 		return DistYCbCrBuffer::dist(pix1, pix2);
1039 
1040 		//if (pix1 == pix2) //about 4% perf boost
1041 		//	return 0;
1042 		//return distYCbCr(pix1, pix2, luminanceWeight);
1043 	}
1044 };
1045 
1046 struct ColorDistanceARGB
1047 {
dist__anon189d792b0111::ColorDistanceARGB1048 	static double dist(uint32_t pix1, uint32_t pix2, double luminanceWeight)
1049 	{
1050 		const double a1 = getAlpha(pix1) / 255.0 ;
1051 		const double a2 = getAlpha(pix2) / 255.0 ;
1052 		/*
1053 		Requirements for a color distance handling alpha channel: with a1, a2 in [0, 1]
1054 
1055 			1. if a1 = a2, distance should be: a1 * distYCbCr()
1056 			2. if a1 = 0,  distance should be: a2 * distYCbCr(black, white) = a2 * 255
1057 			3. if a1 = 1,  ??? maybe: 255 * (1 - a2) + a2 * distYCbCr()
1058 		*/
1059 
1060 		//return std::min(a1, a2) * DistYCbCrBuffer::dist(pix1, pix2) + 255 * abs(a1 - a2);
1061 		//=> following code is 15% faster:
1062 		const double d = DistYCbCrBuffer::dist(pix1, pix2);
1063 		if (a1 < a2)
1064 			return a1 * d + 255 * (a2 - a1);
1065 		else
1066 			return a2 * d + 255 * (a1 - a2);
1067 
1068 		//alternative? return std::sqrt(a1 * a2 * square(DistYCbCrBuffer::dist(pix1, pix2)) + square(255 * (a1 - a2)));
1069 	}
1070 };
1071 
1072 
1073 struct ColorGradientRGB
1074 {
1075 	template <unsigned int M, unsigned int N>
alphaGrad__anon189d792b0111::ColorGradientRGB1076 	static void alphaGrad(uint32_t& pixBack, uint32_t pixFront)
1077 	{
1078 		pixBack = gradientRGB<M, N>(pixFront, pixBack);
1079 	}
1080 };
1081 
1082 struct ColorGradientARGB
1083 {
1084 	template <unsigned int M, unsigned int N>
alphaGrad__anon189d792b0111::ColorGradientARGB1085 	static void alphaGrad(uint32_t& pixBack, uint32_t pixFront)
1086 	{
1087 		pixBack = gradientARGB<M, N>(pixFront, pixBack);
1088 	}
1089 };
1090 }
1091 
1092 
scale(size_t factor,const uint32_t * src,uint32_t * trg,int srcWidth,int srcHeight,ColorFormat colFmt,const xbrz::ScalerCfg & cfg,int yFirst,int yLast)1093 void xbrz::scale(size_t factor, const uint32_t* src, uint32_t* trg, int srcWidth, int srcHeight, ColorFormat colFmt, const xbrz::ScalerCfg& cfg, int yFirst, int yLast)
1094 {
1095 	switch (colFmt)
1096 	{
1097 		case ColorFormat::ARGB:
1098 			switch (factor)
1099 			{
1100 				case 2:
1101 					return scaleImage<Scaler2x<ColorGradientARGB>, ColorDistanceARGB>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast);
1102 				case 3:
1103 					return scaleImage<Scaler3x<ColorGradientARGB>, ColorDistanceARGB>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast);
1104 				case 4:
1105 					return scaleImage<Scaler4x<ColorGradientARGB>, ColorDistanceARGB>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast);
1106 				case 5:
1107 					return scaleImage<Scaler5x<ColorGradientARGB>, ColorDistanceARGB>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast);
1108 				case 6:
1109 					return scaleImage<Scaler6x<ColorGradientARGB>, ColorDistanceARGB>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast);
1110 			}
1111 			break;
1112 
1113 		case ColorFormat::RGB:
1114 			switch (factor)
1115 			{
1116 				case 2:
1117 					return scaleImage<Scaler2x<ColorGradientRGB>, ColorDistanceRGB>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast);
1118 				case 3:
1119 					return scaleImage<Scaler3x<ColorGradientRGB>, ColorDistanceRGB>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast);
1120 				case 4:
1121 					return scaleImage<Scaler4x<ColorGradientRGB>, ColorDistanceRGB>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast);
1122 				case 5:
1123 					return scaleImage<Scaler5x<ColorGradientRGB>, ColorDistanceRGB>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast);
1124 				case 6:
1125 					return scaleImage<Scaler6x<ColorGradientRGB>, ColorDistanceRGB>(src, trg, srcWidth, srcHeight, cfg, yFirst, yLast);
1126 			}
1127 			break;
1128 	}
1129 	assert(false);
1130 }
1131 
1132 
equalColorTest(uint32_t col1,uint32_t col2,ColorFormat colFmt,double luminanceWeight,double equalColorTolerance)1133 bool xbrz::equalColorTest(uint32_t col1, uint32_t col2, ColorFormat colFmt, double luminanceWeight, double equalColorTolerance)
1134 {
1135 	switch (colFmt)
1136 	{
1137 		case ColorFormat::ARGB:
1138 			return ColorDistanceARGB::dist(col1, col2, luminanceWeight) < equalColorTolerance;
1139 
1140 		case ColorFormat::RGB:
1141 			return ColorDistanceRGB::dist(col1, col2, luminanceWeight) < equalColorTolerance;
1142 	}
1143 	assert(false);
1144 	return false;
1145 }
1146 
1147 
nearestNeighborScale(const uint32_t * src,int srcWidth,int srcHeight,int srcPitch,uint32_t * trg,int trgWidth,int trgHeight,int trgPitch,SliceType st,int yFirst,int yLast)1148 void xbrz::nearestNeighborScale(const uint32_t* src, int srcWidth, int srcHeight, int srcPitch,
1149 								uint32_t* trg, int trgWidth, int trgHeight, int trgPitch,
1150 								SliceType st, int yFirst, int yLast)
1151 {
1152 	if (srcPitch < srcWidth * static_cast<int>(sizeof(uint32_t))  ||
1153 		trgPitch < trgWidth * static_cast<int>(sizeof(uint32_t)))
1154 	{
1155 		assert(false);
1156 		return;
1157 	}
1158 
1159 	switch (st)
1160 	{
1161 		case NN_SCALE_SLICE_SOURCE:
1162 			//nearest-neighbor (going over source image - fast for upscaling, since source is read only once
1163 			yFirst = std::max(yFirst, 0);
1164 			yLast  = std::min(yLast, srcHeight);
1165 			if (yFirst >= yLast || trgWidth <= 0 || trgHeight <= 0) return;
1166 
1167 			for (int y = yFirst; y < yLast; ++y)
1168 			{
1169 				//mathematically: ySrc = floor(srcHeight * yTrg / trgHeight)
1170 				// => search for integers in: [ySrc, ySrc + 1) * trgHeight / srcHeight
1171 
1172 				//keep within for loop to support MT input slices!
1173 				const int yTrg_first = ( y	  * trgHeight + srcHeight - 1) / srcHeight; //=ceil(y * trgHeight / srcHeight)
1174 				const int yTrg_last  = ((y + 1) * trgHeight + srcHeight - 1) / srcHeight; //=ceil(((y + 1) * trgHeight) / srcHeight)
1175 				const int blockHeight = yTrg_last - yTrg_first;
1176 
1177 				if (blockHeight > 0)
1178 				{
1179 					const uint32_t* srcLine = byteAdvance(src, y * srcPitch);
1180 					uint32_t* trgLine  = byteAdvance(trg, yTrg_first * trgPitch);
1181 					int xTrg_first = 0;
1182 
1183 					for (int x = 0; x < srcWidth; ++x)
1184 					{
1185 						int xTrg_last = ((x + 1) * trgWidth + srcWidth - 1) / srcWidth;
1186 						const int blockWidth = xTrg_last - xTrg_first;
1187 						if (blockWidth > 0)
1188 						{
1189 							xTrg_first = xTrg_last;
1190 							fillBlock(trgLine, trgPitch, srcLine[x], blockWidth, blockHeight);
1191 							trgLine += blockWidth;
1192 						}
1193 					}
1194 				}
1195 			}
1196 			break;
1197 
1198 		case NN_SCALE_SLICE_TARGET:
1199 			//nearest-neighbor (going over target image - slow for upscaling, since source is read multiple times missing out on cache! Fast for similar image sizes!)
1200 			yFirst = std::max(yFirst, 0);
1201 			yLast  = std::min(yLast, trgHeight);
1202 			if (yFirst >= yLast || srcHeight <= 0 || srcWidth <= 0) return;
1203 
1204 			for (int y = yFirst; y < yLast; ++y)
1205 			{
1206 				uint32_t* trgLine = byteAdvance(trg, y * trgPitch);
1207 				const int ySrc = srcHeight * y / trgHeight;
1208 				const uint32_t* srcLine = byteAdvance(src, ySrc * srcPitch);
1209 				for (int x = 0; x < trgWidth; ++x)
1210 				{
1211 					const int xSrc = srcWidth * x / trgWidth;
1212 					trgLine[x] = srcLine[xSrc];
1213 				}
1214 			}
1215 			break;
1216 	}
1217 }
1218