diff --git a/examples/example_4bit_palette.cpp b/examples/example_4bit_palette.cpp index a5e610de..1490ddfc 100644 --- a/examples/example_4bit_palette.cpp +++ b/examples/example_4bit_palette.cpp @@ -44,11 +44,9 @@ Gimp 2.8 image editor (until you set mode to RGB). #include "lodepng.h" -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { //check if user gave a filename - if(argc < 2) - { + if(argc < 2) { std::cout << "please provide a filename to save to" << std::endl; return 0; } @@ -57,8 +55,7 @@ int main(int argc, char *argv[]) lodepng::State state; //generate palette - for(int i = 0; i < 16; i++) - { + for(int i = 0; i < 16; i++) { unsigned char r = 127 * (1 + std::sin(5 * i * 6.28318531 / 16)); unsigned char g = 127 * (1 + std::sin(2 * i * 6.28318531 / 16)); unsigned char b = 127 * (1 + std::sin(3 * i * 6.28318531 / 16)); @@ -83,8 +80,7 @@ int main(int argc, char *argv[]) std::vector image; image.resize((w * h * 4 + 7) / 8, 0); for(unsigned y = 0; y < h; y++) - for(unsigned x = 0; x < w; x++) - { + for(unsigned x = 0; x < w; x++) { size_t byte_index = (y * w + x) / 2; bool byte_half = (y * w + x) % 2 == 1; @@ -97,8 +93,7 @@ int main(int argc, char *argv[]) //encode and save std::vector buffer; unsigned error = lodepng::encode(buffer, image.empty() ? 0 : &image[0], w, h, state); - if(error) - { + if(error) { std::cout << "encoder error " << error << ": "<< lodepng_error_text(error) << std::endl; return 0; } diff --git a/examples/example_bmp2png.cpp b/examples/example_bmp2png.cpp index c6bdd24d..9254bdeb 100644 --- a/examples/example_bmp2png.cpp +++ b/examples/example_bmp2png.cpp @@ -44,10 +44,9 @@ NOTE: it overwrites the output file without warning if it exists! //returns 0 if all went ok, non-0 if error //output image is always given in RGBA (with alpha channel), even if it's a BMP without alpha channel -unsigned decodeBMP(std::vector& image, unsigned& w, unsigned& h, const std::vector& bmp) -{ +unsigned decodeBMP(std::vector& image, unsigned& w, unsigned& h, const std::vector& bmp) { static const unsigned MINHEADER = 54; //minimum BMP header size - + if(bmp.size() < MINHEADER) return -1; if(bmp[0] != 'B' || bmp[1] != 'M') return 1; //It's not a BMP file if it doesn't start with marker 'BM' unsigned pixeloffset = bmp[10] + 256 * bmp[11]; //where the pixel data starts @@ -76,21 +75,17 @@ unsigned decodeBMP(std::vector& image, unsigned& w, unsigned& h, The 2D for loop below does all these 3 conversions at once. */ for(unsigned y = 0; y < h; y++) - for(unsigned x = 0; x < w; x++) - { + for(unsigned x = 0; x < w; x++) { //pixel start byte position in the BMP unsigned bmpos = pixeloffset + (h - y - 1) * scanlineBytes + numChannels * x; //pixel start byte position in the new raw image unsigned newpos = 4 * y * w + 4 * x; - if(numChannels == 3) - { + if(numChannels == 3) { image[newpos + 0] = bmp[bmpos + 2]; //R image[newpos + 1] = bmp[bmpos + 1]; //G image[newpos + 2] = bmp[bmpos + 0]; //B image[newpos + 3] = 255; //A - } - else - { + } else { image[newpos + 0] = bmp[bmpos + 3]; //R image[newpos + 1] = bmp[bmpos + 2]; //G image[newpos + 2] = bmp[bmpos + 1]; //B @@ -100,10 +95,8 @@ unsigned decodeBMP(std::vector& image, unsigned& w, unsigned& h, return 0; } -int main(int argc, char *argv[]) -{ - if(argc < 3) - { +int main(int argc, char *argv[]) { + if(argc < 3) { std::cout << "Please provice input PNG and output BMP file names" << std::endl; return 0; } @@ -114,21 +107,19 @@ int main(int argc, char *argv[]) unsigned w, h; unsigned error = decodeBMP(image, w, h, bmp); - if(error) - { + if(error) { std::cout << "BMP decoding error " << error << std::endl; return 0; } - + std::vector png; error = lodepng::encode(png, image, w, h); - if(error) - { + if(error) { std::cout << "PNG encoding error " << error << ": " << lodepng_error_text(error) << std::endl; return 0; } - + lodepng::save_file(png, argv[2]); - + } diff --git a/examples/example_decode.c b/examples/example_decode.c index 8f6ce392..fc8c0f2c 100644 --- a/examples/example_decode.c +++ b/examples/example_decode.c @@ -1,113 +1,109 @@ -/* -LodePNG Examples - -Copyright (c) 2005-2012 Lode Vandevenne - -This software is provided 'as-is', without any express or implied -warranty. In no event will the authors be held liable for any damages -arising from the use of this software. - -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it -freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - - 3. This notice may not be removed or altered from any source - distribution. -*/ - -#include "lodepng.h" - -#include -#include - -/* -3 ways to decode a PNG from a file to RGBA pixel data (and 2 in-memory ways). -*/ - -/* -Example 1 -Decode from disk to raw pixels with a single function call -*/ -void decodeOneStep(const char* filename) -{ - unsigned error; - unsigned char* image; - unsigned width, height; - - error = lodepng_decode32_file(&image, &width, &height, filename); - if(error) printf("error %u: %s\n", error, lodepng_error_text(error)); - - /*use image here*/ - - free(image); -} - -/* -Example 2 -Load PNG file from disk to memory first, then decode to raw pixels in memory. -*/ -void decodeTwoSteps(const char* filename) -{ - unsigned error; - unsigned char* image; - unsigned width, height; - unsigned char* png = 0; - size_t pngsize; - - error = lodepng_load_file(&png, &pngsize, filename); - if(!error) error = lodepng_decode32(&image, &width, &height, png, pngsize); - if(error) printf("error %u: %s\n", error, lodepng_error_text(error)); - - free(png); - - /*use image here*/ - - free(image); -} - -/* -Example 3 -Load PNG file from disk using a State, normally needed for more advanced usage. -*/ -void decodeWithState(const char* filename) -{ - unsigned error; - unsigned char* image; - unsigned width, height; - unsigned char* png = 0; - size_t pngsize; - LodePNGState state; - - lodepng_state_init(&state); - /*optionally customize the state*/ - - error = lodepng_load_file(&png, &pngsize, filename); - if(!error) error = lodepng_decode(&image, &width, &height, &state, png, pngsize); - if(error) printf("error %u: %s\n", error, lodepng_error_text(error)); - - free(png); - - /*use image here*/ - /*state contains extra information about the PNG such as text chunks, ...*/ - - lodepng_state_cleanup(&state); - free(image); -} - -int main(int argc, char *argv[]) -{ - const char* filename = argc > 1 ? argv[1] : "test.png"; - - decodeOneStep(filename); - - return 0; -} - +/* +LodePNG Examples + +Copyright (c) 2005-2012 Lode Vandevenne + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +*/ + +#include "lodepng.h" + +#include +#include + +/* +3 ways to decode a PNG from a file to RGBA pixel data (and 2 in-memory ways). +*/ + +/* +Example 1 +Decode from disk to raw pixels with a single function call +*/ +void decodeOneStep(const char* filename) { + unsigned error; + unsigned char* image; + unsigned width, height; + + error = lodepng_decode32_file(&image, &width, &height, filename); + if(error) printf("error %u: %s\n", error, lodepng_error_text(error)); + + /*use image here*/ + + free(image); +} + +/* +Example 2 +Load PNG file from disk to memory first, then decode to raw pixels in memory. +*/ +void decodeTwoSteps(const char* filename) { + unsigned error; + unsigned char* image; + unsigned width, height; + unsigned char* png = 0; + size_t pngsize; + + error = lodepng_load_file(&png, &pngsize, filename); + if(!error) error = lodepng_decode32(&image, &width, &height, png, pngsize); + if(error) printf("error %u: %s\n", error, lodepng_error_text(error)); + + free(png); + + /*use image here*/ + + free(image); +} + +/* +Example 3 +Load PNG file from disk using a State, normally needed for more advanced usage. +*/ +void decodeWithState(const char* filename) { + unsigned error; + unsigned char* image; + unsigned width, height; + unsigned char* png = 0; + size_t pngsize; + LodePNGState state; + + lodepng_state_init(&state); + /*optionally customize the state*/ + + error = lodepng_load_file(&png, &pngsize, filename); + if(!error) error = lodepng_decode(&image, &width, &height, &state, png, pngsize); + if(error) printf("error %u: %s\n", error, lodepng_error_text(error)); + + free(png); + + /*use image here*/ + /*state contains extra information about the PNG such as text chunks, ...*/ + + lodepng_state_cleanup(&state); + free(image); +} + +int main(int argc, char *argv[]) { + const char* filename = argc > 1 ? argv[1] : "test.png"; + + decodeOneStep(filename); + + return 0; +} + diff --git a/examples/example_decode.cpp b/examples/example_decode.cpp index 76cda6e2..3a778408 100644 --- a/examples/example_decode.cpp +++ b/examples/example_decode.cpp @@ -1,95 +1,91 @@ -/* -LodePNG Examples - -Copyright (c) 2005-2012 Lode Vandevenne - -This software is provided 'as-is', without any express or implied -warranty. In no event will the authors be held liable for any damages -arising from the use of this software. - -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it -freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - - 3. This notice may not be removed or altered from any source - distribution. -*/ - -#include "lodepng.h" -#include - -/* -3 ways to decode a PNG from a file to RGBA pixel data (and 2 in-memory ways). -*/ - -//g++ lodepng.cpp example_decode.cpp -ansi -pedantic -Wall -Wextra -O3 - - -//Example 1 -//Decode from disk to raw pixels with a single function call -void decodeOneStep(const char* filename) -{ - std::vector image; //the raw pixels - unsigned width, height; - - //decode - unsigned error = lodepng::decode(image, width, height, filename); - - //if there's an error, display it - if(error) std::cout << "decoder error " << error << ": " << lodepng_error_text(error) << std::endl; - - //the pixels are now in the vector "image", 4 bytes per pixel, ordered RGBARGBA..., use it as texture, draw it, ... -} - -//Example 2 -//Load PNG file from disk to memory first, then decode to raw pixels in memory. -void decodeTwoSteps(const char* filename) -{ - std::vector png; - std::vector image; //the raw pixels - unsigned width, height; - - //load and decode - unsigned error = lodepng::load_file(png, filename); - if(!error) error = lodepng::decode(image, width, height, png); - - //if there's an error, display it - if(error) std::cout << "decoder error " << error << ": " << lodepng_error_text(error) << std::endl; - - //the pixels are now in the vector "image", 4 bytes per pixel, ordered RGBARGBA..., use it as texture, draw it, ... -} - -//Example 3 -//Load PNG file from disk using a State, normally needed for more advanced usage. -void decodeWithState(const char* filename) -{ - std::vector png; - std::vector image; //the raw pixels - unsigned width, height; - lodepng::State state; //optionally customize this one - - unsigned error = lodepng::load_file(png, filename); //load the image file with given filename - if(!error) error = lodepng::decode(image, width, height, state, png); - - //if there's an error, display it - if(error) std::cout << "decoder error " << error << ": "<< lodepng_error_text(error) << std::endl; - - //the pixels are now in the vector "image", 4 bytes per pixel, ordered RGBARGBA..., use it as texture, draw it, ... - //State state contains extra information about the PNG such as text chunks, ... -} - -int main(int argc, char *argv[]) -{ - const char* filename = argc > 1 ? argv[1] : "test.png"; - - decodeOneStep(filename); -} - +/* +LodePNG Examples + +Copyright (c) 2005-2012 Lode Vandevenne + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +*/ + +#include "lodepng.h" +#include + +/* +3 ways to decode a PNG from a file to RGBA pixel data (and 2 in-memory ways). +*/ + +//g++ lodepng.cpp example_decode.cpp -ansi -pedantic -Wall -Wextra -O3 + + +//Example 1 +//Decode from disk to raw pixels with a single function call +void decodeOneStep(const char* filename) { + std::vector image; //the raw pixels + unsigned width, height; + + //decode + unsigned error = lodepng::decode(image, width, height, filename); + + //if there's an error, display it + if(error) std::cout << "decoder error " << error << ": " << lodepng_error_text(error) << std::endl; + + //the pixels are now in the vector "image", 4 bytes per pixel, ordered RGBARGBA..., use it as texture, draw it, ... +} + +//Example 2 +//Load PNG file from disk to memory first, then decode to raw pixels in memory. +void decodeTwoSteps(const char* filename) { + std::vector png; + std::vector image; //the raw pixels + unsigned width, height; + + //load and decode + unsigned error = lodepng::load_file(png, filename); + if(!error) error = lodepng::decode(image, width, height, png); + + //if there's an error, display it + if(error) std::cout << "decoder error " << error << ": " << lodepng_error_text(error) << std::endl; + + //the pixels are now in the vector "image", 4 bytes per pixel, ordered RGBARGBA..., use it as texture, draw it, ... +} + +//Example 3 +//Load PNG file from disk using a State, normally needed for more advanced usage. +void decodeWithState(const char* filename) { + std::vector png; + std::vector image; //the raw pixels + unsigned width, height; + lodepng::State state; //optionally customize this one + + unsigned error = lodepng::load_file(png, filename); //load the image file with given filename + if(!error) error = lodepng::decode(image, width, height, state, png); + + //if there's an error, display it + if(error) std::cout << "decoder error " << error << ": "<< lodepng_error_text(error) << std::endl; + + //the pixels are now in the vector "image", 4 bytes per pixel, ordered RGBARGBA..., use it as texture, draw it, ... + //State state contains extra information about the PNG such as text chunks, ... +} + +int main(int argc, char *argv[]) { + const char* filename = argc > 1 ? argv[1] : "test.png"; + + decodeOneStep(filename); +} + diff --git a/examples/example_encode.c b/examples/example_encode.c index 0e0f8bf1..ce43abae 100644 --- a/examples/example_encode.c +++ b/examples/example_encode.c @@ -1,116 +1,111 @@ -/* -LodePNG Examples - -Copyright (c) 2005-2012 Lode Vandevenne - -This software is provided 'as-is', without any express or implied -warranty. In no event will the authors be held liable for any damages -arising from the use of this software. - -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it -freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - - 3. This notice may not be removed or altered from any source - distribution. -*/ - -#include "lodepng.h" - -#include -#include - -/* -3 ways to encode a PNG from RGBA pixel data to a file (and 2 in-memory ways). -NOTE: this samples overwrite the file or test.png without warning! -*/ - -/* -Example 1 -Encode from raw pixels to disk with a single function call -The image argument has width * height RGBA pixels or width * height * 4 bytes -*/ -void encodeOneStep(const char* filename, const unsigned char* image, unsigned width, unsigned height) -{ - /*Encode the image*/ - unsigned error = lodepng_encode32_file(filename, image, width, height); - - /*if there's an error, display it*/ - if(error) printf("error %u: %s\n", error, lodepng_error_text(error)); -} - -/* -Example 2 -Encode from raw pixels to an in-memory PNG file first, then write it to disk -The image argument has width * height RGBA pixels or width * height * 4 bytes -*/ -void encodeTwoSteps(const char* filename, const unsigned char* image, unsigned width, unsigned height) -{ - unsigned char* png; - size_t pngsize; - - unsigned error = lodepng_encode32(&png, &pngsize, image, width, height); - if(!error) lodepng_save_file(png, pngsize, filename); - - /*if there's an error, display it*/ - if(error) printf("error %u: %s\n", error, lodepng_error_text(error)); - - free(png); -} - -/* -Example 3 -Save a PNG file to disk using a State, normally needed for more advanced usage. -The image argument has width * height RGBA pixels or width * height * 4 bytes -*/ -void encodeWithState(const char* filename, const unsigned char* image, unsigned width, unsigned height) -{ - unsigned error; - unsigned char* png; - size_t pngsize; - LodePNGState state; - - lodepng_state_init(&state); - /*optionally customize the state*/ - - error = lodepng_encode(&png, &pngsize, image, width, height, &state); - if(!error) lodepng_save_file(png, pngsize, filename); - - /*if there's an error, display it*/ - if(error) printf("error %u: %s\n", error, lodepng_error_text(error)); - - lodepng_state_cleanup(&state); - free(png); -} - -int main(int argc, char *argv[]) -{ - const char* filename = argc > 1 ? argv[1] : "test.png"; - - /*generate some image*/ - unsigned width = 512, height = 512; - unsigned char* image = malloc(width * height * 4); - unsigned x, y; - for(y = 0; y < height; y++) - for(x = 0; x < width; x++) - { - image[4 * width * y + 4 * x + 0] = 255 * !(x & y); - image[4 * width * y + 4 * x + 1] = x ^ y; - image[4 * width * y + 4 * x + 2] = x | y; - image[4 * width * y + 4 * x + 3] = 255; - } - - /*run an example*/ - encodeOneStep(filename, image, width, height); - - free(image); - return 0; -} +/* +LodePNG Examples + +Copyright (c) 2005-2012 Lode Vandevenne + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +*/ + +#include "lodepng.h" + +#include +#include + +/* +3 ways to encode a PNG from RGBA pixel data to a file (and 2 in-memory ways). +NOTE: this samples overwrite the file or test.png without warning! +*/ + +/* +Example 1 +Encode from raw pixels to disk with a single function call +The image argument has width * height RGBA pixels or width * height * 4 bytes +*/ +void encodeOneStep(const char* filename, const unsigned char* image, unsigned width, unsigned height) { + /*Encode the image*/ + unsigned error = lodepng_encode32_file(filename, image, width, height); + + /*if there's an error, display it*/ + if(error) printf("error %u: %s\n", error, lodepng_error_text(error)); +} + +/* +Example 2 +Encode from raw pixels to an in-memory PNG file first, then write it to disk +The image argument has width * height RGBA pixels or width * height * 4 bytes +*/ +void encodeTwoSteps(const char* filename, const unsigned char* image, unsigned width, unsigned height) { + unsigned char* png; + size_t pngsize; + + unsigned error = lodepng_encode32(&png, &pngsize, image, width, height); + if(!error) lodepng_save_file(png, pngsize, filename); + + /*if there's an error, display it*/ + if(error) printf("error %u: %s\n", error, lodepng_error_text(error)); + + free(png); +} + +/* +Example 3 +Save a PNG file to disk using a State, normally needed for more advanced usage. +The image argument has width * height RGBA pixels or width * height * 4 bytes +*/ +void encodeWithState(const char* filename, const unsigned char* image, unsigned width, unsigned height) { + unsigned error; + unsigned char* png; + size_t pngsize; + LodePNGState state; + + lodepng_state_init(&state); + /*optionally customize the state*/ + + error = lodepng_encode(&png, &pngsize, image, width, height, &state); + if(!error) lodepng_save_file(png, pngsize, filename); + + /*if there's an error, display it*/ + if(error) printf("error %u: %s\n", error, lodepng_error_text(error)); + + lodepng_state_cleanup(&state); + free(png); +} + +int main(int argc, char *argv[]) { + const char* filename = argc > 1 ? argv[1] : "test.png"; + + /*generate some image*/ + unsigned width = 512, height = 512; + unsigned char* image = malloc(width * height * 4); + unsigned x, y; + for(y = 0; y < height; y++) + for(x = 0; x < width; x++) { + image[4 * width * y + 4 * x + 0] = 255 * !(x & y); + image[4 * width * y + 4 * x + 1] = x ^ y; + image[4 * width * y + 4 * x + 2] = x | y; + image[4 * width * y + 4 * x + 3] = 255; + } + + /*run an example*/ + encodeOneStep(filename, image, width, height); + + free(image); + return 0; +} diff --git a/examples/example_encode.cpp b/examples/example_encode.cpp index 0258e620..228ac030 100644 --- a/examples/example_encode.cpp +++ b/examples/example_encode.cpp @@ -1,97 +1,92 @@ -/* -LodePNG Examples - -Copyright (c) 2005-2012 Lode Vandevenne - -This software is provided 'as-is', without any express or implied -warranty. In no event will the authors be held liable for any damages -arising from the use of this software. - -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it -freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - - 3. This notice may not be removed or altered from any source - distribution. -*/ - -#include "lodepng.h" -#include - -/* -3 ways to encode a PNG from RGBA pixel data to a file (and 2 in-memory ways). -NOTE: this samples overwrite the file or test.png without warning! -*/ - -//g++ lodepng.cpp examples/example_encode.cpp -I./ -ansi -pedantic -Wall -Wextra -O3 - -//Example 1 -//Encode from raw pixels to disk with a single function call -//The image argument has width * height RGBA pixels or width * height * 4 bytes -void encodeOneStep(const char* filename, std::vector& image, unsigned width, unsigned height) -{ - //Encode the image - unsigned error = lodepng::encode(filename, image, width, height); - - //if there's an error, display it - if(error) std::cout << "encoder error " << error << ": "<< lodepng_error_text(error) << std::endl; -} - -//Example 2 -//Encode from raw pixels to an in-memory PNG file first, then write it to disk -//The image argument has width * height RGBA pixels or width * height * 4 bytes -void encodeTwoSteps(const char* filename, std::vector& image, unsigned width, unsigned height) -{ - std::vector png; - - unsigned error = lodepng::encode(png, image, width, height); - if(!error) lodepng::save_file(png, filename); - - //if there's an error, display it - if(error) std::cout << "encoder error " << error << ": "<< lodepng_error_text(error) << std::endl; -} - -//Example 3 -//Save a PNG file to disk using a State, normally needed for more advanced usage. -//The image argument has width * height RGBA pixels or width * height * 4 bytes -void encodeWithState(const char* filename, std::vector& image, unsigned width, unsigned height) -{ - std::vector png; - lodepng::State state; //optionally customize this one - - unsigned error = lodepng::encode(png, image, width, height, state); - if(!error) lodepng::save_file(png, filename); - - //if there's an error, display it - if(error) std::cout << "encoder error " << error << ": "<< lodepng_error_text(error) << std::endl; -} - -//saves image to filename given as argument. Warning, this overwrites the file without warning! -int main(int argc, char *argv[]) -{ - //NOTE: this sample will overwrite the file or test.png without warning! - const char* filename = argc > 1 ? argv[1] : "test.png"; - - //generate some image - unsigned width = 512, height = 512; - std::vector image; - image.resize(width * height * 4); - for(unsigned y = 0; y < height; y++) - for(unsigned x = 0; x < width; x++) - { - image[4 * width * y + 4 * x + 0] = 255 * !(x & y); - image[4 * width * y + 4 * x + 1] = x ^ y; - image[4 * width * y + 4 * x + 2] = x | y; - image[4 * width * y + 4 * x + 3] = 255; - } - - encodeOneStep(filename, image, width, height); -} +/* +LodePNG Examples + +Copyright (c) 2005-2012 Lode Vandevenne + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +*/ + +#include "lodepng.h" +#include + +/* +3 ways to encode a PNG from RGBA pixel data to a file (and 2 in-memory ways). +NOTE: this samples overwrite the file or test.png without warning! +*/ + +//g++ lodepng.cpp examples/example_encode.cpp -I./ -ansi -pedantic -Wall -Wextra -O3 + +//Example 1 +//Encode from raw pixels to disk with a single function call +//The image argument has width * height RGBA pixels or width * height * 4 bytes +void encodeOneStep(const char* filename, std::vector& image, unsigned width, unsigned height) { + //Encode the image + unsigned error = lodepng::encode(filename, image, width, height); + + //if there's an error, display it + if(error) std::cout << "encoder error " << error << ": "<< lodepng_error_text(error) << std::endl; +} + +//Example 2 +//Encode from raw pixels to an in-memory PNG file first, then write it to disk +//The image argument has width * height RGBA pixels or width * height * 4 bytes +void encodeTwoSteps(const char* filename, std::vector& image, unsigned width, unsigned height) { + std::vector png; + + unsigned error = lodepng::encode(png, image, width, height); + if(!error) lodepng::save_file(png, filename); + + //if there's an error, display it + if(error) std::cout << "encoder error " << error << ": "<< lodepng_error_text(error) << std::endl; +} + +//Example 3 +//Save a PNG file to disk using a State, normally needed for more advanced usage. +//The image argument has width * height RGBA pixels or width * height * 4 bytes +void encodeWithState(const char* filename, std::vector& image, unsigned width, unsigned height) { + std::vector png; + lodepng::State state; //optionally customize this one + + unsigned error = lodepng::encode(png, image, width, height, state); + if(!error) lodepng::save_file(png, filename); + + //if there's an error, display it + if(error) std::cout << "encoder error " << error << ": "<< lodepng_error_text(error) << std::endl; +} + +//saves image to filename given as argument. Warning, this overwrites the file without warning! +int main(int argc, char *argv[]) { + //NOTE: this sample will overwrite the file or test.png without warning! + const char* filename = argc > 1 ? argv[1] : "test.png"; + + //generate some image + unsigned width = 512, height = 512; + std::vector image; + image.resize(width * height * 4); + for(unsigned y = 0; y < height; y++) + for(unsigned x = 0; x < width; x++) { + image[4 * width * y + 4 * x + 0] = 255 * !(x & y); + image[4 * width * y + 4 * x + 1] = x ^ y; + image[4 * width * y + 4 * x + 2] = x | y; + image[4 * width * y + 4 * x + 3] = 255; + } + + encodeOneStep(filename, image, width, height); +} diff --git a/examples/example_encode_type.cpp b/examples/example_encode_type.cpp index a28e38d0..c133b241 100644 --- a/examples/example_encode_type.cpp +++ b/examples/example_encode_type.cpp @@ -1,79 +1,76 @@ -/* -LodePNG Examples - -Copyright (c) 2005-2015 Lode Vandevenne - -This software is provided 'as-is', without any express or implied -warranty. In no event will the authors be held liable for any damages -arising from the use of this software. - -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it -freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - - 3. This notice may not be removed or altered from any source - distribution. -*/ - -//g++ -I ./ lodepng.cpp examples/example_encode_type.cpp -ansi -pedantic -Wall -Wextra -O3 - - - -/* -This example shows how to enforce a certain color type of the PNG image when -encoding a PNG (because by default, LodePNG automatically chooses an optimal -color type, no matter what your raw data's color type is) -*/ - -#include -#include - -#include "lodepng.h" - -int main(int argc, char *argv[]) -{ - //check if user gave a filename - if(argc < 2) - { - std::cout << "please provide a filename to save to" << std::endl; - return 0; - } - - //generate some image - const unsigned w = 256; - const unsigned h = 256; - std::vector image(w * h * 4); - for(unsigned y = 0; y < h; y++) - for(unsigned x = 0; x < w; x++) - { - int index = y * w * 4 + x * 4; - image[index + 0] = 0; - image[index + 1] = 0; - image[index + 2] = 0; - image[index + 3] = 255; - } - - // we're going to encode with a state rather than a convenient function, because enforcing a color type requires setting options - lodepng::State state; - // input color type - state.info_raw.colortype = LCT_RGBA; - state.info_raw.bitdepth = 8; - // output color type - state.info_png.color.colortype = LCT_RGBA; - state.info_png.color.bitdepth = 8; - state.encoder.auto_convert = 0; // without this, it would ignore the output color type specified above and choose an optimal one instead - - //encode and save - std::vector buffer; - unsigned error = lodepng::encode(buffer, &image[0], w, h, state); - if(error) std::cout << "encoder error " << error << ": "<< lodepng_error_text(error) << std::endl; - else lodepng::save_file(buffer, argv[1]); -} +/* +LodePNG Examples + +Copyright (c) 2005-2015 Lode Vandevenne + +This software is provided 'as-is', without any express or implied +warranty. In no event will the authors be held liable for any damages +arising from the use of this software. + +Permission is granted to anyone to use this software for any purpose, +including commercial applications, and to alter it and redistribute it +freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + + 3. This notice may not be removed or altered from any source + distribution. +*/ + +//g++ -I ./ lodepng.cpp examples/example_encode_type.cpp -ansi -pedantic -Wall -Wextra -O3 + + + +/* +This example shows how to enforce a certain color type of the PNG image when +encoding a PNG (because by default, LodePNG automatically chooses an optimal +color type, no matter what your raw data's color type is) +*/ + +#include +#include + +#include "lodepng.h" + +int main(int argc, char *argv[]) { + //check if user gave a filename + if(argc < 2) { + std::cout << "please provide a filename to save to" << std::endl; + return 0; + } + + //generate some image + const unsigned w = 256; + const unsigned h = 256; + std::vector image(w * h * 4); + for(unsigned y = 0; y < h; y++) + for(unsigned x = 0; x < w; x++) { + int index = y * w * 4 + x * 4; + image[index + 0] = 0; + image[index + 1] = 0; + image[index + 2] = 0; + image[index + 3] = 255; + } + + // we're going to encode with a state rather than a convenient function, because enforcing a color type requires setting options + lodepng::State state; + // input color type + state.info_raw.colortype = LCT_RGBA; + state.info_raw.bitdepth = 8; + // output color type + state.info_png.color.colortype = LCT_RGBA; + state.info_png.color.bitdepth = 8; + state.encoder.auto_convert = 0; // without this, it would ignore the output color type specified above and choose an optimal one instead + + //encode and save + std::vector buffer; + unsigned error = lodepng::encode(buffer, &image[0], w, h, state); + if(error) std::cout << "encoder error " << error << ": "<< lodepng_error_text(error) << std::endl; + else lodepng::save_file(buffer, argv[1]); +} diff --git a/examples/example_gzip.cpp b/examples/example_gzip.cpp index b2ddf17b..60545aa3 100644 --- a/examples/example_gzip.cpp +++ b/examples/example_gzip.cpp @@ -36,21 +36,19 @@ See also the gzip specification, RFC 1952: http://www.gzip.org/zlib/rfc-gzip.htm //g++ lodepng.cpp example_gzip.cpp -ansi -pedantic -Wall -Wextra -O3 //saves image to filename given as argument. Warning, this overwrites the file without warning! -int main(int argc, char *argv[]) -{ - if(argc < 2) - { +int main(int argc, char *argv[]) { + if(argc < 2) { std::cout << "Please provide input filename (output is input with .gz)" << std::endl; return 0; } - + //NOTE: this sample will overwrite the output file without warning! std::string infilename = argv[1]; std::string outfilename = infilename + ".gz"; - + std::vector in; lodepng::load_file(in, infilename); - + size_t outsize = 10; unsigned char* out = (unsigned char*)malloc(outsize); out[0] = 31; //ID1 @@ -65,16 +63,16 @@ int main(int argc, char *argv[]) out[8] = 2; //2 = slow, 4 = fast compression out[9] = 255; //OS unknown - + lodepng_deflate(&out, &outsize, &in[0], in.size(), &lodepng_default_compress_settings); - + unsigned crc = lodepng_crc32(&in[0], in.size()); - + size_t footer = outsize; - + outsize += 8; out = (unsigned char*)realloc(out, outsize); - + //CRC out[footer + 0] = crc % 256; out[footer + 1] = (crc >> 8) % 256; @@ -86,8 +84,8 @@ int main(int argc, char *argv[]) out[footer + 5] = (in.size() >> 8) % 256; out[footer + 6] = (in.size() >> 16) % 256; out[footer + 7] = (in.size() >> 24) % 256; - + lodepng_save_file(out, outsize, outfilename.c_str()); - + free(out); } diff --git a/examples/example_opengl.cpp b/examples/example_opengl.cpp index 18798649..a4352ebd 100644 --- a/examples/example_opengl.cpp +++ b/examples/example_opengl.cpp @@ -46,10 +46,8 @@ shows LodePNG can be used to load PNG images as textures in OpenGL. #include #include -int main(int argc, char *argv[]) -{ - if(argc < 2) - { +int main(int argc, char *argv[]) { + if(argc < 2) { std::cout << "Please provide a filename." << std::endl; return 1; } @@ -61,12 +59,11 @@ int main(int argc, char *argv[]) unsigned error = lodepng::decode(image, width, height, filename); // If there's an error, display it. - if(error != 0) - { + if(error != 0) { std::cout << "error " << error << ": " << lodepng_error_text(error) << std::endl; return 1; } - + // Here the PNG is loaded in "image". All the rest of the code is SDL and OpenGL stuff. int screenw = width; @@ -74,16 +71,14 @@ int main(int argc, char *argv[]) int screenh = height; if(screenh > 768) screenw = 768; - if(SDL_Init(SDL_INIT_VIDEO) < 0) - { + if(SDL_Init(SDL_INIT_VIDEO) < 0) { std::cout << "Error: Unable to init SDL: " << SDL_GetError() << std::endl; return 1; } - + SDL_Surface* scr = SDL_SetVideoMode(screenw, screenh, 32, SDL_OPENGL); - if(scr == 0) - { + if(scr == 0) { std::cout << "Error: Unable to set video. SDL error message: " << SDL_GetError() << std::endl; return 1; } @@ -103,12 +98,11 @@ int main(int argc, char *argv[]) glEnable(GL_BLEND); glDisable(GL_ALPHA_TEST); - if(glGetError() != GL_NO_ERROR) - { + if(glGetError() != GL_NO_ERROR) { std::cout << "Error initing GL" << std::endl; return 1; } - + // Texture size must be power of two for the primitive OpenGL version this is written for. Find next power of two. size_t u2 = 1; while(u2 < width) u2 *= 2; size_t v2 = 1; while(v2 < height) v2 *= 2; @@ -120,29 +114,26 @@ int main(int argc, char *argv[]) std::vector image2(u2 * v2 * 4); for(size_t y = 0; y < height; y++) for(size_t x = 0; x < width; x++) - for(size_t c = 0; c < 4; c++) - { + for(size_t c = 0; c < 4; c++) { image2[4 * u2 * y + 4 * x + c] = image[4 * width * y + 4 * x + c]; } - + // Enable the texture for OpenGL. glEnable(GL_TEXTURE_2D); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); //GL_NEAREST = no smoothing glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, 4, u2, v2, 0, GL_RGBA, GL_UNSIGNED_BYTE, &image2[0]); - + bool done = false; SDL_Event event = {0}; glColor4ub(255, 255, 255, 255); - - while(!done) - { + + while(!done) { // Quit the loop when receiving quit event. - while(SDL_PollEvent(&event)) - { + while(SDL_PollEvent(&event)) { if(event.type == SDL_QUIT) done = 1; } - + // Draw the texture on a quad, using u3 and v3 to correct non power of two texture size. glBegin(GL_QUADS); glTexCoord2d( 0, 0); glVertex2f( 0, 0); @@ -150,12 +141,12 @@ int main(int argc, char *argv[]) glTexCoord2d(u3, v3); glVertex2f(width, height); glTexCoord2d( 0, v3); glVertex2f( 0, height); glEnd(); - + // Redraw and clear screen. SDL_GL_SwapBuffers(); glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - + //Limit frames per second, to not heat up the CPU and GPU too much. SDL_Delay(16); } diff --git a/examples/example_optimize_png.cpp b/examples/example_optimize_png.cpp index d64c7f22..4fa2ac1c 100644 --- a/examples/example_optimize_png.cpp +++ b/examples/example_optimize_png.cpp @@ -37,35 +37,32 @@ NOTE: This is not as good as a true PNG optimizer like optipng or pngcrush. #include -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { std::vector image; unsigned w, h; std::vector buffer; unsigned error; - + //check if user gave a filename - if(argc < 3) - { + if(argc < 3) { std::cout << "please provide in and out filename" << std::endl; return 0; } - + lodepng::load_file(buffer, argv[1]); error = lodepng::decode(image, w, h, buffer); - if(error) - { + if(error) { std::cout << "decoding error " << error << ": " << lodepng_error_text(error) << std::endl; return 0; } - + size_t origsize = buffer.size(); std::cout << "Original size: " << origsize << " (" << (origsize / 1024) << "K)" << std::endl; buffer.clear(); - + //Now encode as hard as possible with several filter types and window sizes - + lodepng::State state; state.encoder.filter_palette_zero = 0; //We try several filter types, including zero, allow trying them all on palette images too. state.encoder.add_id = false; //Don't add LodePNG version chunk to save more bytes @@ -84,7 +81,7 @@ int main(int argc, char *argv[]) // min match 3 allows all deflate lengths. min match 6 is similar to "Z_FILTERED" of zlib. int minmatches[2] = { 3, 6 }; int bestminmatch = 0; - + int autoconverts[2] = { 0, 1 }; std::string autoconvertnames[2] = { "0", "1" }; int bestautoconvert = 0; @@ -92,11 +89,10 @@ int main(int argc, char *argv[]) int bestblocktype = 0; // Try out all combinations of everything - for(int i = 0; i < 4; i++) //filter strategy - for(int j = 0; j < 2; j++) //min match - for(int k = 0; k < 2; k++) //block type (for small images only) - for(int l = 0; l < 2; l++) //color convert strategy - { + for(int i = 0; i < 4; i++) //filter strategy + for(int j = 0; j < 2; j++) //min match + for(int k = 0; k < 2; k++) //block type (for small images only) + for(int l = 0; l < 2; l++) { //color convert strategy if(bestsize > 3000 && (k > 0 || l > 0)) continue; /* these only make sense on small images */ std::vector temp; state.encoder.filter_strategy = strategies[i]; @@ -122,12 +118,12 @@ int main(int argc, char *argv[]) inited = true; } } - + std::cout << "Chosen filter strategy: " << strategynames[beststrategy] << std::endl; std::cout << "Chosen min match: " << bestminmatch << std::endl; std::cout << "Chosen block type: " << bestblocktype << std::endl; std::cout << "Chosen auto convert: " << autoconvertnames[bestautoconvert] << std::endl; - + lodepng::save_file(buffer, argv[2]); std::cout << "New size: " << buffer.size() << " (" << (buffer.size() / 1024) << "K)" << std::endl; } diff --git a/examples/example_png2bmp.cpp b/examples/example_png2bmp.cpp index 3fd8328b..ae12298f 100644 --- a/examples/example_png2bmp.cpp +++ b/examples/example_png2bmp.cpp @@ -41,12 +41,11 @@ g++ lodepng.cpp example_png2bmp.cpp -Wall -Wextra -pedantic -ansi -lSDL -O3 //Input image must be RGB buffer (3 bytes per pixel), but you can easily make it //support RGBA input and output by changing the inputChannels and/or outputChannels //in the function to 4. -void encodeBMP(std::vector& bmp, const unsigned char* image, int w, int h) -{ +void encodeBMP(std::vector& bmp, const unsigned char* image, int w, int h) { //3 bytes per pixel used for both input and output. int inputChannels = 3; int outputChannels = 3; - + //bytes 0-13 bmp.push_back('B'); bmp.push_back('M'); //0: bfType bmp.push_back(0); bmp.push_back(0); bmp.push_back(0); bmp.push_back(0); //2: bfSize; size not yet known for now, filled in later. @@ -66,7 +65,7 @@ void encodeBMP(std::vector& bmp, const unsigned char* image, int bmp.push_back(0); bmp.push_back(0); bmp.push_back(0); bmp.push_back(0); //42: biYPelsPerMeter bmp.push_back(0); bmp.push_back(0); bmp.push_back(0); bmp.push_back(0); //46: biClrUsed bmp.push_back(0); bmp.push_back(0); bmp.push_back(0); bmp.push_back(0); //50: biClrImportant - + /* Convert the input RGBRGBRGB pixel buffer to the BMP pixel buffer format. There are 3 differences with the input buffer: -BMP stores the rows inversed, from bottom to top @@ -76,14 +75,11 @@ void encodeBMP(std::vector& bmp, const unsigned char* image, int int imagerowbytes = outputChannels * w; imagerowbytes = imagerowbytes % 4 == 0 ? imagerowbytes : imagerowbytes + (4 - imagerowbytes % 4); //must be multiple of 4 - - for(int y = h - 1; y >= 0; y--) //the rows are stored inversed in bmp - { + + for(int y = h - 1; y >= 0; y--) { //the rows are stored inversed in bmp int c = 0; - for(int x = 0; x < imagerowbytes; x++) - { - if(x < w * outputChannels) - { + for(int x = 0; x < imagerowbytes; x++) { + if(x < w * outputChannels) { int inc = c; //Convert RGB(A) into BGR(A) if(c == 0) inc = 2; @@ -103,30 +99,27 @@ void encodeBMP(std::vector& bmp, const unsigned char* image, int bmp[5] = bmp.size() / 16777216; } -int main(int argc, char *argv[]) -{ - if(argc < 3) - { +int main(int argc, char *argv[]) { + if(argc < 3) { std::cout << "Please provice input PNG and output BMP file names" << std::endl; return 0; } const char* infile = argv[1]; const char* outfile = argv[2]; - - + + std::vector image; //the raw pixels unsigned width, height; unsigned error = lodepng::decode(image, width, height, infile, LCT_RGB, 8); - if(error) - { + if(error) { std::cout << "error " << error << ": " << lodepng_error_text(error) << std::endl; return 0; } std::vector bmp; encodeBMP(bmp, &image[0], width, height); - + lodepng::save_file(bmp, outfile); } diff --git a/examples/example_png_info.cpp b/examples/example_png_info.cpp index cd2eca60..43427ccc 100644 --- a/examples/example_png_info.cpp +++ b/examples/example_png_info.cpp @@ -38,8 +38,7 @@ etc... /* Display general info about the PNG. */ -void displayPNGInfo(const LodePNGInfo& info) -{ +void displayPNGInfo(const LodePNGInfo& info) { const LodePNGColorMode& color = info.color; std::cout << "Compression method: " << info.compression_method << std::endl; @@ -53,20 +52,17 @@ void displayPNGInfo(const LodePNGInfo& info) std::cout << "Can have alpha: " << lodepng_can_have_alpha(&color) << std::endl; std::cout << "Palette size: " << color.palettesize << std::endl; std::cout << "Has color key: " << color.key_defined << std::endl; - if(color.key_defined) - { + if(color.key_defined) { std::cout << "Color key r: " << color.key_r << std::endl; std::cout << "Color key g: " << color.key_g << std::endl; std::cout << "Color key b: " << color.key_b << std::endl; } std::cout << "Texts: " << info.text_num << std::endl; - for(size_t i = 0; i < info.text_num; i++) - { + for(size_t i = 0; i < info.text_num; i++) { std::cout << "Text: " << info.text_keys[i] << ": " << info.text_strings[i] << std::endl << std::endl; } std::cout << "International texts: " << info.itext_num << std::endl; - for(size_t i = 0; i < info.itext_num; i++) - { + for(size_t i = 0; i < info.itext_num; i++) { std::cout << "Text: " << info.itext_keys[i] << ", " << info.itext_langtags[i] << ", " @@ -74,8 +70,7 @@ void displayPNGInfo(const LodePNGInfo& info) << info.itext_strings[i] << std::endl << std::endl; } std::cout << "Time defined: " << info.time_defined << std::endl; - if(info.time_defined) - { + if(info.time_defined) { const LodePNGTime& time = info.time; std::cout << "year: " << time.year << std::endl; std::cout << "month: " << time.month << std::endl; @@ -85,8 +80,7 @@ void displayPNGInfo(const LodePNGInfo& info) std::cout << "second: " << time.second << std::endl; } std::cout << "Physics defined: " << info.phys_defined << std::endl; - if(info.phys_defined) - { + if(info.phys_defined) { std::cout << "physics X: " << info.phys_x << std::endl; std::cout << "physics Y: " << info.phys_y << std::endl; std::cout << "physics unit: " << info.phys_unit << std::endl; @@ -97,8 +91,7 @@ void displayPNGInfo(const LodePNGInfo& info) /* Display the names and sizes of all chunks in the PNG file. */ -void displayChunkNames(const std::vector& buffer) -{ +void displayChunkNames(const std::vector& buffer) { // Listing chunks is based on the original file, not the decoded png info. const unsigned char *chunk, *begin, *end, *next; end = &buffer.back() + 1; @@ -107,18 +100,15 @@ void displayChunkNames(const std::vector& buffer) std::cout << std::endl << "Chunks:" << std::endl; std::cout << " type: length(s)"; std::string last_type; - while(chunk + 8 < end && chunk >= begin) - { + while(chunk + 8 < end && chunk >= begin) { char type[5]; lodepng_chunk_type(type, chunk); - if(std::string(type).size() != 4) - { + if(std::string(type).size() != 4) { std::cout << "this is probably not a PNG" << std::endl; return; } - if(last_type != type) - { + if(last_type != type) { std::cout << std::endl; std::cout << " " << type << ": "; } @@ -137,10 +127,8 @@ void displayChunkNames(const std::vector& buffer) /* Show ASCII art preview of the image */ -void displayAsciiArt(const std::vector& image, unsigned w, unsigned h) -{ - if(w > 0 && h > 0) - { +void displayAsciiArt(const std::vector& image, unsigned w, unsigned h) { + if(w > 0 && h > 0) { std::cout << std::endl << "ASCII Art Preview: " << std::endl; unsigned w2 = 48; if(w < w2) w2 = w; @@ -151,11 +139,9 @@ void displayAsciiArt(const std::vector& image, unsigned w, unsign std::cout << '+'; for(unsigned x = 0; x < w2; x++) std::cout << '-'; std::cout << '+' << std::endl; - for(unsigned y = 0; y < h2; y++) - { + for(unsigned y = 0; y < h2; y++) { std::cout << "|"; - for(unsigned x = 0; x < w2; x++) - { + for(unsigned x = 0; x < w2; x++) { unsigned x2 = x * w / w2; unsigned y2 = y * h / h2; int r = image[y2 * w * 4 + x2 * 4 + 0]; @@ -167,8 +153,7 @@ void displayAsciiArt(const std::vector& image, unsigned w, unsign int max = (r > g && r > b) ? r : (g > b ? g : b); int saturation = max - min; int letter = 'i'; //i for grey, or r,y,g,c,b,m for colors - if(saturation > 32) - { + if(saturation > 32) { int h = lightness >= (min + max) / 2; if(h) letter = (min == r ? 'c' : (min == g ? 'm' : 'y')); else letter = (max == r ? 'r' : (max == g ? 'g' : 'b')); @@ -193,12 +178,10 @@ void displayAsciiArt(const std::vector& image, unsigned w, unsign /* Show the filtertypes of each scanline in this PNG image. */ -void displayFilterTypes(const std::vector& buffer, bool ignore_checksums) -{ +void displayFilterTypes(const std::vector& buffer, bool ignore_checksums) { //Get color type and interlace type lodepng::State state; - if(ignore_checksums) - { + if(ignore_checksums) { state.decoder.ignore_crc = 1; state.decoder.zlibsettings.ignore_adler32 = 1; } @@ -206,14 +189,12 @@ void displayFilterTypes(const std::vector& buffer, bool ignore_ch unsigned error; error = lodepng_inspect(&w, &h, &state, &buffer[0], buffer.size()); - if(error) - { + if(error) { std::cout << "inspect error " << error << ": " << lodepng_error_text(error) << std::endl; return; } - if(state.info_png.interlace_method == 1) - { + if(state.info_png.interlace_method == 1) { std::cout << "showing filtertypes for interlaced PNG not supported by this example" << std::endl; return; } @@ -225,18 +206,15 @@ void displayFilterTypes(const std::vector& buffer, bool ignore_ch std::vector zdata; - while(chunk + 8 < end && chunk >= begin) - { + while(chunk + 8 < end && chunk >= begin) { char type[5]; lodepng_chunk_type(type, chunk); - if(std::string(type).size() != 4) - { + if(std::string(type).size() != 4) { std::cout << "this is probably not a PNG" << std::endl; return; } - if(std::string(type) == "IDAT") - { + if(std::string(type) == "IDAT") { const unsigned char* cdata = lodepng_chunk_data_const(chunk); unsigned clength = lodepng_chunk_length(chunk); if(chunk + clength + 12 > end || clength > buffer.size() || chunk + clength + 12 < begin) { @@ -244,8 +222,7 @@ void displayFilterTypes(const std::vector& buffer, bool ignore_ch return; } - for(unsigned i = 0; i < clength; i++) - { + for(unsigned i = 0; i < clength; i++) { zdata.push_back(cdata[i]); } } @@ -259,8 +236,7 @@ void displayFilterTypes(const std::vector& buffer, bool ignore_ch std::vector data; error = lodepng::decompress(data, &zdata[0], zdata.size()); - if(error) - { + if(error) { std::cout << "decompress error " << error << ": " << lodepng_error_text(error) << std::endl; return; } @@ -268,15 +244,13 @@ void displayFilterTypes(const std::vector& buffer, bool ignore_ch //A line is 1 filter byte + all pixels size_t linebytes = 1 + lodepng_get_raw_size(w, 1, &state.info_png.color); - if(linebytes == 0) - { + if(linebytes == 0) { std::cout << "error: linebytes is 0" << std::endl; return; } std::cout << "Filter types: "; - for(size_t i = 0; i < data.size(); i += linebytes) - { + for(size_t i = 0; i < data.size(); i += linebytes) { std::cout << (int)(data[i]) << " "; } std::cout << std::endl; @@ -287,17 +261,14 @@ void displayFilterTypes(const std::vector& buffer, bool ignore_ch /* Main */ -int main(int argc, char *argv[]) /*list the chunks*/ -{ +int main(int argc, char *argv[]) /*list the chunks*/ { bool ignore_checksums = false; std::string filename = ""; - for (int i = 1; i < argc; i++) - { + for (int i = 1; i < argc; i++) { if(std::string(argv[i]) == "--ignore_checksums") ignore_checksums = true; else filename = argv[i]; } - if(filename == "") - { + if(filename == "") { std::cout << "Please provide a filename to preview" << std::endl; return 0; } @@ -309,16 +280,14 @@ int main(int argc, char *argv[]) /*list the chunks*/ lodepng::load_file(buffer, filename); //load the image file with given filename lodepng::State state; - if(ignore_checksums) - { + if(ignore_checksums) { state.decoder.ignore_crc = 1; state.decoder.zlibsettings.ignore_adler32 = 1; } unsigned error = lodepng::decode(image, w, h, state, buffer); - if(error) - { + if(error) { std::cout << "decoder error " << error << ": " << lodepng_error_text(error) << std::endl; return 0; } @@ -328,8 +297,7 @@ int main(int argc, char *argv[]) /*list the chunks*/ std::cout << "Height: " << h << std::endl; std::cout << "Num pixels: " << w * h << std::endl; - if(w > 0 && h > 0) - { + if(w > 0 && h > 0) { std::cout << "Top left pixel color:" << " r: " << (int)image[0] << " g: " << (int)image[1] diff --git a/examples/example_reencode.cpp b/examples/example_reencode.cpp index d4386129..d316bc91 100644 --- a/examples/example_reencode.cpp +++ b/examples/example_reencode.cpp @@ -35,42 +35,38 @@ This sample shows how LodePNG can be used for a conforming PNG editor. #include -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { std::vector image; unsigned w, h; std::vector buffer; lodepng::State state; unsigned error; - + //check if user gave a filename - if(argc < 3) - { + if(argc < 3) { std::cout << "please provide in and out filename" << std::endl; return 0; } - + state.decoder.color_convert = 0; state.decoder.remember_unknown_chunks = 1; //make it reproduce even unknown chunks in the saved image - + lodepng::load_file(buffer, argv[1]); error = lodepng::decode(image, w, h, state, buffer); - if(error) - { + if(error) { std::cout << "decoder error " << error << ": " << lodepng_error_text(error) << std::endl; return 0; } - + buffer.clear(); - + state.encoder.text_compression = 1; - + error = lodepng::encode(buffer, image, w, h, state); - if(error) - { + if(error) { std::cout << "encoder error " << error << ": " << lodepng_error_text(error) << std::endl; return 0; } - + lodepng::save_file(buffer, argv[2]); } diff --git a/examples/example_sdl.c b/examples/example_sdl.c index e4ae3de5..874bc4c1 100644 --- a/examples/example_sdl.c +++ b/examples/example_sdl.c @@ -42,8 +42,7 @@ Press any key to see next image, or esc to quit. #include /*shows image with SDL. Returns 1 if user wants to fully quit, 0 if user wants to see next image.*/ -int show(const char* filename) -{ +int show(const char* filename) { unsigned error; unsigned char* image; unsigned w, h, x, y; @@ -58,8 +57,7 @@ int show(const char* filename) error = lodepng_decode32_file(&image, &w, &h, filename); /*stop if there is an error*/ - if(error) - { + if(error) { printf("decoder error %u: %s\n", error, lodepng_error_text(error)); return 0; } @@ -70,14 +68,12 @@ int show(const char* filename) if(h / 1024 >= jump) jump = h / 1024 + 1; /*init SDL*/ - if(SDL_Init(SDL_INIT_VIDEO) < 0) - { + if(SDL_Init(SDL_INIT_VIDEO) < 0) { printf("Error, SDL video init failed\n"); return 0; } scr = SDL_SetVideoMode(w / jump, h / jump, 32, SDL_HWSURFACE); - if(!scr) - { + if(!scr) { printf("Error, no SDL screen\n"); return 0; } @@ -85,8 +81,7 @@ int show(const char* filename) /*plot the pixels of the PNG file*/ for(y = 0; y + jump - 1 < h; y += jump) - for(x = 0; x + jump - 1 < w; x += jump) - { + for(x = 0; x + jump - 1 < w; x += jump) { int checkerColor; Uint32* bufp; Uint32 r, g, b, a; @@ -110,10 +105,8 @@ int show(const char* filename) /*pause until you press escape and meanwhile redraw screen*/ done = 0; - while(done == 0) - { - while(SDL_PollEvent(&event)) - { + while(done == 0) { + while(SDL_PollEvent(&event)) { if(event.type == SDL_QUIT) done = 2; else if(SDL_GetKeyState(NULL)[SDLK_ESCAPE]) done = 2; else if(event.type == SDL_KEYDOWN) done = 1; /*press any other key for next image*/ @@ -128,14 +121,12 @@ int show(const char* filename) return done == 2 ? 1 : 0; } -int main(int argc, char* argv[]) -{ +int main(int argc, char* argv[]) { int i; if(argc <= 1) printf("Please enter PNG file name(s) to display\n");; - for(i = 1; i < argc; i++) - { + for(i = 1; i < argc; i++) { if(show(argv[i])) return 0; } return 0; diff --git a/examples/example_sdl.cpp b/examples/example_sdl.cpp index 0c68ef5e..dc7dee28 100644 --- a/examples/example_sdl.cpp +++ b/examples/example_sdl.cpp @@ -39,22 +39,19 @@ Press any key to see next image, or esc to quit. #include #include -int show(const std::string& caption, const unsigned char* rgba, unsigned w, unsigned h) -{ +int show(const std::string& caption, const unsigned char* rgba, unsigned w, unsigned h) { //avoid too large window size by downscaling large image unsigned jump = 1; if(w / 1024 >= jump) jump = w / 1024 + 1; if(h / 1024 >= jump) jump = h / 1024 + 1; //init SDL - if(SDL_Init(SDL_INIT_VIDEO) < 0) - { + if(SDL_Init(SDL_INIT_VIDEO) < 0) { std::cout << "error, SDL video init failed" << std::endl; return 0; } SDL_Surface* scr = SDL_SetVideoMode(w / jump, h / jump, 32, SDL_HWSURFACE); - if(!scr) - { + if(!scr) { std::cout << "error, no SDL screen" << std::endl; return 0; } @@ -62,8 +59,7 @@ int show(const std::string& caption, const unsigned char* rgba, unsigned w, unsi //plot the pixels of the PNG file for(unsigned y = 0; y + jump - 1 < h; y += jump) - for(unsigned x = 0; x + jump - 1 < w; x += jump) - { + for(unsigned x = 0; x + jump - 1 < w; x += jump) { //get RGBA components Uint32 r = rgba[4 * y * w + 4 * x + 0]; //red Uint32 g = rgba[4 * y * w + 4 * x + 1]; //green @@ -85,10 +81,8 @@ int show(const std::string& caption, const unsigned char* rgba, unsigned w, unsi //pause until you press escape and meanwhile redraw screen SDL_Event event; int done = 0; - while(done == 0) - { - while(SDL_PollEvent(&event)) - { + while(done == 0) { + while(SDL_PollEvent(&event)) { if(event.type == SDL_QUIT) done = 2; else if(SDL_GetKeyState(NULL)[SDLK_ESCAPE]) done = 2; else if(event.type == SDL_KEYDOWN) done = 1; //press any other key for next image @@ -102,8 +96,7 @@ int show(const std::string& caption, const unsigned char* rgba, unsigned w, unsi } /*shows image with SDL. Returns 1 if user wants to fully quit, 0 if user wants to see next image.*/ -int showfile(const char* filename) -{ +int showfile(const char* filename) { std::cout << "showing " << filename << std::endl; std::vector buffer, image; @@ -112,8 +105,7 @@ int showfile(const char* filename) unsigned error = lodepng::decode(image, w, h, buffer); //decode the png //stop if there is an error - if(error) - { + if(error) { std::cout << "decoder error " << error << ": " << lodepng_error_text(error) << std::endl; return 0; } @@ -121,12 +113,10 @@ int showfile(const char* filename) return show(filename, &image[0], w, h); } -int main(int argc, char* argv[]) -{ +int main(int argc, char* argv[]) { if(argc <= 1) std::cout << "Please enter PNG file name(s) to display" << std::endl; - for(int i = 1; i < argc; i++) - { + for(int i = 1; i < argc; i++) { if(showfile(argv[i])) return 0; } } diff --git a/lodepng.cpp b/lodepng.cpp index 05287bbf..9128a9b6 100644 --- a/lodepng.cpp +++ b/lodepng.cpp @@ -1,5 +1,5 @@ /* -LodePNG version 20180910 +LodePNG version 20181230 Copyright (c) 2005-2018 Lode Vandevenne @@ -39,7 +39,7 @@ Rename this file to lodepng.cpp to use it for C++, or to lodepng.c to use it for #pragma warning( disable : 4996 ) /*VS does not like fopen, but fopen_s is not standard C so unusable here*/ #endif /*_MSC_VER */ -const char* LODEPNG_VERSION_STRING = "20180910"; +const char* LODEPNG_VERSION_STRING = "20181230"; /* This source file is built up in the following large parts. The code sections @@ -60,24 +60,21 @@ lodepng source code. Don't forget to remove "static" if you copypaste them from here.*/ #ifdef LODEPNG_COMPILE_ALLOCATORS -static void* lodepng_malloc(size_t size) -{ +static void* lodepng_malloc(size_t size) { #ifdef LODEPNG_MAX_ALLOC if(size > LODEPNG_MAX_ALLOC) return 0; #endif return malloc(size); } -static void* lodepng_realloc(void* ptr, size_t new_size) -{ +static void* lodepng_realloc(void* ptr, size_t new_size) { #ifdef LODEPNG_MAX_ALLOC if(new_size > LODEPNG_MAX_ALLOC) return 0; #endif return realloc(ptr, new_size); } -static void lodepng_free(void* ptr) -{ +static void lodepng_free(void* ptr) { free(ptr); } #else /*LODEPNG_COMPILE_ALLOCATORS*/ @@ -102,8 +99,7 @@ It makes the error handling code shorter and more readable. Example: if(!uivector_resizev(&frequencies_ll, 286, 0)) ERROR_BREAK(83); */ -#define CERROR_BREAK(errorvar, code)\ -{\ +#define CERROR_BREAK(errorvar, code){\ errorvar = code;\ break;\ } @@ -112,22 +108,19 @@ Example: if(!uivector_resizev(&frequencies_ll, 286, 0)) ERROR_BREAK(83); #define ERROR_BREAK(code) CERROR_BREAK(error, code) /*Set error var to the error code, and return it.*/ -#define CERROR_RETURN_ERROR(errorvar, code)\ -{\ +#define CERROR_RETURN_ERROR(errorvar, code){\ errorvar = code;\ return code;\ } /*Try the code, if it returns error, also return the error.*/ -#define CERROR_TRY_RETURN(call)\ -{\ +#define CERROR_TRY_RETURN(call){\ unsigned error = call;\ if(error) return error;\ } /*Set error var to the error code, and return from the void function.*/ -#define CERROR_RETURN(errorvar, code)\ -{\ +#define CERROR_RETURN(errorvar, code){\ errorvar = code;\ return;\ } @@ -143,29 +136,24 @@ About uivector, ucvector and string: #ifdef LODEPNG_COMPILE_ZLIB /*dynamic vector of unsigned ints*/ -typedef struct uivector -{ +typedef struct uivector { unsigned* data; size_t size; /*size in number of unsigned longs*/ size_t allocsize; /*allocated size in bytes*/ } uivector; -static void uivector_cleanup(void* p) -{ +static void uivector_cleanup(void* p) { ((uivector*)p)->size = ((uivector*)p)->allocsize = 0; lodepng_free(((uivector*)p)->data); ((uivector*)p)->data = NULL; } /*returns 1 if success, 0 if failure ==> nothing done*/ -static unsigned uivector_reserve(uivector* p, size_t allocsize) -{ - if(allocsize > p->allocsize) - { +static unsigned uivector_reserve(uivector* p, size_t allocsize) { + if(allocsize > p->allocsize) { size_t newsize = (allocsize > p->allocsize * 2) ? allocsize : (allocsize * 3 / 2); void* data = lodepng_realloc(p->data, newsize); - if(data) - { + if(data) { p->allocsize = newsize; p->data = (unsigned*)data; } @@ -175,32 +163,28 @@ static unsigned uivector_reserve(uivector* p, size_t allocsize) } /*returns 1 if success, 0 if failure ==> nothing done*/ -static unsigned uivector_resize(uivector* p, size_t size) -{ +static unsigned uivector_resize(uivector* p, size_t size) { if(!uivector_reserve(p, size * sizeof(unsigned))) return 0; p->size = size; return 1; /*success*/ } /*resize and give all new elements the value*/ -static unsigned uivector_resizev(uivector* p, size_t size, unsigned value) -{ +static unsigned uivector_resizev(uivector* p, size_t size, unsigned value) { size_t oldsize = p->size, i; if(!uivector_resize(p, size)) return 0; for(i = oldsize; i < size; ++i) p->data[i] = value; return 1; } -static void uivector_init(uivector* p) -{ +static void uivector_init(uivector* p) { p->data = NULL; p->size = p->allocsize = 0; } #ifdef LODEPNG_COMPILE_ENCODER /*returns 1 if success, 0 if failure ==> nothing done*/ -static unsigned uivector_push_back(uivector* p, unsigned c) -{ +static unsigned uivector_push_back(uivector* p, unsigned c) { if(!uivector_resize(p, p->size + 1)) return 0; p->data[p->size - 1] = c; return 1; @@ -211,22 +195,18 @@ static unsigned uivector_push_back(uivector* p, unsigned c) /* /////////////////////////////////////////////////////////////////////////// */ /*dynamic vector of unsigned chars*/ -typedef struct ucvector -{ +typedef struct ucvector { unsigned char* data; size_t size; /*used size*/ size_t allocsize; /*allocated size*/ } ucvector; /*returns 1 if success, 0 if failure ==> nothing done*/ -static unsigned ucvector_reserve(ucvector* p, size_t allocsize) -{ - if(allocsize > p->allocsize) - { +static unsigned ucvector_reserve(ucvector* p, size_t allocsize) { + if(allocsize > p->allocsize) { size_t newsize = (allocsize > p->allocsize * 2) ? allocsize : (allocsize * 3 / 2); void* data = lodepng_realloc(p->data, newsize); - if(data) - { + if(data) { p->allocsize = newsize; p->data = (unsigned char*)data; } @@ -236,8 +216,7 @@ static unsigned ucvector_reserve(ucvector* p, size_t allocsize) } /*returns 1 if success, 0 if failure ==> nothing done*/ -static unsigned ucvector_resize(ucvector* p, size_t size) -{ +static unsigned ucvector_resize(ucvector* p, size_t size) { if(!ucvector_reserve(p, size * sizeof(unsigned char))) return 0; p->size = size; return 1; /*success*/ @@ -245,15 +224,13 @@ static unsigned ucvector_resize(ucvector* p, size_t size) #ifdef LODEPNG_COMPILE_PNG -static void ucvector_cleanup(void* p) -{ +static void ucvector_cleanup(void* p) { ((ucvector*)p)->size = ((ucvector*)p)->allocsize = 0; lodepng_free(((ucvector*)p)->data); ((ucvector*)p)->data = NULL; } -static void ucvector_init(ucvector* p) -{ +static void ucvector_init(ucvector* p) { p->data = NULL; p->size = p->allocsize = 0; } @@ -262,8 +239,7 @@ static void ucvector_init(ucvector* p) #ifdef LODEPNG_COMPILE_ZLIB /*you can both convert from vector to buffer&size and vica versa. If you use init_buffer to take over a buffer and size, it is not needed to use cleanup*/ -static void ucvector_init_buffer(ucvector* p, unsigned char* buffer, size_t size) -{ +static void ucvector_init_buffer(ucvector* p, unsigned char* buffer, size_t size) { p->data = buffer; p->allocsize = p->size = size; } @@ -271,8 +247,7 @@ static void ucvector_init_buffer(ucvector* p, unsigned char* buffer, size_t size #if (defined(LODEPNG_COMPILE_PNG) && defined(LODEPNG_COMPILE_ANCILLARY_CHUNKS)) || defined(LODEPNG_COMPILE_ENCODER) /*returns 1 if success, 0 if failure ==> nothing done*/ -static unsigned ucvector_push_back(ucvector* p, unsigned char c) -{ +static unsigned ucvector_push_back(ucvector* p, unsigned char c) { if(!ucvector_resize(p, p->size + 1)) return 0; p->data[p->size - 1] = c; return 1; @@ -286,22 +261,18 @@ static unsigned ucvector_push_back(ucvector* p, unsigned char c) #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /*free string pointer and set it to NULL*/ -static void string_cleanup(char** out) -{ +static void string_cleanup(char** out) { lodepng_free(*out); *out = NULL; } /* dynamically allocates a new string with a copy of the null terminated input text */ -static char* alloc_string(const char* in) -{ +static char* alloc_string(const char* in) { size_t insize = strlen(in); char* out = (char*)lodepng_malloc(insize + 1); - if(out) - { + if(out) { size_t i; - for(i = 0; i != insize; ++i) - { + for(i = 0; i != insize; ++i) { out[i] = in[i]; } out[i] = 0; @@ -313,15 +284,13 @@ static char* alloc_string(const char* in) /* ////////////////////////////////////////////////////////////////////////// */ -unsigned lodepng_read32bitInt(const unsigned char* buffer) -{ +unsigned lodepng_read32bitInt(const unsigned char* buffer) { return (unsigned)((buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]); } #if defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER) /*buffer must have at least 4 allocated bytes available*/ -static void lodepng_set32bitInt(unsigned char* buffer, unsigned value) -{ +static void lodepng_set32bitInt(unsigned char* buffer, unsigned value) { buffer[0] = (unsigned char)((value >> 24) & 0xff); buffer[1] = (unsigned char)((value >> 16) & 0xff); buffer[2] = (unsigned char)((value >> 8) & 0xff); @@ -330,8 +299,7 @@ static void lodepng_set32bitInt(unsigned char* buffer, unsigned value) #endif /*defined(LODEPNG_COMPILE_PNG) || defined(LODEPNG_COMPILE_ENCODER)*/ #ifdef LODEPNG_COMPILE_ENCODER -static void lodepng_add32bitInt(ucvector* buffer, unsigned value) -{ +static void lodepng_add32bitInt(ucvector* buffer, unsigned value) { ucvector_resize(buffer, buffer->size + 4); /*todo: give error if resize failed*/ lodepng_set32bitInt(&buffer->data[buffer->size - 4], value); } @@ -344,15 +312,13 @@ static void lodepng_add32bitInt(ucvector* buffer, unsigned value) #ifdef LODEPNG_COMPILE_DISK /* returns negative value on error. This should be pure C compatible, so no fstat. */ -static long lodepng_filesize(const char* filename) -{ +static long lodepng_filesize(const char* filename) { FILE* file; long size; file = fopen(filename, "rb"); if(!file) return -1; - if(fseek(file, 0, SEEK_END) != 0) - { + if(fseek(file, 0, SEEK_END) != 0) { fclose(file); return -1; } @@ -366,8 +332,7 @@ static long lodepng_filesize(const char* filename) } /* load file into buffer that already has the correct allocated size. Returns error code.*/ -static unsigned lodepng_buffer_file(unsigned char* out, size_t size, const char* filename) -{ +static unsigned lodepng_buffer_file(unsigned char* out, size_t size, const char* filename) { FILE* file; size_t readsize; file = fopen(filename, "rb"); @@ -380,8 +345,7 @@ static unsigned lodepng_buffer_file(unsigned char* out, size_t size, const char* return 0; } -unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename) -{ +unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* filename) { long size = lodepng_filesize(filename); if (size < 0) return 78; *outsize = (size_t)size; @@ -393,8 +357,7 @@ unsigned lodepng_load_file(unsigned char** out, size_t* outsize, const char* fil } /*write given buffer to the file, overwriting the file, it doesn't append to it.*/ -unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename) -{ +unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const char* filename) { FILE* file; file = fopen(filename, "wb" ); if(!file) return 79; @@ -414,8 +377,7 @@ unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const #ifdef LODEPNG_COMPILE_ZLIB #ifdef LODEPNG_COMPILE_ENCODER /*TODO: this ignores potential out of memory errors*/ -#define addBitToStream(/*size_t**/ bitpointer, /*ucvector**/ bitstream, /*unsigned char*/ bit)\ -{\ +#define addBitToStream(/*size_t**/ bitpointer, /*ucvector**/ bitstream, /*unsigned char*/ bit){\ /*add a new byte at the end*/\ if(((*bitpointer) & 7) == 0) ucvector_push_back(bitstream, (unsigned char)0);\ /*earlier bit of huffman code is in a lesser significant bit of an earlier byte*/\ @@ -423,14 +385,12 @@ unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const ++(*bitpointer);\ } -static void addBitsToStream(size_t* bitpointer, ucvector* bitstream, unsigned value, size_t nbits) -{ +static void addBitsToStream(size_t* bitpointer, ucvector* bitstream, unsigned value, size_t nbits) { size_t i; for(i = 0; i != nbits; ++i) addBitToStream(bitpointer, bitstream, (unsigned char)((value >> i) & 1)); } -static void addBitsToStreamReversed(size_t* bitpointer, ucvector* bitstream, unsigned value, size_t nbits) -{ +static void addBitsToStreamReversed(size_t* bitpointer, ucvector* bitstream, unsigned value, size_t nbits) { size_t i; for(i = 0; i != nbits; ++i) addBitToStream(bitpointer, bitstream, (unsigned char)((value >> (nbits - 1 - i)) & 1)); } @@ -440,18 +400,15 @@ static void addBitsToStreamReversed(size_t* bitpointer, ucvector* bitstream, uns #define READBIT(bitpointer, bitstream) ((bitstream[bitpointer >> 3] >> (bitpointer & 0x7)) & (unsigned char)1) -static unsigned char readBitFromStream(size_t* bitpointer, const unsigned char* bitstream) -{ +static unsigned char readBitFromStream(size_t* bitpointer, const unsigned char* bitstream) { unsigned char result = (unsigned char)(READBIT(*bitpointer, bitstream)); ++(*bitpointer); return result; } -static unsigned readBitsFromStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits) -{ +static unsigned readBitsFromStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits) { unsigned result = 0, i; - for(i = 0; i != nbits; ++i) - { + for(i = 0; i != nbits; ++i) { result += ((unsigned)READBIT(*bitpointer, bitstream)) << i; ++(*bitpointer); } @@ -502,8 +459,7 @@ static const unsigned CLCL_ORDER[NUM_CODE_LENGTH_CODES] /* Huffman tree struct, containing multiple representations of the tree */ -typedef struct HuffmanTree -{ +typedef struct HuffmanTree { unsigned* tree2d; unsigned* tree1d; unsigned* lengths; /*the lengths of the codes of the 1d-tree*/ @@ -513,34 +469,29 @@ typedef struct HuffmanTree /*function used for debug purposes to draw the tree in ascii art with C++*/ /* -static void HuffmanTree_draw(HuffmanTree* tree) -{ +static void HuffmanTree_draw(HuffmanTree* tree) { std::cout << "tree. length: " << tree->numcodes << " maxbitlen: " << tree->maxbitlen << std::endl; - for(size_t i = 0; i != tree->tree1d.size; ++i) - { + for(size_t i = 0; i != tree->tree1d.size; ++i) { if(tree->lengths.data[i]) std::cout << i << " " << tree->tree1d.data[i] << " " << tree->lengths.data[i] << std::endl; } std::cout << std::endl; }*/ -static void HuffmanTree_init(HuffmanTree* tree) -{ +static void HuffmanTree_init(HuffmanTree* tree) { tree->tree2d = 0; tree->tree1d = 0; tree->lengths = 0; } -static void HuffmanTree_cleanup(HuffmanTree* tree) -{ +static void HuffmanTree_cleanup(HuffmanTree* tree) { lodepng_free(tree->tree2d); lodepng_free(tree->tree1d); lodepng_free(tree->lengths); } /*the tree representation used by the decoder. return value is error*/ -static unsigned HuffmanTree_make2DTree(HuffmanTree* tree) -{ +static unsigned HuffmanTree_make2DTree(HuffmanTree* tree) { unsigned nodefilled = 0; /*up to which node it is filled*/ unsigned treepos = 0; /*position in the tree (1 of the numcodes columns)*/ unsigned n, i; @@ -558,27 +509,20 @@ static unsigned HuffmanTree_make2DTree(HuffmanTree* tree) There is only memory for such good tree currently, if there are more nodes (due to too long length codes), error 55 will happen */ - for(n = 0; n < tree->numcodes * 2; ++n) - { + for(n = 0; n < tree->numcodes * 2; ++n) { tree->tree2d[n] = 32767; /*32767 here means the tree2d isn't filled there yet*/ } - for(n = 0; n < tree->numcodes; ++n) /*the codes*/ - { - for(i = 0; i != tree->lengths[n]; ++i) /*the bits for this code*/ - { + for(n = 0; n < tree->numcodes; ++n) /*the codes*/ { + for(i = 0; i != tree->lengths[n]; ++i) /*the bits for this code*/ { unsigned char bit = (unsigned char)((tree->tree1d[n] >> (tree->lengths[n] - i - 1)) & 1); /*oversubscribed, see comment in lodepng_error_text*/ if(treepos > 2147483647 || treepos + 2 > tree->numcodes) return 55; - if(tree->tree2d[2 * treepos + bit] == 32767) /*not yet filled in*/ - { - if(i + 1 == tree->lengths[n]) /*last bit*/ - { + if(tree->tree2d[2 * treepos + bit] == 32767) /*not yet filled in*/ { + if(i + 1 == tree->lengths[n]) /*last bit*/ { tree->tree2d[2 * treepos + bit] = n; /*put the current code in it*/ treepos = 0; - } - else - { + } else { /*put address of the next step in here, first that address has to be found of course (it's just nodefilled + 1)...*/ ++nodefilled; @@ -591,8 +535,7 @@ static unsigned HuffmanTree_make2DTree(HuffmanTree* tree) } } - for(n = 0; n < tree->numcodes * 2; ++n) - { + for(n = 0; n < tree->numcodes * 2; ++n) { if(tree->tree2d[n] == 32767) tree->tree2d[n] = 0; /*remove possible remaining 32767's*/ } @@ -604,8 +547,7 @@ Second step for the ...makeFromLengths and ...makeFromFrequencies functions. numcodes, lengths and maxbitlen must already be filled in correctly. return value is error. */ -static unsigned HuffmanTree_makeFromLengths2(HuffmanTree* tree) -{ +static unsigned HuffmanTree_makeFromLengths2(HuffmanTree* tree) { uivector blcount; uivector nextcode; unsigned error = 0; @@ -621,18 +563,15 @@ static unsigned HuffmanTree_makeFromLengths2(HuffmanTree* tree) || !uivector_resizev(&nextcode, tree->maxbitlen + 1, 0)) error = 83; /*alloc fail*/ - if(!error) - { + if(!error) { /*step 1: count number of instances of each code length*/ for(bits = 0; bits != tree->numcodes; ++bits) ++blcount.data[tree->lengths[bits]]; /*step 2: generate the nextcode values*/ - for(bits = 1; bits <= tree->maxbitlen; ++bits) - { + for(bits = 1; bits <= tree->maxbitlen; ++bits) { nextcode.data[bits] = (nextcode.data[bits - 1] + blcount.data[bits - 1]) << 1; } /*step 3: generate all the codes*/ - for(n = 0; n != tree->numcodes; ++n) - { + for(n = 0; n != tree->numcodes; ++n) { if(tree->lengths[n] != 0) tree->tree1d[n] = nextcode.data[tree->lengths[n]]++; } } @@ -650,8 +589,7 @@ by Deflate. maxbitlen is the maximum bits that a code in the tree can have. return value is error. */ static unsigned HuffmanTree_makeFromLengths(HuffmanTree* tree, const unsigned* bitlen, - size_t numcodes, unsigned maxbitlen) -{ + size_t numcodes, unsigned maxbitlen) { unsigned i; tree->lengths = (unsigned*)lodepng_malloc(numcodes * sizeof(unsigned)); if(!tree->lengths) return 83; /*alloc fail*/ @@ -667,8 +605,7 @@ static unsigned HuffmanTree_makeFromLengths(HuffmanTree* tree, const unsigned* b Jyrki Katajainen, Alistair Moffat, Andrew Turpin, 1995.*/ /*chain node for boundary package merge*/ -typedef struct BPMNode -{ +typedef struct BPMNode { int weight; /*the sum of all weights in this chain*/ unsigned index; /*index of this leaf node (called "count" in the paper)*/ struct BPMNode* tail; /*the next nodes in this chain (null if last)*/ @@ -676,8 +613,7 @@ typedef struct BPMNode } BPMNode; /*lists of chains*/ -typedef struct BPMLists -{ +typedef struct BPMLists { /*memory pool*/ unsigned memsize; BPMNode* memory; @@ -691,26 +627,22 @@ typedef struct BPMLists } BPMLists; /*creates a new chain node with the given parameters, from the memory in the lists */ -static BPMNode* bpmnode_create(BPMLists* lists, int weight, unsigned index, BPMNode* tail) -{ +static BPMNode* bpmnode_create(BPMLists* lists, int weight, unsigned index, BPMNode* tail) { unsigned i; BPMNode* result; /*memory full, so garbage collect*/ - if(lists->nextfree >= lists->numfree) - { + if(lists->nextfree >= lists->numfree) { /*mark only those that are in use*/ for(i = 0; i != lists->memsize; ++i) lists->memory[i].in_use = 0; - for(i = 0; i != lists->listsize; ++i) - { + for(i = 0; i != lists->listsize; ++i) { BPMNode* node; for(node = lists->chains0[i]; node != 0; node = node->tail) node->in_use = 1; for(node = lists->chains1[i]; node != 0; node = node->tail) node->in_use = 1; } /*collect those that are free*/ lists->numfree = 0; - for(i = 0; i != lists->memsize; ++i) - { + for(i = 0; i != lists->memsize; ++i) { if(!lists->memory[i].in_use) lists->freelist[lists->numfree++] = &lists->memory[i]; } lists->nextfree = 0; @@ -724,22 +656,18 @@ static BPMNode* bpmnode_create(BPMLists* lists, int weight, unsigned index, BPMN } /*sort the leaves with stable mergesort*/ -static void bpmnode_sort(BPMNode* leaves, size_t num) -{ +static void bpmnode_sort(BPMNode* leaves, size_t num) { BPMNode* mem = (BPMNode*)lodepng_malloc(sizeof(*leaves) * num); size_t width, counter = 0; - for(width = 1; width < num; width *= 2) - { + for(width = 1; width < num; width *= 2) { BPMNode* a = (counter & 1) ? mem : leaves; BPMNode* b = (counter & 1) ? leaves : mem; size_t p; - for(p = 0; p < num; p += 2 * width) - { + for(p = 0; p < num; p += 2 * width) { size_t q = (p + width > num) ? num : (p + width); size_t r = (p + 2 * width > num) ? num : (p + 2 * width); size_t i = p, j = q, k; - for(k = p; k < r; k++) - { + for(k = p; k < r; k++) { if(i < q && (j >= r || a[i].weight <= a[j].weight)) b[k] = a[i++]; else b[k] = a[j++]; } @@ -751,31 +679,25 @@ static void bpmnode_sort(BPMNode* leaves, size_t num) } /*Boundary Package Merge step, numpresent is the amount of leaves, and c is the current chain.*/ -static void boundaryPM(BPMLists* lists, BPMNode* leaves, size_t numpresent, int c, int num) -{ +static void boundaryPM(BPMLists* lists, BPMNode* leaves, size_t numpresent, int c, int num) { unsigned lastindex = lists->chains1[c]->index; - if(c == 0) - { + if(c == 0) { if(lastindex >= numpresent) return; lists->chains0[c] = lists->chains1[c]; lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, 0); - } - else - { + } else { /*sum of the weights of the head nodes of the previous lookahead chains.*/ int sum = lists->chains0[c - 1]->weight + lists->chains1[c - 1]->weight; lists->chains0[c] = lists->chains1[c]; - if(lastindex < numpresent && sum > leaves[lastindex].weight) - { + if(lastindex < numpresent && sum > leaves[lastindex].weight) { lists->chains1[c] = bpmnode_create(lists, leaves[lastindex].weight, lastindex + 1, lists->chains1[c]->tail); return; } lists->chains1[c] = bpmnode_create(lists, sum, lastindex, lists->chains1[c - 1]); /*in the end we are only interested in the chain of the last list, so no need to recurse if we're at the last one (this gives measurable speedup)*/ - if(num + 1 < (int)(2 * numpresent - 2)) - { + if(num + 1 < (int)(2 * numpresent - 2)) { boundaryPM(lists, leaves, numpresent, c - 1, num); boundaryPM(lists, leaves, numpresent, c - 1, num); } @@ -783,8 +705,7 @@ static void boundaryPM(BPMLists* lists, BPMNode* leaves, size_t numpresent, int } unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequencies, - size_t numcodes, unsigned maxbitlen) -{ + size_t numcodes, unsigned maxbitlen) { unsigned error = 0; unsigned i; size_t numpresent = 0; /*number of symbols with non-zero frequency*/ @@ -796,10 +717,8 @@ unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequen leaves = (BPMNode*)lodepng_malloc(numcodes * sizeof(*leaves)); if(!leaves) return 83; /*alloc fail*/ - for(i = 0; i != numcodes; ++i) - { - if(frequencies[i] > 0) - { + for(i = 0; i != numcodes; ++i) { + if(frequencies[i] > 0) { leaves[numpresent].weight = (int)frequencies[i]; leaves[numpresent].index = i; ++numpresent; @@ -813,17 +732,12 @@ unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequen make these work as well ensure there are at least two symbols. The Package-Merge code below also doesn't work correctly if there's only one symbol, it'd give it the theoritical 0 bits but in practice zlib wants 1 bit*/ - if(numpresent == 0) - { + if(numpresent == 0) { lengths[0] = lengths[1] = 1; /*note that for RFC 1951 section 3.2.7, only lengths[0] = 1 is needed*/ - } - else if(numpresent == 1) - { + } else if(numpresent == 1) { lengths[leaves[0].index] = 1; lengths[leaves[0].index == 0 ? 1 : 0] = 1; - } - else - { + } else { BPMLists lists; BPMNode* node; @@ -839,15 +753,13 @@ unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequen lists.chains1 = (BPMNode**)lodepng_malloc(lists.listsize * sizeof(BPMNode*)); if(!lists.memory || !lists.freelist || !lists.chains0 || !lists.chains1) error = 83; /*alloc fail*/ - if(!error) - { + if(!error) { for(i = 0; i != lists.memsize; ++i) lists.freelist[i] = &lists.memory[i]; bpmnode_create(&lists, leaves[0].weight, 1, 0); bpmnode_create(&lists, leaves[1].weight, 2, 0); - for(i = 0; i != lists.listsize; ++i) - { + for(i = 0; i != lists.listsize; ++i) { lists.chains0[i] = &lists.memory[0]; lists.chains1[i] = &lists.memory[1]; } @@ -855,8 +767,7 @@ unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequen /*each boundaryPM call adds one chain to the last list, and we need 2 * numpresent - 2 chains.*/ for(i = 2; i != 2 * numpresent - 2; ++i) boundaryPM(&lists, leaves, numpresent, (int)maxbitlen - 1, (int)i); - for(node = lists.chains1[maxbitlen - 1]; node; node = node->tail) - { + for(node = lists.chains1[maxbitlen - 1]; node; node = node->tail) { for(i = 0; i != node->index; ++i) ++lengths[leaves[i].index]; } } @@ -873,8 +784,7 @@ unsigned lodepng_huffman_code_lengths(unsigned* lengths, const unsigned* frequen /*Create the Huffman tree given the symbol frequencies*/ static unsigned HuffmanTree_makeFromFrequencies(HuffmanTree* tree, const unsigned* frequencies, - size_t mincodes, size_t numcodes, unsigned maxbitlen) -{ + size_t mincodes, size_t numcodes, unsigned maxbitlen) { unsigned error = 0; while(!frequencies[numcodes - 1] && numcodes > mincodes) --numcodes; /*trim zeroes*/ tree->maxbitlen = maxbitlen; @@ -889,20 +799,17 @@ static unsigned HuffmanTree_makeFromFrequencies(HuffmanTree* tree, const unsigne return error; } -static unsigned HuffmanTree_getCode(const HuffmanTree* tree, unsigned index) -{ +static unsigned HuffmanTree_getCode(const HuffmanTree* tree, unsigned index) { return tree->tree1d[index]; } -static unsigned HuffmanTree_getLength(const HuffmanTree* tree, unsigned index) -{ +static unsigned HuffmanTree_getLength(const HuffmanTree* tree, unsigned index) { return tree->lengths[index]; } #endif /*LODEPNG_COMPILE_ENCODER*/ /*get the literal and length code tree of a deflated block with fixed tree, as per the deflate specification*/ -static unsigned generateFixedLitLenTree(HuffmanTree* tree) -{ +static unsigned generateFixedLitLenTree(HuffmanTree* tree) { unsigned i, error = 0; unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DEFLATE_CODE_SYMBOLS * sizeof(unsigned)); if(!bitlen) return 83; /*alloc fail*/ @@ -920,8 +827,7 @@ static unsigned generateFixedLitLenTree(HuffmanTree* tree) } /*get the distance code tree of a deflated block with fixed tree, as specified in the deflate specification*/ -static unsigned generateFixedDistanceTree(HuffmanTree* tree) -{ +static unsigned generateFixedDistanceTree(HuffmanTree* tree) { unsigned i, error = 0; unsigned* bitlen = (unsigned*)lodepng_malloc(NUM_DISTANCE_SYMBOLS * sizeof(unsigned)); if(!bitlen) return 83; /*alloc fail*/ @@ -941,11 +847,9 @@ returns the code, or (unsigned)(-1) if error happened inbitlength is the length of the complete buffer, in bits (so its byte length times 8) */ static unsigned huffmanDecodeSymbol(const unsigned char* in, size_t* bp, - const HuffmanTree* codetree, size_t inbitlength) -{ + const HuffmanTree* codetree, size_t inbitlength) { unsigned treepos = 0, ct; - for(;;) - { + for(;;) { if(*bp >= inbitlength) return (unsigned)(-1); /*error: end of input memory reached without endcode*/ /* decode the symbol from the tree. The "readBitFromStream" code is inlined in @@ -968,8 +872,7 @@ static unsigned huffmanDecodeSymbol(const unsigned char* in, size_t* bp, /* ////////////////////////////////////////////////////////////////////////// */ /*get the tree of a deflated block with fixed tree, as specified in the deflate specification*/ -static void getTreeInflateFixed(HuffmanTree* tree_ll, HuffmanTree* tree_d) -{ +static void getTreeInflateFixed(HuffmanTree* tree_ll, HuffmanTree* tree_d) { /*TODO: check for out of memory errors*/ generateFixedLitLenTree(tree_ll); generateFixedDistanceTree(tree_d); @@ -977,8 +880,7 @@ static void getTreeInflateFixed(HuffmanTree* tree_ll, HuffmanTree* tree_d) /*get the tree of a deflated block with dynamic tree, the tree itself is also Huffman compressed with a known tree*/ static unsigned getTreeInflateDynamic(HuffmanTree* tree_ll, HuffmanTree* tree_d, - const unsigned char* in, size_t* bp, size_t inlength) -{ + const unsigned char* in, size_t* bp, size_t inlength) { /*make sure that length values that aren't filled in will be 0, or a wrong tree will be generated*/ unsigned error = 0; unsigned n, HLIT, HDIST, HCLEN, i; @@ -1004,15 +906,13 @@ static unsigned getTreeInflateDynamic(HuffmanTree* tree_ll, HuffmanTree* tree_d, HuffmanTree_init(&tree_cl); - while(!error) - { + while(!error) { /*read the code length codes out of 3 * (amount of code length codes) bits*/ bitlen_cl = (unsigned*)lodepng_malloc(NUM_CODE_LENGTH_CODES * sizeof(unsigned)); if(!bitlen_cl) ERROR_BREAK(83 /*alloc fail*/); - for(i = 0; i != NUM_CODE_LENGTH_CODES; ++i) - { + for(i = 0; i != NUM_CODE_LENGTH_CODES; ++i) { if(i < HCLEN) bitlen_cl[CLCL_ORDER[i]] = readBitsFromStream(bp, in, 3); else bitlen_cl[CLCL_ORDER[i]] = 0; /*if not, it must stay 0*/ } @@ -1029,17 +929,13 @@ static unsigned getTreeInflateDynamic(HuffmanTree* tree_ll, HuffmanTree* tree_d, /*i is the current symbol we're reading in the part that contains the code lengths of lit/len and dist codes*/ i = 0; - while(i < HLIT + HDIST) - { + while(i < HLIT + HDIST) { unsigned code = huffmanDecodeSymbol(in, bp, &tree_cl, inbitlength); - if(code <= 15) /*a length code*/ - { + if(code <= 15) /*a length code*/ { if(i < HLIT) bitlen_ll[i] = code; else bitlen_d[i - HLIT] = code; ++i; - } - else if(code == 16) /*repeat previous*/ - { + } else if(code == 16) /*repeat previous*/ { unsigned replength = 3; /*read in the 2 bits that indicate repeat length (3-6)*/ unsigned value; /*set value to the previous code*/ @@ -1051,50 +947,40 @@ static unsigned getTreeInflateDynamic(HuffmanTree* tree_ll, HuffmanTree* tree_d, if(i < HLIT + 1) value = bitlen_ll[i - 1]; else value = bitlen_d[i - HLIT - 1]; /*repeat this value in the next lengths*/ - for(n = 0; n < replength; ++n) - { + for(n = 0; n < replength; ++n) { if(i >= HLIT + HDIST) ERROR_BREAK(13); /*error: i is larger than the amount of codes*/ if(i < HLIT) bitlen_ll[i] = value; else bitlen_d[i - HLIT] = value; ++i; } - } - else if(code == 17) /*repeat "0" 3-10 times*/ - { + } else if(code == 17) /*repeat "0" 3-10 times*/ { unsigned replength = 3; /*read in the bits that indicate repeat length*/ if((*bp + 3) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/ replength += readBitsFromStream(bp, in, 3); /*repeat this value in the next lengths*/ - for(n = 0; n < replength; ++n) - { + for(n = 0; n < replength; ++n) { if(i >= HLIT + HDIST) ERROR_BREAK(14); /*error: i is larger than the amount of codes*/ if(i < HLIT) bitlen_ll[i] = 0; else bitlen_d[i - HLIT] = 0; ++i; } - } - else if(code == 18) /*repeat "0" 11-138 times*/ - { + } else if(code == 18) /*repeat "0" 11-138 times*/ { unsigned replength = 11; /*read in the bits that indicate repeat length*/ if((*bp + 7) > inbitlength) ERROR_BREAK(50); /*error, bit pointer jumps past memory*/ replength += readBitsFromStream(bp, in, 7); /*repeat this value in the next lengths*/ - for(n = 0; n < replength; ++n) - { + for(n = 0; n < replength; ++n) { if(i >= HLIT + HDIST) ERROR_BREAK(15); /*error: i is larger than the amount of codes*/ if(i < HLIT) bitlen_ll[i] = 0; else bitlen_d[i - HLIT] = 0; ++i; } - } - else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ - { - if(code == (unsigned)(-1)) - { + } else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ { + if(code == (unsigned)(-1)) { /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol (10=no endcode, 11=wrong jump outside of tree)*/ error = (*bp) > inbitlength ? 10 : 11; @@ -1125,8 +1011,7 @@ static unsigned getTreeInflateDynamic(HuffmanTree* tree_ll, HuffmanTree* tree_d, /*inflate a block with dynamic of fixed Huffman tree*/ static unsigned inflateHuffmanBlock(ucvector* out, const unsigned char* in, size_t* bp, - size_t* pos, size_t inlength, unsigned btype) -{ + size_t* pos, size_t inlength, unsigned btype) { unsigned error = 0; HuffmanTree tree_ll; /*the huffman tree for literal and length codes*/ HuffmanTree tree_d; /*the huffman tree for distance codes*/ @@ -1138,19 +1023,15 @@ static unsigned inflateHuffmanBlock(ucvector* out, const unsigned char* in, size if(btype == 1) getTreeInflateFixed(&tree_ll, &tree_d); else if(btype == 2) error = getTreeInflateDynamic(&tree_ll, &tree_d, in, bp, inlength); - while(!error) /*decode all symbols until end reached, breaks at end code*/ - { + while(!error) /*decode all symbols until end reached, breaks at end code*/ { /*code_ll is literal, length or end code*/ unsigned code_ll = huffmanDecodeSymbol(in, bp, &tree_ll, inbitlength); - if(code_ll <= 255) /*literal symbol*/ - { + if(code_ll <= 255) /*literal symbol*/ { /*ucvector_push_back would do the same, but for some reason the two lines below run 10% faster*/ if(!ucvector_resize(out, (*pos) + 1)) ERROR_BREAK(83 /*alloc fail*/); out->data[*pos] = (unsigned char)code_ll; ++(*pos); - } - else if(code_ll >= FIRST_LENGTH_CODE_INDEX && code_ll <= LAST_LENGTH_CODE_INDEX) /*length code*/ - { + } else if(code_ll >= FIRST_LENGTH_CODE_INDEX && code_ll <= LAST_LENGTH_CODE_INDEX) /*length code*/ { unsigned code_d, distance; unsigned numextrabits_l, numextrabits_d; /*extra bits for length and distance*/ size_t start, forward, backward, length; @@ -1165,10 +1046,8 @@ static unsigned inflateHuffmanBlock(ucvector* out, const unsigned char* in, size /*part 3: get distance code*/ code_d = huffmanDecodeSymbol(in, bp, &tree_d, inbitlength); - if(code_d > 29) - { - if(code_d == (unsigned)(-1)) /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ - { + if(code_d > 29) { + if(code_d == (unsigned)(-1)) /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ { /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol (10=no endcode, 11=wrong jump outside of tree)*/ error = (*bp) > inlength * 8 ? 10 : 11; @@ -1190,21 +1069,16 @@ static unsigned inflateHuffmanBlock(ucvector* out, const unsigned char* in, size if(!ucvector_resize(out, (*pos) + length)) ERROR_BREAK(83 /*alloc fail*/); if (distance < length) { - for(forward = 0; forward < length; ++forward) - { + for(forward = 0; forward < length; ++forward) { out->data[(*pos)++] = out->data[backward++]; } } else { memcpy(out->data + *pos, out->data + backward, length); *pos += length; } - } - else if(code_ll == 256) - { + } else if(code_ll == 256) { break; /*end code, break the loop*/ - } - else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ - { + } else /*if(code == (unsigned)(-1))*/ /*huffmanDecodeSymbol returns (unsigned)(-1) in case of error*/ { /*return error code 10 or 11 depending on the situation that happened in huffmanDecodeSymbol (10=no endcode, 11=wrong jump outside of tree)*/ error = ((*bp) > inlength * 8) ? 10 : 11; @@ -1218,8 +1092,7 @@ static unsigned inflateHuffmanBlock(ucvector* out, const unsigned char* in, size return error; } -static unsigned inflateNoCompression(ucvector* out, const unsigned char* in, size_t* bp, size_t* pos, size_t inlength) -{ +static unsigned inflateNoCompression(ucvector* out, const unsigned char* in, size_t* bp, size_t* pos, size_t inlength) { size_t p; unsigned LEN, NLEN, n, error = 0; @@ -1248,8 +1121,7 @@ static unsigned inflateNoCompression(ucvector* out, const unsigned char* in, siz static unsigned lodepng_inflatev(ucvector* out, const unsigned char* in, size_t insize, - const LodePNGDecompressSettings* settings) -{ + const LodePNGDecompressSettings* settings) { /*bit pointer in the "in" data, current byte is bp >> 3, current bit is bp & 0x7 (from lsb to msb of the byte)*/ size_t bp = 0; unsigned BFINAL = 0; @@ -1258,8 +1130,7 @@ static unsigned lodepng_inflatev(ucvector* out, (void)settings; - while(!BFINAL) - { + while(!BFINAL) { unsigned BTYPE; if(bp + 2 >= insize * 8) return 52; /*error, bit pointer will jump past memory*/ BFINAL = readBitFromStream(&bp, in); @@ -1278,8 +1149,7 @@ static unsigned lodepng_inflatev(ucvector* out, unsigned lodepng_inflate(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, - const LodePNGDecompressSettings* settings) -{ + const LodePNGDecompressSettings* settings) { unsigned error; ucvector v; ucvector_init_buffer(&v, *out, *outsize); @@ -1291,14 +1161,10 @@ unsigned lodepng_inflate(unsigned char** out, size_t* outsize, static unsigned inflate(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, - const LodePNGDecompressSettings* settings) -{ - if(settings->custom_inflate) - { + const LodePNGDecompressSettings* settings) { + if(settings->custom_inflate) { return settings->custom_inflate(out, outsize, in, insize, settings); - } - else - { + } else { return lodepng_inflate(out, outsize, in, insize, settings); } } @@ -1314,15 +1180,13 @@ static unsigned inflate(unsigned char** out, size_t* outsize, static const size_t MAX_SUPPORTED_DEFLATE_LENGTH = 258; /*bitlen is the size in bits of the code*/ -static void addHuffmanSymbol(size_t* bp, ucvector* compressed, unsigned code, unsigned bitlen) -{ +static void addHuffmanSymbol(size_t* bp, ucvector* compressed, unsigned code, unsigned bitlen) { addBitsToStreamReversed(bp, compressed, code, bitlen); } /*search the index in the array, that has the largest value smaller than or equal to the given value, given array must be sorted (if no value is smaller, it returns the size of the given array)*/ -static size_t searchCodeIndex(const unsigned* array, size_t array_size, size_t value) -{ +static size_t searchCodeIndex(const unsigned* array, size_t array_size, size_t value) { /*binary search (only small gain over linear). TODO: use CPU log2 instruction for getting symbols instead*/ size_t left = 1; size_t right = array_size - 1; @@ -1336,8 +1200,7 @@ static size_t searchCodeIndex(const unsigned* array, size_t array_size, size_t v return left; } -static void addLengthDistance(uivector* values, size_t length, size_t distance) -{ +static void addLengthDistance(uivector* values, size_t length, size_t distance) { /*values in encoded vector are those used by deflate: 0-255: literal bytes 256: end @@ -1360,8 +1223,7 @@ bytes as input because 3 is the minimum match length for deflate*/ static const unsigned HASH_NUM_VALUES = 65536; static const unsigned HASH_BIT_MASK = 65535; /*HASH_NUM_VALUES - 1, but C90 does not like that as initializer*/ -typedef struct Hash -{ +typedef struct Hash { int* head; /*hash value to head circular pos - can be outdated if went around window*/ /*circular pos to prev circular pos*/ unsigned short* chain; @@ -1374,8 +1236,7 @@ typedef struct Hash unsigned short* zeros; /*length of zeros streak, used as a second hash chain*/ } Hash; -static unsigned hash_init(Hash* hash, unsigned windowsize) -{ +static unsigned hash_init(Hash* hash, unsigned windowsize) { unsigned i; hash->head = (int*)lodepng_malloc(sizeof(int) * HASH_NUM_VALUES); hash->val = (int*)lodepng_malloc(sizeof(int) * windowsize); @@ -1385,8 +1246,7 @@ static unsigned hash_init(Hash* hash, unsigned windowsize) hash->headz = (int*)lodepng_malloc(sizeof(int) * (MAX_SUPPORTED_DEFLATE_LENGTH + 1)); hash->chainz = (unsigned short*)lodepng_malloc(sizeof(unsigned short) * windowsize); - if(!hash->head || !hash->chain || !hash->val || !hash->headz|| !hash->chainz || !hash->zeros) - { + if(!hash->head || !hash->chain || !hash->val || !hash->headz|| !hash->chainz || !hash->zeros) { return 83; /*alloc fail*/ } @@ -1401,8 +1261,7 @@ static unsigned hash_init(Hash* hash, unsigned windowsize) return 0; } -static void hash_cleanup(Hash* hash) -{ +static void hash_cleanup(Hash* hash) { lodepng_free(hash->head); lodepng_free(hash->val); lodepng_free(hash->chain); @@ -1414,11 +1273,9 @@ static void hash_cleanup(Hash* hash) -static unsigned getHash(const unsigned char* data, size_t size, size_t pos) -{ +static unsigned getHash(const unsigned char* data, size_t size, size_t pos) { unsigned result = 0; - if(pos + 2 < size) - { + if(pos + 2 < size) { /*A simple shift and xor hash is used. Since the data of PNGs is dominated by zeroes due to the filters, a better hash does not have a significant effect on speed in traversing the chain, and causes more time spend on @@ -1435,8 +1292,7 @@ static unsigned getHash(const unsigned char* data, size_t size, size_t pos) return result & HASH_BIT_MASK; } -static unsigned countZeros(const unsigned char* data, size_t size, size_t pos) -{ +static unsigned countZeros(const unsigned char* data, size_t size, size_t pos) { const unsigned char* start = data + pos; const unsigned char* end = start + MAX_SUPPORTED_DEFLATE_LENGTH; if(end > data + size) end = data + size; @@ -1447,8 +1303,7 @@ static unsigned countZeros(const unsigned char* data, size_t size, size_t pos) } /*wpos = pos & (windowsize - 1)*/ -static void updateHashChain(Hash* hash, size_t wpos, unsigned hashval, unsigned short numzeros) -{ +static void updateHashChain(Hash* hash, size_t wpos, unsigned hashval, unsigned short numzeros) { hash->val[wpos] = (int)hashval; if(hash->head[hashval] != -1) hash->chain[wpos] = hash->head[hashval]; hash->head[hashval] = (int)wpos; @@ -1469,8 +1324,7 @@ this hash technique is one out of several ways to speed this up. */ static unsigned encodeLZ77(uivector* out, Hash* hash, const unsigned char* in, size_t inpos, size_t insize, unsigned windowsize, - unsigned minmatch, unsigned nicematch, unsigned lazymatching) -{ + unsigned minmatch, unsigned nicematch, unsigned lazymatching) { size_t pos; unsigned i, error = 0; /*for large window lengths, assume the user wants no compression loss. Otherwise, max hash chain length speedup.*/ @@ -1495,20 +1349,16 @@ static unsigned encodeLZ77(uivector* out, Hash* hash, if(nicematch > MAX_SUPPORTED_DEFLATE_LENGTH) nicematch = MAX_SUPPORTED_DEFLATE_LENGTH; - for(pos = inpos; pos < insize; ++pos) - { + for(pos = inpos; pos < insize; ++pos) { size_t wpos = pos & (windowsize - 1); /*position for in 'circular' hash buffers*/ unsigned chainlength = 0; hashval = getHash(in, insize, pos); - if(usezeros && hashval == 0) - { + if(usezeros && hashval == 0) { if(numzeros == 0) numzeros = countZeros(in, insize, pos); else if(pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros; - } - else - { + } else { numzeros = 0; } @@ -1524,37 +1374,32 @@ static unsigned encodeLZ77(uivector* out, Hash* hash, /*search for the longest string*/ prev_offset = 0; - for(;;) - { + for(;;) { if(chainlength++ >= maxchainlength) break; current_offset = (unsigned)(hashpos <= wpos ? wpos - hashpos : wpos - hashpos + windowsize); if(current_offset < prev_offset) break; /*stop when went completely around the circular buffer*/ prev_offset = current_offset; - if(current_offset > 0) - { + if(current_offset > 0) { /*test the next characters*/ foreptr = &in[pos]; backptr = &in[pos - current_offset]; /*common case in PNGs is lots of zeros. Quickly skip over them as a speedup*/ - if(numzeros >= 3) - { + if(numzeros >= 3) { unsigned skip = hash->zeros[hashpos]; if(skip > numzeros) skip = numzeros; backptr += skip; foreptr += skip; } - while(foreptr != lastptr && *backptr == *foreptr) /*maximum supported length by deflate is max length*/ - { + while(foreptr != lastptr && *backptr == *foreptr) /*maximum supported length by deflate is max length*/ { ++backptr; ++foreptr; } current_length = (unsigned)(foreptr - &in[pos]); - if(current_length > length) - { + if(current_length > length) { length = current_length; /*the longest length*/ offset = current_offset; /*the offset that is related to this longest length*/ /*jump out once a length of max length is found (speed gain). This also jumps @@ -1565,39 +1410,30 @@ static unsigned encodeLZ77(uivector* out, Hash* hash, if(hashpos == hash->chain[hashpos]) break; - if(numzeros >= 3 && length > numzeros) - { + if(numzeros >= 3 && length > numzeros) { hashpos = hash->chainz[hashpos]; if(hash->zeros[hashpos] != numzeros) break; - } - else - { + } else { hashpos = hash->chain[hashpos]; /*outdated hash value, happens if particular value was not encountered in whole last window*/ if(hash->val[hashpos] != (int)hashval) break; } } - if(lazymatching) - { - if(!lazy && length >= 3 && length <= maxlazymatch && length < MAX_SUPPORTED_DEFLATE_LENGTH) - { + if(lazymatching) { + if(!lazy && length >= 3 && length <= maxlazymatch && length < MAX_SUPPORTED_DEFLATE_LENGTH) { lazy = 1; lazylength = length; lazyoffset = offset; continue; /*try the next byte*/ } - if(lazy) - { + if(lazy) { lazy = 0; if(pos == 0) ERROR_BREAK(81); - if(length > lazylength + 1) - { + if(length > lazylength + 1) { /*push the previous character as literal*/ if(!uivector_push_back(out, in[pos - 1])) ERROR_BREAK(83 /*alloc fail*/); - } - else - { + } else { length = lazylength; offset = lazyoffset; hash->head[hashval] = -1; /*the same hashchain update will be done, this ensures no wrong alteration*/ @@ -1609,31 +1445,22 @@ static unsigned encodeLZ77(uivector* out, Hash* hash, if(length >= 3 && offset > windowsize) ERROR_BREAK(86 /*too big (or overflown negative) offset*/); /*encode it as length/distance pair or literal value*/ - if(length < 3) /*only lengths of 3 or higher are supported as length/distance pair*/ - { + if(length < 3) /*only lengths of 3 or higher are supported as length/distance pair*/ { if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/); - } - else if(length < minmatch || (length == 3 && offset > 4096)) - { + } else if(length < minmatch || (length == 3 && offset > 4096)) { /*compensate for the fact that longer offsets have more extra bits, a length of only 3 may be not worth it then*/ if(!uivector_push_back(out, in[pos])) ERROR_BREAK(83 /*alloc fail*/); - } - else - { + } else { addLengthDistance(out, length, offset); - for(i = 1; i < length; ++i) - { + for(i = 1; i < length; ++i) { ++pos; wpos = pos & (windowsize - 1); hashval = getHash(in, insize, pos); - if(usezeros && hashval == 0) - { + if(usezeros && hashval == 0) { if(numzeros == 0) numzeros = countZeros(in, insize, pos); else if(pos + numzeros > insize || in[pos + numzeros - 1] != 0) --numzeros; - } - else - { + } else { numzeros = 0; } updateHashChain(hash, wpos, hashval, numzeros); @@ -1646,15 +1473,13 @@ static unsigned encodeLZ77(uivector* out, Hash* hash, /* /////////////////////////////////////////////////////////////////////////// */ -static unsigned deflateNoCompression(ucvector* out, const unsigned char* data, size_t datasize) -{ +static unsigned deflateNoCompression(ucvector* out, const unsigned char* data, size_t datasize) { /*non compressed deflate block data: 1 bit BFINAL,2 bits BTYPE,(5 bits): it jumps to start of next byte, 2 bytes LEN, 2 bytes NLEN, LEN bytes literal DATA*/ size_t i, j, numdeflateblocks = (datasize + 65534) / 65535; unsigned datapos = 0; - for(i = 0; i != numdeflateblocks; ++i) - { + for(i = 0; i != numdeflateblocks; ++i) { unsigned BFINAL, BTYPE, LEN, NLEN; unsigned char firstbyte; @@ -1674,8 +1499,7 @@ static unsigned deflateNoCompression(ucvector* out, const unsigned char* data, s ucvector_push_back(out, (unsigned char)(NLEN >> 8)); /*Decompressed data*/ - for(j = 0; j < 65535 && datapos < datasize; ++j) - { + for(j = 0; j < 65535 && datapos < datasize; ++j) { ucvector_push_back(out, data[datapos++]); } } @@ -1689,15 +1513,12 @@ tree_ll: the tree for lit and len codes. tree_d: the tree for distance codes. */ static void writeLZ77data(size_t* bp, ucvector* out, const uivector* lz77_encoded, - const HuffmanTree* tree_ll, const HuffmanTree* tree_d) -{ + const HuffmanTree* tree_ll, const HuffmanTree* tree_d) { size_t i = 0; - for(i = 0; i != lz77_encoded->size; ++i) - { + for(i = 0; i != lz77_encoded->size; ++i) { unsigned val = lz77_encoded->data[i]; addHuffmanSymbol(bp, out, HuffmanTree_getCode(tree_ll, val), HuffmanTree_getLength(tree_ll, val)); - if(val > 256) /*for a length code, 3 more things have to be added*/ - { + if(val > 256) /*for a length code, 3 more things have to be added*/ { unsigned length_index = val - FIRST_LENGTH_CODE_INDEX; unsigned n_length_extra_bits = LENGTHEXTRA[length_index]; unsigned length_extra_bits = lz77_encoded->data[++i]; @@ -1719,8 +1540,7 @@ static void writeLZ77data(size_t* bp, ucvector* out, const uivector* lz77_encode /*Deflate for a block of type "dynamic", that is, with freely, optimally, created huffman trees*/ static unsigned deflateDynamic(ucvector* out, size_t* bp, Hash* hash, const unsigned char* data, size_t datapos, size_t dataend, - const LodePNGCompressSettings* settings, unsigned final) -{ + const LodePNGCompressSettings* settings, unsigned final) { unsigned error = 0; /* @@ -1774,16 +1594,12 @@ static unsigned deflateDynamic(ucvector* out, size_t* bp, Hash* hash, /*This while loop never loops due to a break at the end, it is here to allow breaking out of it to the cleanup phase on error conditions.*/ - while(!error) - { - if(settings->use_lz77) - { + while(!error) { + if(settings->use_lz77) { error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize, settings->minmatch, settings->nicematch, settings->lazymatching); if(error) break; - } - else - { + } else { if(!uivector_resize(&lz77_encoded, datasize)) ERROR_BREAK(83 /*alloc fail*/); for(i = datapos; i < dataend; ++i) lz77_encoded.data[i - datapos] = data[i]; /*no LZ77, but still will be Huffman compressed*/ } @@ -1792,12 +1608,10 @@ static unsigned deflateDynamic(ucvector* out, size_t* bp, Hash* hash, if(!uivector_resizev(&frequencies_d, 30, 0)) ERROR_BREAK(83 /*alloc fail*/); /*Count the frequencies of lit, len and dist codes*/ - for(i = 0; i != lz77_encoded.size; ++i) - { + for(i = 0; i != lz77_encoded.size; ++i) { unsigned symbol = lz77_encoded.data[i]; ++frequencies_ll.data[symbol]; - if(symbol > 256) - { + if(symbol > 256) { unsigned dist = lz77_encoded.data[i + 2]; ++frequencies_d.data[dist]; i += 3; @@ -1820,47 +1634,36 @@ static unsigned deflateDynamic(ucvector* out, size_t* bp, Hash* hash, /*run-length compress bitlen_ldd into bitlen_lld_e by using repeat codes 16 (copy length 3-6 times), 17 (3-10 zeroes), 18 (11-138 zeroes)*/ - for(i = 0; i != (unsigned)bitlen_lld.size; ++i) - { + for(i = 0; i != (unsigned)bitlen_lld.size; ++i) { unsigned j = 0; /*amount of repititions*/ while(i + j + 1 < (unsigned)bitlen_lld.size && bitlen_lld.data[i + j + 1] == bitlen_lld.data[i]) ++j; - if(bitlen_lld.data[i] == 0 && j >= 2) /*repeat code for zeroes*/ - { + if(bitlen_lld.data[i] == 0 && j >= 2) /*repeat code for zeroes*/ { ++j; /*include the first zero*/ - if(j <= 10) /*repeat code 17 supports max 10 zeroes*/ - { + if(j <= 10) /*repeat code 17 supports max 10 zeroes*/ { uivector_push_back(&bitlen_lld_e, 17); uivector_push_back(&bitlen_lld_e, j - 3); - } - else /*repeat code 18 supports max 138 zeroes*/ - { + } else /*repeat code 18 supports max 138 zeroes*/ { if(j > 138) j = 138; uivector_push_back(&bitlen_lld_e, 18); uivector_push_back(&bitlen_lld_e, j - 11); } i += (j - 1); - } - else if(j >= 3) /*repeat code for value other than zero*/ - { + } else if(j >= 3) /*repeat code for value other than zero*/ { size_t k; unsigned num = j / 6, rest = j % 6; uivector_push_back(&bitlen_lld_e, bitlen_lld.data[i]); - for(k = 0; k < num; ++k) - { + for(k = 0; k < num; ++k) { uivector_push_back(&bitlen_lld_e, 16); uivector_push_back(&bitlen_lld_e, 6 - 3); } - if(rest >= 3) - { + if(rest >= 3) { uivector_push_back(&bitlen_lld_e, 16); uivector_push_back(&bitlen_lld_e, rest - 3); } else j -= rest; i += j; - } - else /*too short to benefit from repeat code*/ - { + } else /*too short to benefit from repeat code*/ { uivector_push_back(&bitlen_lld_e, bitlen_lld.data[i]); } } @@ -1868,8 +1671,7 @@ static unsigned deflateDynamic(ucvector* out, size_t* bp, Hash* hash, /*generate tree_cl, the huffmantree of huffmantrees*/ if(!uivector_resizev(&frequencies_cl, NUM_CODE_LENGTH_CODES, 0)) ERROR_BREAK(83 /*alloc fail*/); - for(i = 0; i != bitlen_lld_e.size; ++i) - { + for(i = 0; i != bitlen_lld_e.size; ++i) { ++frequencies_cl.data[bitlen_lld_e.data[i]]; /*after a repeat code come the bits that specify the number of repetitions, those don't need to be in the frequencies_cl calculation*/ @@ -1881,13 +1683,11 @@ static unsigned deflateDynamic(ucvector* out, size_t* bp, Hash* hash, if(error) break; if(!uivector_resize(&bitlen_cl, tree_cl.numcodes)) ERROR_BREAK(83 /*alloc fail*/); - for(i = 0; i != tree_cl.numcodes; ++i) - { + for(i = 0; i != tree_cl.numcodes; ++i) { /*lenghts of code length tree is in the order as specified by deflate*/ bitlen_cl.data[i] = HuffmanTree_getLength(&tree_cl, CLCL_ORDER[i]); } - while(bitlen_cl.data[bitlen_cl.size - 1] == 0 && bitlen_cl.size > 4) - { + while(bitlen_cl.data[bitlen_cl.size - 1] == 0 && bitlen_cl.size > 4) { /*remove zeros at the end, but minimum size must be 4*/ if(!uivector_resize(&bitlen_cl, bitlen_cl.size - 1)) ERROR_BREAK(83 /*alloc fail*/); } @@ -1926,8 +1726,7 @@ static unsigned deflateDynamic(ucvector* out, size_t* bp, Hash* hash, for(i = 0; i != HCLEN + 4; ++i) addBitsToStream(bp, out, bitlen_cl.data[i], 3); /*write the lenghts of the lit/len AND the dist alphabet*/ - for(i = 0; i != bitlen_lld_e.size; ++i) - { + for(i = 0; i != bitlen_lld_e.size; ++i) { addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_cl, bitlen_lld_e.data[i]), HuffmanTree_getLength(&tree_cl, bitlen_lld_e.data[i])); /*extra bits of repeat codes*/ @@ -1965,8 +1764,7 @@ static unsigned deflateDynamic(ucvector* out, size_t* bp, Hash* hash, static unsigned deflateFixed(ucvector* out, size_t* bp, Hash* hash, const unsigned char* data, size_t datapos, size_t dataend, - const LodePNGCompressSettings* settings, unsigned final) -{ + const LodePNGCompressSettings* settings, unsigned final) { HuffmanTree tree_ll; /*tree for literal values and length codes*/ HuffmanTree tree_d; /*tree for distance codes*/ @@ -1984,19 +1782,15 @@ static unsigned deflateFixed(ucvector* out, size_t* bp, Hash* hash, addBitToStream(bp, out, 1); /*first bit of BTYPE*/ addBitToStream(bp, out, 0); /*second bit of BTYPE*/ - if(settings->use_lz77) /*LZ77 encoded*/ - { + if(settings->use_lz77) /*LZ77 encoded*/ { uivector lz77_encoded; uivector_init(&lz77_encoded); error = encodeLZ77(&lz77_encoded, hash, data, datapos, dataend, settings->windowsize, settings->minmatch, settings->nicematch, settings->lazymatching); if(!error) writeLZ77data(bp, out, &lz77_encoded, &tree_ll, &tree_d); uivector_cleanup(&lz77_encoded); - } - else /*no LZ77, but still will be Huffman compressed*/ - { - for(i = datapos; i < dataend; ++i) - { + } else /*no LZ77, but still will be Huffman compressed*/ { + for(i = datapos; i < dataend; ++i) { addHuffmanSymbol(bp, out, HuffmanTree_getCode(&tree_ll, data[i]), HuffmanTree_getLength(&tree_ll, data[i])); } } @@ -2011,8 +1805,7 @@ static unsigned deflateFixed(ucvector* out, size_t* bp, Hash* hash, } static unsigned lodepng_deflatev(ucvector* out, const unsigned char* in, size_t insize, - const LodePNGCompressSettings* settings) -{ + const LodePNGCompressSettings* settings) { unsigned error = 0; size_t i, blocksize, numdeflateblocks; size_t bp = 0; /*the bit pointer*/ @@ -2021,8 +1814,7 @@ static unsigned lodepng_deflatev(ucvector* out, const unsigned char* in, size_t if(settings->btype > 2) return 61; else if(settings->btype == 0) return deflateNoCompression(out, in, insize); else if(settings->btype == 1) blocksize = insize; - else /*if(settings->btype == 2)*/ - { + else /*if(settings->btype == 2)*/ { /*on PNGs, deflate blocks of 65-262k seem to give most dense encoding*/ blocksize = insize / 8 + 8; if(blocksize < 65536) blocksize = 65536; @@ -2035,8 +1827,7 @@ static unsigned lodepng_deflatev(ucvector* out, const unsigned char* in, size_t error = hash_init(&hash, settings->windowsize); if(error) return error; - for(i = 0; i != numdeflateblocks && !error; ++i) - { + for(i = 0; i != numdeflateblocks && !error; ++i) { unsigned final = (i == numdeflateblocks - 1); size_t start = i * blocksize; size_t end = start + blocksize; @@ -2053,8 +1844,7 @@ static unsigned lodepng_deflatev(ucvector* out, const unsigned char* in, size_t unsigned lodepng_deflate(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, - const LodePNGCompressSettings* settings) -{ + const LodePNGCompressSettings* settings) { unsigned error; ucvector v; ucvector_init_buffer(&v, *out, *outsize); @@ -2066,14 +1856,10 @@ unsigned lodepng_deflate(unsigned char** out, size_t* outsize, static unsigned deflate(unsigned char** out, size_t* outsize, const unsigned char* in, size_t insize, - const LodePNGCompressSettings* settings) -{ - if(settings->custom_deflate) - { + const LodePNGCompressSettings* settings) { + if(settings->custom_deflate) { return settings->custom_deflate(out, outsize, in, insize, settings); - } - else - { + } else { return lodepng_deflate(out, outsize, in, insize, settings); } } @@ -2084,18 +1870,15 @@ static unsigned deflate(unsigned char** out, size_t* outsize, /* / Adler32 */ /* ////////////////////////////////////////////////////////////////////////// */ -static unsigned update_adler32(unsigned adler, const unsigned char* data, unsigned len) -{ +static unsigned update_adler32(unsigned adler, const unsigned char* data, unsigned len) { unsigned s1 = adler & 0xffff; unsigned s2 = (adler >> 16) & 0xffff; - while(len > 0) - { + while(len > 0) { /*at least 5552 sums can be done before the sums overflow, saving a lot of module divisions*/ unsigned amount = len > 5552 ? 5552 : len; len -= amount; - while(amount > 0) - { + while(amount > 0) { s1 += (*data++); s2 += s1; --amount; @@ -2108,8 +1891,7 @@ static unsigned update_adler32(unsigned adler, const unsigned char* data, unsign } /*Return the adler32 of the bytes data[0..len-1]*/ -static unsigned adler32(const unsigned char* data, unsigned len) -{ +static unsigned adler32(const unsigned char* data, unsigned len) { return update_adler32(1L, data, len); } @@ -2120,15 +1902,13 @@ static unsigned adler32(const unsigned char* data, unsigned len) #ifdef LODEPNG_COMPILE_DECODER unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in, - size_t insize, const LodePNGDecompressSettings* settings) -{ + size_t insize, const LodePNGDecompressSettings* settings) { unsigned error = 0; unsigned CM, CINFO, FDICT; if(insize < 2) return 53; /*error, size of zlib data too small*/ /*read information from zlib header*/ - if((in[0] * 256 + in[1]) % 31 != 0) - { + if((in[0] * 256 + in[1]) % 31 != 0) { /*error: 256 * in[0] + in[1] must be a multiple of 31, the FCHECK value is supposed to be made that way*/ return 24; } @@ -2139,13 +1919,11 @@ unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize, const uns FDICT = (in[1] >> 5) & 1; /*FLEVEL = (in[1] >> 6) & 3;*/ /*FLEVEL is not used here*/ - if(CM != 8 || CINFO > 7) - { + if(CM != 8 || CINFO > 7) { /*error: only compression method 8: inflate with sliding window of 32k is supported by the PNG spec*/ return 25; } - if(FDICT != 0) - { + if(FDICT != 0) { /*error: the specification of PNG says about the zlib stream: "The additional flags shall not specify a preset dictionary."*/ return 26; @@ -2154,8 +1932,7 @@ unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize, const uns error = inflate(out, outsize, in + 2, insize - 2, settings); if(error) return error; - if(!settings->ignore_adler32) - { + if(!settings->ignore_adler32) { unsigned ADLER32 = lodepng_read32bitInt(&in[insize - 4]); unsigned checksum = adler32(*out, (unsigned)(*outsize)); if(checksum != ADLER32) return 58; /*error, adler checksum not correct, data must be corrupted*/ @@ -2165,14 +1942,10 @@ unsigned lodepng_zlib_decompress(unsigned char** out, size_t* outsize, const uns } static unsigned zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in, - size_t insize, const LodePNGDecompressSettings* settings) -{ - if(settings->custom_zlib) - { + size_t insize, const LodePNGDecompressSettings* settings) { + if(settings->custom_zlib) { return settings->custom_zlib(out, outsize, in, insize, settings); - } - else - { + } else { return lodepng_zlib_decompress(out, outsize, in, insize, settings); } } @@ -2182,8 +1955,7 @@ static unsigned zlib_decompress(unsigned char** out, size_t* outsize, const unsi #ifdef LODEPNG_COMPILE_ENCODER unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in, - size_t insize, const LodePNGCompressSettings* settings) -{ + size_t insize, const LodePNGCompressSettings* settings) { /*initially, *out must be NULL and outsize 0, if you just give some random *out that's pointing to a non allocated buffer, this'll crash*/ ucvector outv; @@ -2208,8 +1980,7 @@ unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize, const unsig error = deflate(&deflatedata, &deflatesize, in, insize, settings); - if(!error) - { + if(!error) { unsigned ADLER32 = adler32(in, (unsigned)insize); for(i = 0; i != deflatesize; ++i) ucvector_push_back(&outv, deflatedata[i]); lodepng_free(deflatedata); @@ -2224,14 +1995,10 @@ unsigned lodepng_zlib_compress(unsigned char** out, size_t* outsize, const unsig /* compress using the default or custom zlib function */ static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in, - size_t insize, const LodePNGCompressSettings* settings) -{ - if(settings->custom_zlib) - { + size_t insize, const LodePNGCompressSettings* settings) { + if(settings->custom_zlib) { return settings->custom_zlib(out, outsize, in, insize, settings); - } - else - { + } else { return lodepng_zlib_compress(out, outsize, in, insize, settings); } } @@ -2242,16 +2009,14 @@ static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsign #ifdef LODEPNG_COMPILE_DECODER static unsigned zlib_decompress(unsigned char** out, size_t* outsize, const unsigned char* in, - size_t insize, const LodePNGDecompressSettings* settings) -{ + size_t insize, const LodePNGDecompressSettings* settings) { if(!settings->custom_zlib) return 87; /*no custom zlib function provided */ return settings->custom_zlib(out, outsize, in, insize, settings); } #endif /*LODEPNG_COMPILE_DECODER*/ #ifdef LODEPNG_COMPILE_ENCODER static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsigned char* in, - size_t insize, const LodePNGCompressSettings* settings) -{ + size_t insize, const LodePNGCompressSettings* settings) { if(!settings->custom_zlib) return 87; /*no custom zlib function provided */ return settings->custom_zlib(out, outsize, in, insize, settings); } @@ -2266,8 +2031,7 @@ static unsigned zlib_compress(unsigned char** out, size_t* outsize, const unsign /*this is a good tradeoff between speed and compression ratio*/ #define DEFAULT_WINDOWSIZE 2048 -void lodepng_compress_settings_init(LodePNGCompressSettings* settings) -{ +void lodepng_compress_settings_init(LodePNGCompressSettings* settings) { /*compress with dynamic huffman tree (not in the mathematical sense, just not the predefined one)*/ settings->btype = 2; settings->use_lz77 = 1; @@ -2288,8 +2052,7 @@ const LodePNGCompressSettings lodepng_default_compress_settings = {2, 1, DEFAULT #ifdef LODEPNG_COMPILE_DECODER -void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings) -{ +void lodepng_decompress_settings_init(LodePNGDecompressSettings* settings) { settings->ignore_adler32 = 0; settings->custom_zlib = 0; @@ -2352,12 +2115,10 @@ static unsigned lodepng_crc32_table[256] = { }; /*Return the CRC of the bytes buf[0..len-1].*/ -unsigned lodepng_crc32(const unsigned char* data, size_t length) -{ +unsigned lodepng_crc32(const unsigned char* data, size_t length) { unsigned r = 0xffffffffu; size_t i; - for(i = 0; i < length; ++i) - { + for(i = 0; i < length; ++i) { r = lodepng_crc32_table[(r ^ data[i]) & 0xff] ^ (r >> 8); } return r ^ 0xffffffffu; @@ -2370,19 +2131,16 @@ unsigned lodepng_crc32(const unsigned char* data, size_t length); /* / Reading and writing single bits and bytes from/to stream for LodePNG / */ /* ////////////////////////////////////////////////////////////////////////// */ -static unsigned char readBitFromReversedStream(size_t* bitpointer, const unsigned char* bitstream) -{ +static unsigned char readBitFromReversedStream(size_t* bitpointer, const unsigned char* bitstream) { unsigned char result = (unsigned char)((bitstream[(*bitpointer) >> 3] >> (7 - ((*bitpointer) & 0x7))) & 1); ++(*bitpointer); return result; } -static unsigned readBitsFromReversedStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits) -{ +static unsigned readBitsFromReversedStream(size_t* bitpointer, const unsigned char* bitstream, size_t nbits) { unsigned result = 0; size_t i; - for(i = 0 ; i < nbits; ++i) - { + for(i = 0 ; i < nbits; ++i) { result <<= 1; result |= (unsigned)readBitFromReversedStream(bitpointer, bitstream); } @@ -2390,11 +2148,9 @@ static unsigned readBitsFromReversedStream(size_t* bitpointer, const unsigned ch } #ifdef LODEPNG_COMPILE_DECODER -static void setBitOfReversedStream0(size_t* bitpointer, unsigned char* bitstream, unsigned char bit) -{ +static void setBitOfReversedStream0(size_t* bitpointer, unsigned char* bitstream, unsigned char bit) { /*the current bit in bitstream must be 0 for this to work*/ - if(bit) - { + if(bit) { /*earlier bit of huffman code is in a lesser significant bit of an earlier byte*/ bitstream[(*bitpointer) >> 3] |= (bit << (7 - ((*bitpointer) & 0x7))); } @@ -2402,8 +2158,7 @@ static void setBitOfReversedStream0(size_t* bitpointer, unsigned char* bitstream } #endif /*LODEPNG_COMPILE_DECODER*/ -static void setBitOfReversedStream(size_t* bitpointer, unsigned char* bitstream, unsigned char bit) -{ +static void setBitOfReversedStream(size_t* bitpointer, unsigned char* bitstream, unsigned char bit) { /*the current bit in bitstream may be 0 or 1 for this to work*/ if(bit == 0) bitstream[(*bitpointer) >> 3] &= (unsigned char)(~(1 << (7 - ((*bitpointer) & 0x7)))); else bitstream[(*bitpointer) >> 3] |= (1 << (7 - ((*bitpointer) & 0x7))); @@ -2414,51 +2169,42 @@ static void setBitOfReversedStream(size_t* bitpointer, unsigned char* bitstream, /* / PNG chunks / */ /* ////////////////////////////////////////////////////////////////////////// */ -unsigned lodepng_chunk_length(const unsigned char* chunk) -{ +unsigned lodepng_chunk_length(const unsigned char* chunk) { return lodepng_read32bitInt(&chunk[0]); } -void lodepng_chunk_type(char type[5], const unsigned char* chunk) -{ +void lodepng_chunk_type(char type[5], const unsigned char* chunk) { unsigned i; for(i = 0; i != 4; ++i) type[i] = (char)chunk[4 + i]; type[4] = 0; /*null termination char*/ } -unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type) -{ +unsigned char lodepng_chunk_type_equals(const unsigned char* chunk, const char* type) { if(strlen(type) != 4) return 0; return (chunk[4] == type[0] && chunk[5] == type[1] && chunk[6] == type[2] && chunk[7] == type[3]); } -unsigned char lodepng_chunk_ancillary(const unsigned char* chunk) -{ +unsigned char lodepng_chunk_ancillary(const unsigned char* chunk) { return((chunk[4] & 32) != 0); } -unsigned char lodepng_chunk_private(const unsigned char* chunk) -{ +unsigned char lodepng_chunk_private(const unsigned char* chunk) { return((chunk[6] & 32) != 0); } -unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk) -{ +unsigned char lodepng_chunk_safetocopy(const unsigned char* chunk) { return((chunk[7] & 32) != 0); } -unsigned char* lodepng_chunk_data(unsigned char* chunk) -{ +unsigned char* lodepng_chunk_data(unsigned char* chunk) { return &chunk[8]; } -const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk) -{ +const unsigned char* lodepng_chunk_data_const(const unsigned char* chunk) { return &chunk[8]; } -unsigned lodepng_chunk_check_crc(const unsigned char* chunk) -{ +unsigned lodepng_chunk_check_crc(const unsigned char* chunk) { unsigned length = lodepng_chunk_length(chunk); unsigned CRC = lodepng_read32bitInt(&chunk[length + 8]); /*the CRC is taken of the data and the 4 chunk type letters, not the length*/ @@ -2467,15 +2213,13 @@ unsigned lodepng_chunk_check_crc(const unsigned char* chunk) else return 0; } -void lodepng_chunk_generate_crc(unsigned char* chunk) -{ +void lodepng_chunk_generate_crc(unsigned char* chunk) { unsigned length = lodepng_chunk_length(chunk); unsigned CRC = lodepng_crc32(&chunk[4], length + 4); lodepng_set32bitInt(chunk + 8 + length, CRC); } -unsigned char* lodepng_chunk_next(unsigned char* chunk) -{ +unsigned char* lodepng_chunk_next(unsigned char* chunk) { if(chunk[0] == 0x89 && chunk[1] == 0x50 && chunk[2] == 0x4e && chunk[3] == 0x47 && chunk[4] == 0x0d && chunk[5] == 0x0a && chunk[6] == 0x1a && chunk[7] == 0x0a) { /* Is PNG magic header at start of PNG file. Jump to first actual chunk. */ @@ -2486,8 +2230,7 @@ unsigned char* lodepng_chunk_next(unsigned char* chunk) } } -const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk) -{ +const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk) { if(chunk[0] == 0x89 && chunk[1] == 0x50 && chunk[2] == 0x4e && chunk[3] == 0x47 && chunk[4] == 0x0d && chunk[5] == 0x0a && chunk[6] == 0x1a && chunk[7] == 0x0a) { /* Is PNG magic header at start of PNG file. Jump to first actual chunk. */ @@ -2498,28 +2241,23 @@ const unsigned char* lodepng_chunk_next_const(const unsigned char* chunk) } } -unsigned char* lodepng_chunk_find(unsigned char* chunk, const unsigned char* end, const char type[5]) -{ - for(;;) - { +unsigned char* lodepng_chunk_find(unsigned char* chunk, const unsigned char* end, const char type[5]) { + for(;;) { if(chunk + 12 >= end) return 0; if(lodepng_chunk_type_equals(chunk, type)) return chunk; chunk = lodepng_chunk_next(chunk); } } -const unsigned char* lodepng_chunk_find_const(const unsigned char* chunk, const unsigned char* end, const char type[5]) -{ - for(;;) - { +const unsigned char* lodepng_chunk_find_const(const unsigned char* chunk, const unsigned char* end, const char type[5]) { + for(;;) { if(chunk + 12 >= end) return 0; if(lodepng_chunk_type_equals(chunk, type)) return chunk; chunk = lodepng_chunk_next_const(chunk); } } -unsigned lodepng_chunk_append(unsigned char** out, size_t* outlength, const unsigned char* chunk) -{ +unsigned lodepng_chunk_append(unsigned char** out, size_t* outlength, const unsigned char* chunk) { unsigned i; unsigned total_chunk_length = lodepng_chunk_length(chunk) + 12; unsigned char *chunk_start, *new_buffer; @@ -2538,8 +2276,7 @@ unsigned lodepng_chunk_append(unsigned char** out, size_t* outlength, const unsi } unsigned lodepng_chunk_create(unsigned char** out, size_t* outlength, unsigned length, - const char* type, const unsigned char* data) -{ + const char* type, const unsigned char* data) { unsigned i; unsigned char *chunk, *new_buffer; size_t new_length = (*outlength) + length + 12; @@ -2573,10 +2310,8 @@ unsigned lodepng_chunk_create(unsigned char** out, size_t* outlength, unsigned l /* ////////////////////////////////////////////////////////////////////////// */ /*return type is a LodePNG error code*/ -static unsigned checkColorValidity(LodePNGColorType colortype, unsigned bd) /*bd = bitdepth*/ -{ - switch(colortype) - { +static unsigned checkColorValidity(LodePNGColorType colortype, unsigned bd) /*bd = bitdepth*/ { + switch(colortype) { case 0: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 || bd == 16)) return 37; break; /*grey*/ case 2: if(!( bd == 8 || bd == 16)) return 37; break; /*RGB*/ case 3: if(!(bd == 1 || bd == 2 || bd == 4 || bd == 8 )) return 37; break; /*palette*/ @@ -2587,10 +2322,8 @@ static unsigned checkColorValidity(LodePNGColorType colortype, unsigned bd) /*bd return 0; /*allowed color type / bits combination*/ } -static unsigned getNumColorChannels(LodePNGColorType colortype) -{ - switch(colortype) - { +static unsigned getNumColorChannels(LodePNGColorType colortype) { + switch(colortype) { case 0: return 1; /*grey*/ case 2: return 3; /*RGB*/ case 3: return 1; /*palette*/ @@ -2600,16 +2333,14 @@ static unsigned getNumColorChannels(LodePNGColorType colortype) return 0; /*unexisting color type*/ } -static unsigned lodepng_get_bpp_lct(LodePNGColorType colortype, unsigned bitdepth) -{ +static unsigned lodepng_get_bpp_lct(LodePNGColorType colortype, unsigned bitdepth) { /*bits per pixel is amount of channels * bits per channel*/ return getNumColorChannels(colortype) * bitdepth; } /* ////////////////////////////////////////////////////////////////////////// */ -void lodepng_color_mode_init(LodePNGColorMode* info) -{ +void lodepng_color_mode_init(LodePNGColorMode* info) { info->key_defined = 0; info->key_r = info->key_g = info->key_b = 0; info->colortype = LCT_RGBA; @@ -2618,18 +2349,15 @@ void lodepng_color_mode_init(LodePNGColorMode* info) info->palettesize = 0; } -void lodepng_color_mode_cleanup(LodePNGColorMode* info) -{ +void lodepng_color_mode_cleanup(LodePNGColorMode* info) { lodepng_palette_clear(info); } -unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source) -{ +unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* source) { size_t i; lodepng_color_mode_cleanup(dest); *dest = *source; - if(source->palette) - { + if(source->palette) { dest->palette = (unsigned char*)lodepng_malloc(1024); if(!dest->palette && source->palettesize) return 83; /*alloc fail*/ for(i = 0; i != source->palettesize * 4; ++i) dest->palette[i] = source->palette[i]; @@ -2637,8 +2365,7 @@ unsigned lodepng_color_mode_copy(LodePNGColorMode* dest, const LodePNGColorMode* return 0; } -LodePNGColorMode lodepng_color_mode_make(LodePNGColorType colortype, unsigned bitdepth) -{ +LodePNGColorMode lodepng_color_mode_make(LodePNGColorType colortype, unsigned bitdepth) { LodePNGColorMode result; lodepng_color_mode_init(&result); result.colortype = colortype; @@ -2646,41 +2373,35 @@ LodePNGColorMode lodepng_color_mode_make(LodePNGColorType colortype, unsigned bi return result; } -static int lodepng_color_mode_equal(const LodePNGColorMode* a, const LodePNGColorMode* b) -{ +static int lodepng_color_mode_equal(const LodePNGColorMode* a, const LodePNGColorMode* b) { size_t i; if(a->colortype != b->colortype) return 0; if(a->bitdepth != b->bitdepth) return 0; if(a->key_defined != b->key_defined) return 0; - if(a->key_defined) - { + if(a->key_defined) { if(a->key_r != b->key_r) return 0; if(a->key_g != b->key_g) return 0; if(a->key_b != b->key_b) return 0; } if(a->palettesize != b->palettesize) return 0; - for(i = 0; i != a->palettesize * 4; ++i) - { + for(i = 0; i != a->palettesize * 4; ++i) { if(a->palette[i] != b->palette[i]) return 0; } return 1; } -void lodepng_palette_clear(LodePNGColorMode* info) -{ +void lodepng_palette_clear(LodePNGColorMode* info) { if(info->palette) lodepng_free(info->palette); info->palette = 0; info->palettesize = 0; } unsigned lodepng_palette_add(LodePNGColorMode* info, - unsigned char r, unsigned char g, unsigned char b, unsigned char a) -{ + unsigned char r, unsigned char g, unsigned char b, unsigned char a) { unsigned char* data; /*the same resize technique as C++ std::vectors is used, and here it's made so that for a palette with the max of 256 colors, it'll have the exact alloc size*/ - if(!info->palette) /*allocate palette if empty*/ - { + if(!info->palette) /*allocate palette if empty*/ { /*room for 256 colors with 4 bytes each*/ data = (unsigned char*)lodepng_realloc(info->palette, 1024); if(!data) return 83; /*alloc fail*/ @@ -2695,57 +2416,47 @@ unsigned lodepng_palette_add(LodePNGColorMode* info, } /*calculate bits per pixel out of colortype and bitdepth*/ -unsigned lodepng_get_bpp(const LodePNGColorMode* info) -{ +unsigned lodepng_get_bpp(const LodePNGColorMode* info) { return lodepng_get_bpp_lct(info->colortype, info->bitdepth); } -unsigned lodepng_get_channels(const LodePNGColorMode* info) -{ +unsigned lodepng_get_channels(const LodePNGColorMode* info) { return getNumColorChannels(info->colortype); } -unsigned lodepng_is_greyscale_type(const LodePNGColorMode* info) -{ +unsigned lodepng_is_greyscale_type(const LodePNGColorMode* info) { return info->colortype == LCT_GREY || info->colortype == LCT_GREY_ALPHA; } -unsigned lodepng_is_alpha_type(const LodePNGColorMode* info) -{ +unsigned lodepng_is_alpha_type(const LodePNGColorMode* info) { return (info->colortype & 4) != 0; /*4 or 6*/ } -unsigned lodepng_is_palette_type(const LodePNGColorMode* info) -{ +unsigned lodepng_is_palette_type(const LodePNGColorMode* info) { return info->colortype == LCT_PALETTE; } -unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info) -{ +unsigned lodepng_has_palette_alpha(const LodePNGColorMode* info) { size_t i; - for(i = 0; i != info->palettesize; ++i) - { + for(i = 0; i != info->palettesize; ++i) { if(info->palette[i * 4 + 3] < 255) return 1; } return 0; } -unsigned lodepng_can_have_alpha(const LodePNGColorMode* info) -{ +unsigned lodepng_can_have_alpha(const LodePNGColorMode* info) { return info->key_defined || lodepng_is_alpha_type(info) || lodepng_has_palette_alpha(info); } -size_t lodepng_get_raw_size_lct(unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) -{ +size_t lodepng_get_raw_size_lct(unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) { size_t bpp = lodepng_get_bpp_lct(colortype, bitdepth); size_t n = (size_t)w * (size_t)h; return ((n / 8) * bpp) + ((n & 7) * bpp + 7) / 8; } -size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color) -{ +size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* color) { return lodepng_get_raw_size_lct(w, h, color->colortype, color->bitdepth); } @@ -2756,8 +2467,7 @@ size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* colo /*in an idat chunk, each scanline is a multiple of 8 bits, unlike the lodepng output buffer, and in addition has one extra byte per line: the filter byte. So this gives a larger result than lodepng_get_raw_size. */ -static size_t lodepng_get_raw_size_idat(unsigned w, unsigned h, const LodePNGColorMode* color) -{ +static size_t lodepng_get_raw_size_idat(unsigned w, unsigned h, const LodePNGColorMode* color) { size_t bpp = lodepng_get_bpp(color); /* + 1 for the filter byte, and possibly plus padding bits per line */ size_t line = ((size_t)(w / 8) * bpp) + 1 + ((w & 7) * bpp + 7) / 8; @@ -2766,16 +2476,14 @@ static size_t lodepng_get_raw_size_idat(unsigned w, unsigned h, const LodePNGCol /* Safely check if multiplying two integers will overflow (no undefined behavior, compiler removing the code, etc...) and output result. */ -static int lodepng_mulofl(size_t a, size_t b, size_t* result) -{ +static int lodepng_mulofl(size_t a, size_t b, size_t* result) { *result = a * b; /* Unsigned multiplication is well defined and safe in C90 */ return (a != 0 && *result / a != b); } /* Safely check if adding two integers will overflow (no undefined behavior, compiler removing the code, etc...) and output result. */ -static int lodepng_addofl(size_t a, size_t b, size_t* result) -{ +static int lodepng_addofl(size_t a, size_t b, size_t* result) { *result = a + b; /* Unsigned addition is well defined and safe in C90 */ return *result < a; } @@ -2789,8 +2497,7 @@ you can safely compute in a size_t (but not an unsigned): Returns 1 if overflow possible, 0 if not. */ static int lodepng_pixel_overflow(unsigned w, unsigned h, - const LodePNGColorMode* pngcolor, const LodePNGColorMode* rawcolor) -{ + const LodePNGColorMode* pngcolor, const LodePNGColorMode* rawcolor) { size_t bpp = LODEPNG_MAX(lodepng_get_bpp(pngcolor), lodepng_get_bpp(rawcolor)); size_t numpixels, total; size_t line; /* bytes per line in worst case */ @@ -2812,33 +2519,28 @@ static int lodepng_pixel_overflow(unsigned w, unsigned h, #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS -static void LodePNGUnknownChunks_init(LodePNGInfo* info) -{ +static void LodePNGUnknownChunks_init(LodePNGInfo* info) { unsigned i; for(i = 0; i != 3; ++i) info->unknown_chunks_data[i] = 0; for(i = 0; i != 3; ++i) info->unknown_chunks_size[i] = 0; } -static void LodePNGUnknownChunks_cleanup(LodePNGInfo* info) -{ +static void LodePNGUnknownChunks_cleanup(LodePNGInfo* info) { unsigned i; for(i = 0; i != 3; ++i) lodepng_free(info->unknown_chunks_data[i]); } -static unsigned LodePNGUnknownChunks_copy(LodePNGInfo* dest, const LodePNGInfo* src) -{ +static unsigned LodePNGUnknownChunks_copy(LodePNGInfo* dest, const LodePNGInfo* src) { unsigned i; LodePNGUnknownChunks_cleanup(dest); - for(i = 0; i != 3; ++i) - { + for(i = 0; i != 3; ++i) { size_t j; dest->unknown_chunks_size[i] = src->unknown_chunks_size[i]; dest->unknown_chunks_data[i] = (unsigned char*)lodepng_malloc(src->unknown_chunks_size[i]); if(!dest->unknown_chunks_data[i] && dest->unknown_chunks_size[i]) return 83; /*alloc fail*/ - for(j = 0; j < src->unknown_chunks_size[i]; ++j) - { + for(j = 0; j < src->unknown_chunks_size[i]; ++j) { dest->unknown_chunks_data[i][j] = src->unknown_chunks_data[i][j]; } } @@ -2848,18 +2550,15 @@ static unsigned LodePNGUnknownChunks_copy(LodePNGInfo* dest, const LodePNGInfo* /******************************************************************************/ -static void LodePNGText_init(LodePNGInfo* info) -{ +static void LodePNGText_init(LodePNGInfo* info) { info->text_num = 0; info->text_keys = NULL; info->text_strings = NULL; } -static void LodePNGText_cleanup(LodePNGInfo* info) -{ +static void LodePNGText_cleanup(LodePNGInfo* info) { size_t i; - for(i = 0; i != info->text_num; ++i) - { + for(i = 0; i != info->text_num; ++i) { string_cleanup(&info->text_keys[i]); string_cleanup(&info->text_strings[i]); } @@ -2867,30 +2566,25 @@ static void LodePNGText_cleanup(LodePNGInfo* info) lodepng_free(info->text_strings); } -static unsigned LodePNGText_copy(LodePNGInfo* dest, const LodePNGInfo* source) -{ +static unsigned LodePNGText_copy(LodePNGInfo* dest, const LodePNGInfo* source) { size_t i = 0; dest->text_keys = 0; dest->text_strings = 0; dest->text_num = 0; - for(i = 0; i != source->text_num; ++i) - { + for(i = 0; i != source->text_num; ++i) { CERROR_TRY_RETURN(lodepng_add_text(dest, source->text_keys[i], source->text_strings[i])); } return 0; } -void lodepng_clear_text(LodePNGInfo* info) -{ +void lodepng_clear_text(LodePNGInfo* info) { LodePNGText_cleanup(info); } -unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str) -{ +unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str) { char** new_keys = (char**)(lodepng_realloc(info->text_keys, sizeof(char*) * (info->text_num + 1))); char** new_strings = (char**)(lodepng_realloc(info->text_strings, sizeof(char*) * (info->text_num + 1))); - if(!new_keys || !new_strings) - { + if(!new_keys || !new_strings) { lodepng_free(new_keys); lodepng_free(new_strings); return 83; /*alloc fail*/ @@ -2908,8 +2602,7 @@ unsigned lodepng_add_text(LodePNGInfo* info, const char* key, const char* str) /******************************************************************************/ -static void LodePNGIText_init(LodePNGInfo* info) -{ +static void LodePNGIText_init(LodePNGInfo* info) { info->itext_num = 0; info->itext_keys = NULL; info->itext_langtags = NULL; @@ -2917,11 +2610,9 @@ static void LodePNGIText_init(LodePNGInfo* info) info->itext_strings = NULL; } -static void LodePNGIText_cleanup(LodePNGInfo* info) -{ +static void LodePNGIText_cleanup(LodePNGInfo* info) { size_t i; - for(i = 0; i != info->itext_num; ++i) - { + for(i = 0; i != info->itext_num; ++i) { string_cleanup(&info->itext_keys[i]); string_cleanup(&info->itext_langtags[i]); string_cleanup(&info->itext_transkeys[i]); @@ -2933,36 +2624,31 @@ static void LodePNGIText_cleanup(LodePNGInfo* info) lodepng_free(info->itext_strings); } -static unsigned LodePNGIText_copy(LodePNGInfo* dest, const LodePNGInfo* source) -{ +static unsigned LodePNGIText_copy(LodePNGInfo* dest, const LodePNGInfo* source) { size_t i = 0; dest->itext_keys = 0; dest->itext_langtags = 0; dest->itext_transkeys = 0; dest->itext_strings = 0; dest->itext_num = 0; - for(i = 0; i != source->itext_num; ++i) - { + for(i = 0; i != source->itext_num; ++i) { CERROR_TRY_RETURN(lodepng_add_itext(dest, source->itext_keys[i], source->itext_langtags[i], source->itext_transkeys[i], source->itext_strings[i])); } return 0; } -void lodepng_clear_itext(LodePNGInfo* info) -{ +void lodepng_clear_itext(LodePNGInfo* info) { LodePNGIText_cleanup(info); } unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langtag, - const char* transkey, const char* str) -{ + const char* transkey, const char* str) { char** new_keys = (char**)(lodepng_realloc(info->itext_keys, sizeof(char*) * (info->itext_num + 1))); char** new_langtags = (char**)(lodepng_realloc(info->itext_langtags, sizeof(char*) * (info->itext_num + 1))); char** new_transkeys = (char**)(lodepng_realloc(info->itext_transkeys, sizeof(char*) * (info->itext_num + 1))); char** new_strings = (char**)(lodepng_realloc(info->itext_strings, sizeof(char*) * (info->itext_num + 1))); - if(!new_keys || !new_langtags || !new_transkeys || !new_strings) - { + if(!new_keys || !new_langtags || !new_transkeys || !new_strings) { lodepng_free(new_keys); lodepng_free(new_langtags); lodepng_free(new_transkeys); @@ -2985,8 +2671,7 @@ unsigned lodepng_add_itext(LodePNGInfo* info, const char* key, const char* langt } /* same as set but does not delete */ -static unsigned lodepng_assign_icc(LodePNGInfo* info, const char* name, const unsigned char* profile, unsigned profile_size) -{ +static unsigned lodepng_assign_icc(LodePNGInfo* info, const char* name, const unsigned char* profile, unsigned profile_size) { info->iccp_name = alloc_string(name); info->iccp_profile = (unsigned char*)lodepng_malloc(profile_size); @@ -2998,15 +2683,13 @@ static unsigned lodepng_assign_icc(LodePNGInfo* info, const char* name, const un return 0; /*ok*/ } -unsigned lodepng_set_icc(LodePNGInfo* info, const char* name, const unsigned char* profile, unsigned profile_size) -{ +unsigned lodepng_set_icc(LodePNGInfo* info, const char* name, const unsigned char* profile, unsigned profile_size) { if(info->iccp_name) lodepng_clear_icc(info); return lodepng_assign_icc(info, name, profile, profile_size); } -void lodepng_clear_icc(LodePNGInfo* info) -{ +void lodepng_clear_icc(LodePNGInfo* info) { string_cleanup(&info->iccp_name); lodepng_free(info->iccp_profile); info->iccp_profile = NULL; @@ -3014,8 +2697,7 @@ void lodepng_clear_icc(LodePNGInfo* info) } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ -void lodepng_info_init(LodePNGInfo* info) -{ +void lodepng_info_init(LodePNGInfo* info) { lodepng_color_mode_init(&info->color); info->interlace_method = 0; info->compression_method = 0; @@ -3041,8 +2723,7 @@ void lodepng_info_init(LodePNGInfo* info) #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ } -void lodepng_info_cleanup(LodePNGInfo* info) -{ +void lodepng_info_cleanup(LodePNGInfo* info) { lodepng_color_mode_cleanup(&info->color); #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS LodePNGText_cleanup(info); @@ -3054,8 +2735,7 @@ void lodepng_info_cleanup(LodePNGInfo* info) #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ } -unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source) -{ +unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source) { lodepng_info_cleanup(dest); *dest = *source; lodepng_color_mode_init(&dest->color); @@ -3064,8 +2744,7 @@ unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source) #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS CERROR_TRY_RETURN(LodePNGText_copy(dest, source)); CERROR_TRY_RETURN(LodePNGIText_copy(dest, source)); - if(source->iccp_defined) - { + if(source->iccp_defined) { CERROR_TRY_RETURN(lodepng_assign_icc(dest, source->iccp_name, source->iccp_profile, source->iccp_profile_size)); } @@ -3078,8 +2757,7 @@ unsigned lodepng_info_copy(LodePNGInfo* dest, const LodePNGInfo* source) /* ////////////////////////////////////////////////////////////////////////// */ /*index: bitgroup index, bits: bitgroup size(1, 2 or 4), in: bitgroup value, out: octet array to add bits to*/ -static void addColorBits(unsigned char* out, size_t index, unsigned bits, unsigned in) -{ +static void addColorBits(unsigned char* out, size_t index, unsigned bits, unsigned in) { unsigned m = bits == 1 ? 7 : bits == 2 ? 3 : 1; /*8 / bits - 1*/ /*p = the partial index in the byte, e.g. with 4 palettebits it is 0 for first half or 1 for second half*/ unsigned p = index & m; @@ -3097,26 +2775,21 @@ This is the data structure used to count the number of unique colors and to get index for a color. It's like an octree, but because the alpha channel is used too, each node has 16 instead of 8 children. */ -struct ColorTree -{ +struct ColorTree { ColorTree* children[16]; /*up to 16 pointers to ColorTree of next level*/ int index; /*the payload. Only has a meaningful value if this is in the last level*/ }; -static void color_tree_init(ColorTree* tree) -{ +static void color_tree_init(ColorTree* tree) { int i; for(i = 0; i != 16; ++i) tree->children[i] = 0; tree->index = -1; } -static void color_tree_cleanup(ColorTree* tree) -{ +static void color_tree_cleanup(ColorTree* tree) { int i; - for(i = 0; i != 16; ++i) - { - if(tree->children[i]) - { + for(i = 0; i != 16; ++i) { + if(tree->children[i]) { color_tree_cleanup(tree->children[i]); lodepng_free(tree->children[i]); } @@ -3124,11 +2797,9 @@ static void color_tree_cleanup(ColorTree* tree) } /*returns -1 if color not present, its index otherwise*/ -static int color_tree_get(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a) -{ +static int color_tree_get(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a) { int bit = 0; - for(bit = 0; bit < 8; ++bit) - { + for(bit = 0; bit < 8; ++bit) { int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1); if(!tree->children[i]) return -1; else tree = tree->children[i]; @@ -3137,8 +2808,7 @@ static int color_tree_get(ColorTree* tree, unsigned char r, unsigned char g, uns } #ifdef LODEPNG_COMPILE_ENCODER -static int color_tree_has(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a) -{ +static int color_tree_has(ColorTree* tree, unsigned char r, unsigned char g, unsigned char b, unsigned char a) { return color_tree_get(tree, r, g, b, a) >= 0; } #endif /*LODEPNG_COMPILE_ENCODER*/ @@ -3146,14 +2816,11 @@ static int color_tree_has(ColorTree* tree, unsigned char r, unsigned char g, uns /*color is not allowed to already exist. Index should be >= 0 (it's signed to be compatible with using -1 for "doesn't exist")*/ static void color_tree_add(ColorTree* tree, - unsigned char r, unsigned char g, unsigned char b, unsigned char a, unsigned index) -{ + unsigned char r, unsigned char g, unsigned char b, unsigned char a, unsigned index) { int bit; - for(bit = 0; bit < 8; ++bit) - { + for(bit = 0; bit < 8; ++bit) { int i = 8 * ((r >> bit) & 1) + 4 * ((g >> bit) & 1) + 2 * ((b >> bit) & 1) + 1 * ((a >> bit) & 1); - if(!tree->children[i]) - { + if(!tree->children[i]) { tree->children[i] = (ColorTree*)lodepng_malloc(sizeof(ColorTree)); color_tree_init(tree->children[i]); } @@ -3165,67 +2832,47 @@ static void color_tree_add(ColorTree* tree, /*put a pixel, given its RGBA color, into image of any color type*/ static unsigned rgba8ToPixel(unsigned char* out, size_t i, const LodePNGColorMode* mode, ColorTree* tree /*for palette*/, - unsigned char r, unsigned char g, unsigned char b, unsigned char a) -{ - if(mode->colortype == LCT_GREY) - { - unsigned char grey = r; /*((unsigned short)r + g + b) / 3*/; + unsigned char r, unsigned char g, unsigned char b, unsigned char a) { + if(mode->colortype == LCT_GREY) { + unsigned char grey = r; /*((unsigned short)r + g + b) / 3;*/ if(mode->bitdepth == 8) out[i] = grey; else if(mode->bitdepth == 16) out[i * 2 + 0] = out[i * 2 + 1] = grey; - else - { + else { /*take the most significant bits of grey*/ grey = (grey >> (8 - mode->bitdepth)) & ((1 << mode->bitdepth) - 1); addColorBits(out, i, mode->bitdepth, grey); } - } - else if(mode->colortype == LCT_RGB) - { - if(mode->bitdepth == 8) - { + } else if(mode->colortype == LCT_RGB) { + if(mode->bitdepth == 8) { out[i * 3 + 0] = r; out[i * 3 + 1] = g; out[i * 3 + 2] = b; - } - else - { + } else { out[i * 6 + 0] = out[i * 6 + 1] = r; out[i * 6 + 2] = out[i * 6 + 3] = g; out[i * 6 + 4] = out[i * 6 + 5] = b; } - } - else if(mode->colortype == LCT_PALETTE) - { + } else if(mode->colortype == LCT_PALETTE) { int index = color_tree_get(tree, r, g, b, a); if(index < 0) return 82; /*color not in palette*/ if(mode->bitdepth == 8) out[i] = index; else addColorBits(out, i, mode->bitdepth, (unsigned)index); - } - else if(mode->colortype == LCT_GREY_ALPHA) - { - unsigned char grey = r; /*((unsigned short)r + g + b) / 3*/; - if(mode->bitdepth == 8) - { + } else if(mode->colortype == LCT_GREY_ALPHA) { + unsigned char grey = r; /*((unsigned short)r + g + b) / 3;*/ + if(mode->bitdepth == 8) { out[i * 2 + 0] = grey; out[i * 2 + 1] = a; - } - else if(mode->bitdepth == 16) - { + } else if(mode->bitdepth == 16) { out[i * 4 + 0] = out[i * 4 + 1] = grey; out[i * 4 + 2] = out[i * 4 + 3] = a; } - } - else if(mode->colortype == LCT_RGBA) - { - if(mode->bitdepth == 8) - { + } else if(mode->colortype == LCT_RGBA) { + if(mode->bitdepth == 8) { out[i * 4 + 0] = r; out[i * 4 + 1] = g; out[i * 4 + 2] = b; out[i * 4 + 3] = a; - } - else - { + } else { out[i * 8 + 0] = out[i * 8 + 1] = r; out[i * 8 + 2] = out[i * 8 + 3] = g; out[i * 8 + 4] = out[i * 8 + 5] = b; @@ -3239,33 +2886,25 @@ static unsigned rgba8ToPixel(unsigned char* out, size_t i, /*put a pixel, given its RGBA16 color, into image of any color 16-bitdepth type*/ static void rgba16ToPixel(unsigned char* out, size_t i, const LodePNGColorMode* mode, - unsigned short r, unsigned short g, unsigned short b, unsigned short a) -{ - if(mode->colortype == LCT_GREY) - { - unsigned short grey = r; /*((unsigned)r + g + b) / 3*/; + unsigned short r, unsigned short g, unsigned short b, unsigned short a) { + if(mode->colortype == LCT_GREY) { + unsigned short grey = r; /*((unsigned)r + g + b) / 3;*/ out[i * 2 + 0] = (grey >> 8) & 255; out[i * 2 + 1] = grey & 255; - } - else if(mode->colortype == LCT_RGB) - { + } else if(mode->colortype == LCT_RGB) { out[i * 6 + 0] = (r >> 8) & 255; out[i * 6 + 1] = r & 255; out[i * 6 + 2] = (g >> 8) & 255; out[i * 6 + 3] = g & 255; out[i * 6 + 4] = (b >> 8) & 255; out[i * 6 + 5] = b & 255; - } - else if(mode->colortype == LCT_GREY_ALPHA) - { - unsigned short grey = r; /*((unsigned)r + g + b) / 3*/; + } else if(mode->colortype == LCT_GREY_ALPHA) { + unsigned short grey = r; /*((unsigned)r + g + b) / 3;*/ out[i * 4 + 0] = (grey >> 8) & 255; out[i * 4 + 1] = grey & 255; out[i * 4 + 2] = (a >> 8) & 255; out[i * 4 + 3] = a & 255; - } - else if(mode->colortype == LCT_RGBA) - { + } else if(mode->colortype == LCT_RGBA) { out[i * 8 + 0] = (r >> 8) & 255; out[i * 8 + 1] = r & 255; out[i * 8 + 2] = (g >> 8) & 255; @@ -3281,24 +2920,17 @@ static void rgba16ToPixel(unsigned char* out, size_t i, static void getPixelColorRGBA8(unsigned char* r, unsigned char* g, unsigned char* b, unsigned char* a, const unsigned char* in, size_t i, - const LodePNGColorMode* mode) -{ - if(mode->colortype == LCT_GREY) - { - if(mode->bitdepth == 8) - { + const LodePNGColorMode* mode) { + if(mode->colortype == LCT_GREY) { + if(mode->bitdepth == 8) { *r = *g = *b = in[i]; if(mode->key_defined && *r == mode->key_r) *a = 0; else *a = 255; - } - else if(mode->bitdepth == 16) - { + } else if(mode->bitdepth == 16) { *r = *g = *b = in[i * 2 + 0]; if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0; else *a = 255; - } - else - { + } else { unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/ size_t j = i * mode->bitdepth; unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth); @@ -3306,17 +2938,12 @@ static void getPixelColorRGBA8(unsigned char* r, unsigned char* g, if(mode->key_defined && value == mode->key_r) *a = 0; else *a = 255; } - } - else if(mode->colortype == LCT_RGB) - { - if(mode->bitdepth == 8) - { + } else if(mode->colortype == LCT_RGB) { + if(mode->bitdepth == 8) { *r = in[i * 3 + 0]; *g = in[i * 3 + 1]; *b = in[i * 3 + 2]; if(mode->key_defined && *r == mode->key_r && *g == mode->key_g && *b == mode->key_b) *a = 0; else *a = 255; - } - else - { + } else { *r = in[i * 6 + 0]; *g = in[i * 6 + 2]; *b = in[i * 6 + 4]; @@ -3325,56 +2952,40 @@ static void getPixelColorRGBA8(unsigned char* r, unsigned char* g, && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0; else *a = 255; } - } - else if(mode->colortype == LCT_PALETTE) - { + } else if(mode->colortype == LCT_PALETTE) { unsigned index; if(mode->bitdepth == 8) index = in[i]; - else - { + else { size_t j = i * mode->bitdepth; index = readBitsFromReversedStream(&j, in, mode->bitdepth); } - if(index >= mode->palettesize) - { + if(index >= mode->palettesize) { /*This is an error according to the PNG spec, but common PNG decoders make it black instead. Done here too, slightly faster due to no error handling needed.*/ *r = *g = *b = 0; *a = 255; - } - else - { + } else { *r = mode->palette[index * 4 + 0]; *g = mode->palette[index * 4 + 1]; *b = mode->palette[index * 4 + 2]; *a = mode->palette[index * 4 + 3]; } - } - else if(mode->colortype == LCT_GREY_ALPHA) - { - if(mode->bitdepth == 8) - { + } else if(mode->colortype == LCT_GREY_ALPHA) { + if(mode->bitdepth == 8) { *r = *g = *b = in[i * 2 + 0]; *a = in[i * 2 + 1]; - } - else - { + } else { *r = *g = *b = in[i * 4 + 0]; *a = in[i * 4 + 2]; } - } - else if(mode->colortype == LCT_RGBA) - { - if(mode->bitdepth == 8) - { + } else if(mode->colortype == LCT_RGBA) { + if(mode->bitdepth == 8) { *r = in[i * 4 + 0]; *g = in[i * 4 + 1]; *b = in[i * 4 + 2]; *a = in[i * 4 + 3]; - } - else - { + } else { *r = in[i * 8 + 0]; *g = in[i * 8 + 2]; *b = in[i * 8 + 4]; @@ -3390,57 +3001,40 @@ enough memory, if has_alpha is true the output is RGBA. mode has the color mode of the input buffer.*/ static void getPixelColorsRGBA8(unsigned char* buffer, size_t numpixels, unsigned has_alpha, const unsigned char* in, - const LodePNGColorMode* mode) -{ + const LodePNGColorMode* mode) { unsigned num_channels = has_alpha ? 4 : 3; size_t i; - if(mode->colortype == LCT_GREY) - { - if(mode->bitdepth == 8) - { - for(i = 0; i != numpixels; ++i, buffer += num_channels) - { + if(mode->colortype == LCT_GREY) { + if(mode->bitdepth == 8) { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { buffer[0] = buffer[1] = buffer[2] = in[i]; if(has_alpha) buffer[3] = mode->key_defined && in[i] == mode->key_r ? 0 : 255; } - } - else if(mode->bitdepth == 16) - { - for(i = 0; i != numpixels; ++i, buffer += num_channels) - { + } else if(mode->bitdepth == 16) { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { buffer[0] = buffer[1] = buffer[2] = in[i * 2]; if(has_alpha) buffer[3] = mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r ? 0 : 255; } - } - else - { + } else { unsigned highest = ((1U << mode->bitdepth) - 1U); /*highest possible value for this bit depth*/ size_t j = 0; - for(i = 0; i != numpixels; ++i, buffer += num_channels) - { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { unsigned value = readBitsFromReversedStream(&j, in, mode->bitdepth); buffer[0] = buffer[1] = buffer[2] = (value * 255) / highest; if(has_alpha) buffer[3] = mode->key_defined && value == mode->key_r ? 0 : 255; } } - } - else if(mode->colortype == LCT_RGB) - { - if(mode->bitdepth == 8) - { - for(i = 0; i != numpixels; ++i, buffer += num_channels) - { + } else if(mode->colortype == LCT_RGB) { + if(mode->bitdepth == 8) { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { buffer[0] = in[i * 3 + 0]; buffer[1] = in[i * 3 + 1]; buffer[2] = in[i * 3 + 2]; if(has_alpha) buffer[3] = mode->key_defined && buffer[0] == mode->key_r && buffer[1]== mode->key_g && buffer[2] == mode->key_b ? 0 : 255; } - } - else - { - for(i = 0; i != numpixels; ++i, buffer += num_channels) - { + } else { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { buffer[0] = in[i * 6 + 0]; buffer[1] = in[i * 6 + 2]; buffer[2] = in[i * 6 + 4]; @@ -3450,67 +3044,47 @@ static void getPixelColorsRGBA8(unsigned char* buffer, size_t numpixels, && 256U * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b ? 0 : 255; } } - } - else if(mode->colortype == LCT_PALETTE) - { + } else if(mode->colortype == LCT_PALETTE) { unsigned index; size_t j = 0; - for(i = 0; i != numpixels; ++i, buffer += num_channels) - { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { if(mode->bitdepth == 8) index = in[i]; else index = readBitsFromReversedStream(&j, in, mode->bitdepth); - if(index >= mode->palettesize) - { + if(index >= mode->palettesize) { /*This is an error according to the PNG spec, but most PNG decoders make it black instead. Done here too, slightly faster due to no error handling needed.*/ buffer[0] = buffer[1] = buffer[2] = 0; if(has_alpha) buffer[3] = 255; - } - else - { + } else { buffer[0] = mode->palette[index * 4 + 0]; buffer[1] = mode->palette[index * 4 + 1]; buffer[2] = mode->palette[index * 4 + 2]; if(has_alpha) buffer[3] = mode->palette[index * 4 + 3]; } } - } - else if(mode->colortype == LCT_GREY_ALPHA) - { - if(mode->bitdepth == 8) - { - for(i = 0; i != numpixels; ++i, buffer += num_channels) - { + } else if(mode->colortype == LCT_GREY_ALPHA) { + if(mode->bitdepth == 8) { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { buffer[0] = buffer[1] = buffer[2] = in[i * 2 + 0]; if(has_alpha) buffer[3] = in[i * 2 + 1]; } - } - else - { - for(i = 0; i != numpixels; ++i, buffer += num_channels) - { + } else { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { buffer[0] = buffer[1] = buffer[2] = in[i * 4 + 0]; if(has_alpha) buffer[3] = in[i * 4 + 2]; } } - } - else if(mode->colortype == LCT_RGBA) - { - if(mode->bitdepth == 8) - { - for(i = 0; i != numpixels; ++i, buffer += num_channels) - { + } else if(mode->colortype == LCT_RGBA) { + if(mode->bitdepth == 8) { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { buffer[0] = in[i * 4 + 0]; buffer[1] = in[i * 4 + 1]; buffer[2] = in[i * 4 + 2]; if(has_alpha) buffer[3] = in[i * 4 + 3]; } - } - else - { - for(i = 0; i != numpixels; ++i, buffer += num_channels) - { + } else { + for(i = 0; i != numpixels; ++i, buffer += num_channels) { buffer[0] = in[i * 8 + 0]; buffer[1] = in[i * 8 + 2]; buffer[2] = in[i * 8 + 4]; @@ -3523,16 +3097,12 @@ static void getPixelColorsRGBA8(unsigned char* buffer, size_t numpixels, /*Get RGBA16 color of pixel with index i (y * width + x) from the raw image with given color type, but the given color type must be 16-bit itself.*/ static void getPixelColorRGBA16(unsigned short* r, unsigned short* g, unsigned short* b, unsigned short* a, - const unsigned char* in, size_t i, const LodePNGColorMode* mode) -{ - if(mode->colortype == LCT_GREY) - { + const unsigned char* in, size_t i, const LodePNGColorMode* mode) { + if(mode->colortype == LCT_GREY) { *r = *g = *b = 256 * in[i * 2 + 0] + in[i * 2 + 1]; if(mode->key_defined && 256U * in[i * 2 + 0] + in[i * 2 + 1] == mode->key_r) *a = 0; else *a = 65535; - } - else if(mode->colortype == LCT_RGB) - { + } else if(mode->colortype == LCT_RGB) { *r = 256u * in[i * 6 + 0] + in[i * 6 + 1]; *g = 256u * in[i * 6 + 2] + in[i * 6 + 3]; *b = 256u * in[i * 6 + 4] + in[i * 6 + 5]; @@ -3541,14 +3111,10 @@ static void getPixelColorRGBA16(unsigned short* r, unsigned short* g, unsigned s && 256u * in[i * 6 + 2] + in[i * 6 + 3] == mode->key_g && 256u * in[i * 6 + 4] + in[i * 6 + 5] == mode->key_b) *a = 0; else *a = 65535; - } - else if(mode->colortype == LCT_GREY_ALPHA) - { + } else if(mode->colortype == LCT_GREY_ALPHA) { *r = *g = *b = 256u * in[i * 4 + 0] + in[i * 4 + 1]; *a = 256u * in[i * 4 + 2] + in[i * 4 + 3]; - } - else if(mode->colortype == LCT_RGBA) - { + } else if(mode->colortype == LCT_RGBA) { *r = 256u * in[i * 8 + 0] + in[i * 8 + 1]; *g = 256u * in[i * 8 + 2] + in[i * 8 + 3]; *b = 256u * in[i * 8 + 4] + in[i * 8 + 5]; @@ -3558,37 +3124,32 @@ static void getPixelColorRGBA16(unsigned short* r, unsigned short* g, unsigned s unsigned lodepng_convert(unsigned char* out, const unsigned char* in, const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in, - unsigned w, unsigned h) -{ + unsigned w, unsigned h) { size_t i; ColorTree tree; size_t numpixels = (size_t)w * (size_t)h; unsigned error = 0; - if(lodepng_color_mode_equal(mode_out, mode_in)) - { + if(lodepng_color_mode_equal(mode_out, mode_in)) { size_t numbytes = lodepng_get_raw_size(w, h, mode_in); for(i = 0; i != numbytes; ++i) out[i] = in[i]; return 0; } - if(mode_out->colortype == LCT_PALETTE) - { + if(mode_out->colortype == LCT_PALETTE) { size_t palettesize = mode_out->palettesize; const unsigned char* palette = mode_out->palette; size_t palsize = (size_t)1u << mode_out->bitdepth; /*if the user specified output palette but did not give the values, assume they want the values of the input color type (assuming that one is palette). Note that we never create a new palette ourselves.*/ - if(palettesize == 0) - { + if(palettesize == 0) { palettesize = mode_in->palettesize; palette = mode_in->palette; /*if the input was also palette with same bitdepth, then the color types are also equal, so copy literally. This to preserve the exact indices that were in the PNG even in case there are duplicate colors in the palette.*/ - if (mode_in->colortype == LCT_PALETTE && mode_in->bitdepth == mode_out->bitdepth) - { + if (mode_in->colortype == LCT_PALETTE && mode_in->bitdepth == mode_out->bitdepth) { size_t numbytes = lodepng_get_raw_size(w, h, mode_in); for(i = 0; i != numbytes; ++i) out[i] = in[i]; return 0; @@ -3596,43 +3157,32 @@ unsigned lodepng_convert(unsigned char* out, const unsigned char* in, } if(palettesize < palsize) palsize = palettesize; color_tree_init(&tree); - for(i = 0; i != palsize; ++i) - { + for(i = 0; i != palsize; ++i) { const unsigned char* p = &palette[i * 4]; color_tree_add(&tree, p[0], p[1], p[2], p[3], (unsigned)i); } } - if(mode_in->bitdepth == 16 && mode_out->bitdepth == 16) - { - for(i = 0; i != numpixels; ++i) - { + if(mode_in->bitdepth == 16 && mode_out->bitdepth == 16) { + for(i = 0; i != numpixels; ++i) { unsigned short r = 0, g = 0, b = 0, a = 0; getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in); rgba16ToPixel(out, i, mode_out, r, g, b, a); } - } - else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGBA) - { + } else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGBA) { getPixelColorsRGBA8(out, numpixels, 1, in, mode_in); - } - else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGB) - { + } else if(mode_out->bitdepth == 8 && mode_out->colortype == LCT_RGB) { getPixelColorsRGBA8(out, numpixels, 0, in, mode_in); - } - else - { + } else { unsigned char r = 0, g = 0, b = 0, a = 0; - for(i = 0; i != numpixels; ++i) - { + for(i = 0; i != numpixels; ++i) { getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in); error = rgba8ToPixel(out, i, mode_out, &tree, r, g, b, a); if (error) break; } } - if(mode_out->colortype == LCT_PALETTE) - { + if(mode_out->colortype == LCT_PALETTE) { color_tree_cleanup(&tree); } @@ -3649,63 +3199,47 @@ any palette index but doesn't have an alpha channel. Idem with ignoring color ke unsigned lodepng_convert_rgb( unsigned* r_out, unsigned* g_out, unsigned* b_out, unsigned r_in, unsigned g_in, unsigned b_in, - const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in) -{ + const LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in) { unsigned r = 0, g = 0, b = 0; unsigned mul = 65535 / ((1u << mode_in->bitdepth) - 1u); /*65535, 21845, 4369, 257, 1*/ unsigned shift = 16 - mode_out->bitdepth; - if(mode_in->colortype == LCT_GREY || mode_in->colortype == LCT_GREY_ALPHA) - { + if(mode_in->colortype == LCT_GREY || mode_in->colortype == LCT_GREY_ALPHA) { r = g = b = r_in * mul; - } - else if(mode_in->colortype == LCT_RGB || mode_in->colortype == LCT_RGBA) - { + } else if(mode_in->colortype == LCT_RGB || mode_in->colortype == LCT_RGBA) { r = r_in * mul; g = g_in * mul; b = b_in * mul; - } - else if(mode_in->colortype == LCT_PALETTE) - { + } else if(mode_in->colortype == LCT_PALETTE) { if(r_in >= mode_in->palettesize) return 82; r = mode_in->palette[r_in * 4 + 0] * 257u; g = mode_in->palette[r_in * 4 + 1] * 257u; b = mode_in->palette[r_in * 4 + 2] * 257u; - } - else - { + } else { return 31; } /* now convert to output format */ - if(mode_out->colortype == LCT_GREY || mode_out->colortype == LCT_GREY_ALPHA) - { + if(mode_out->colortype == LCT_GREY || mode_out->colortype == LCT_GREY_ALPHA) { *r_out = r >> shift ; - } - else if(mode_out->colortype == LCT_RGB || mode_out->colortype == LCT_RGBA) - { + } else if(mode_out->colortype == LCT_RGB || mode_out->colortype == LCT_RGBA) { *r_out = r >> shift ; *g_out = g >> shift ; *b_out = b >> shift ; - } - else if(mode_out->colortype == LCT_PALETTE) - { + } else if(mode_out->colortype == LCT_PALETTE) { unsigned i; /* a 16-bit color cannot be in the palette */ if((r >> 8) != (r & 255) || (g >> 8) != (g & 255) || (b >> 8) != (b & 255)) return 82; for(i = 0; i < mode_out->palettesize; i++) { unsigned j = i * 4; if((r >> 8) == mode_out->palette[j + 0] && (g >> 8) == mode_out->palette[j + 1] && - (b >> 8) == mode_out->palette[j + 2]) - { + (b >> 8) == mode_out->palette[j + 2]) { *r_out = i; return 0; } } return 82; - } - else - { + } else { return 31; } @@ -3714,8 +3248,7 @@ unsigned lodepng_convert_rgb( #ifdef LODEPNG_COMPILE_ENCODER -void lodepng_color_profile_init(LodePNGColorProfile* profile) -{ +void lodepng_color_profile_init(LodePNGColorProfile* profile) { profile->colored = 0; profile->key = 0; profile->key_r = profile->key_g = profile->key_b = 0; @@ -3726,8 +3259,7 @@ void lodepng_color_profile_init(LodePNGColorProfile* profile) } /*function used for debug purposes with C++*/ -/*void printColorProfile(LodePNGColorProfile* p) -{ +/*void printColorProfile(LodePNGColorProfile* p) { std::cout << "colored: " << (int)p->colored << ", "; std::cout << "key: " << (int)p->key << ", "; std::cout << "key_r: " << (int)p->key_r << ", "; @@ -3739,8 +3271,7 @@ void lodepng_color_profile_init(LodePNGColorProfile* profile) }*/ /*Returns how many bits needed to represent given value (max 8 bit)*/ -static unsigned getValueRequiredBits(unsigned char value) -{ +static unsigned getValueRequiredBits(unsigned char value) { if(value == 0 || value == 255) return 1; /*The scaling of 2-bit and 4-bit values uses multiples of 85 and 17*/ if(value % 17 == 0) return value % 85 == 0 ? 2 : 4; @@ -3751,8 +3282,7 @@ static unsigned getValueRequiredBits(unsigned char value) It's ok to set some parameters of profile to done already.*/ unsigned lodepng_get_color_profile(LodePNGColorProfile* profile, const unsigned char* in, unsigned w, unsigned h, - const LodePNGColorMode* mode_in) -{ + const LodePNGColorMode* mode_in) { unsigned error = 0; size_t i; ColorTree tree; @@ -3780,25 +3310,20 @@ unsigned lodepng_get_color_profile(LodePNGColorProfile* profile, if(profile->bits >= bpp) bits_done = 1; if(profile->numcolors >= maxnumcolors) numcolors_done = 1; - if(!numcolors_done) - { - for(i = 0; i < profile->numcolors; i++) - { + if(!numcolors_done) { + for(i = 0; i < profile->numcolors; i++) { const unsigned char* color = &profile->palette[i * 4]; color_tree_add(&tree, color[0], color[1], color[2], color[3], i); } } /*Check if the 16-bit input is truly 16-bit*/ - if(mode_in->bitdepth == 16 && !sixteen) - { + if(mode_in->bitdepth == 16 && !sixteen) { unsigned short r, g, b, a; - for(i = 0; i != numpixels; ++i) - { + for(i = 0; i != numpixels; ++i) { getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in); if((r & 255) != ((r >> 8) & 255) || (g & 255) != ((g >> 8) & 255) || - (b & 255) != ((b >> 8) & 255) || (a & 255) != ((a >> 8) & 255)) /*first and second byte differ*/ - { + (b & 255) != ((b >> 8) & 255) || (a & 255) != ((a >> 8) & 255)) /*first and second byte differ*/ { profile->bits = 16; sixteen = 1; bits_done = 1; @@ -3808,38 +3333,29 @@ unsigned lodepng_get_color_profile(LodePNGColorProfile* profile, } } - if(sixteen) - { + if(sixteen) { unsigned short r = 0, g = 0, b = 0, a = 0; - for(i = 0; i != numpixels; ++i) - { + for(i = 0; i != numpixels; ++i) { getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in); - if(!colored_done && (r != g || r != b)) - { + if(!colored_done && (r != g || r != b)) { profile->colored = 1; colored_done = 1; } - if(!alpha_done) - { + if(!alpha_done) { unsigned matchkey = (r == profile->key_r && g == profile->key_g && b == profile->key_b); - if(a != 65535 && (a != 0 || (profile->key && !matchkey))) - { + if(a != 65535 && (a != 0 || (profile->key && !matchkey))) { profile->alpha = 1; profile->key = 0; alpha_done = 1; - } - else if(a == 0 && !profile->alpha && !profile->key) - { + } else if(a == 0 && !profile->alpha && !profile->key) { profile->key = 1; profile->key_r = r; profile->key_g = g; profile->key_b = b; - } - else if(a == 65535 && profile->key && matchkey) - { + } else if(a == 65535 && profile->key && matchkey) { /* Color key cannot be used if an opaque pixel also has that RGB color. */ profile->alpha = 1; profile->key = 0; @@ -3849,13 +3365,10 @@ unsigned lodepng_get_color_profile(LodePNGColorProfile* profile, if(alpha_done && numcolors_done && colored_done && bits_done) break; } - if(profile->key && !profile->alpha) - { - for(i = 0; i != numpixels; ++i) - { + if(profile->key && !profile->alpha) { + for(i = 0; i != numpixels; ++i) { getPixelColorRGBA16(&r, &g, &b, &a, in, i, mode_in); - if(a != 0 && r == profile->key_r && g == profile->key_g && b == profile->key_b) - { + if(a != 0 && r == profile->key_r && g == profile->key_g && b == profile->key_b) { /* Color key cannot be used if an opaque pixel also has that RGB color. */ profile->alpha = 1; profile->key = 0; @@ -3863,48 +3376,37 @@ unsigned lodepng_get_color_profile(LodePNGColorProfile* profile, } } } - } - else /* < 16-bit */ - { + } else /* < 16-bit */ { unsigned char r = 0, g = 0, b = 0, a = 0; - for(i = 0; i != numpixels; ++i) - { + for(i = 0; i != numpixels; ++i) { getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in); - if(!bits_done && profile->bits < 8) - { + if(!bits_done && profile->bits < 8) { /*only r is checked, < 8 bits is only relevant for greyscale*/ unsigned bits = getValueRequiredBits(r); if(bits > profile->bits) profile->bits = bits; } bits_done = (profile->bits >= bpp); - if(!colored_done && (r != g || r != b)) - { + if(!colored_done && (r != g || r != b)) { profile->colored = 1; colored_done = 1; if(profile->bits < 8) profile->bits = 8; /*PNG has no colored modes with less than 8-bit per channel*/ } - if(!alpha_done) - { + if(!alpha_done) { unsigned matchkey = (r == profile->key_r && g == profile->key_g && b == profile->key_b); - if(a != 255 && (a != 0 || (profile->key && !matchkey))) - { + if(a != 255 && (a != 0 || (profile->key && !matchkey))) { profile->alpha = 1; profile->key = 0; alpha_done = 1; if(profile->bits < 8) profile->bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ - } - else if(a == 0 && !profile->alpha && !profile->key) - { + } else if(a == 0 && !profile->alpha && !profile->key) { profile->key = 1; profile->key_r = r; profile->key_g = g; profile->key_b = b; - } - else if(a == 255 && profile->key && matchkey) - { + } else if(a == 255 && profile->key && matchkey) { /* Color key cannot be used if an opaque pixel also has that RGB color. */ profile->alpha = 1; profile->key = 0; @@ -3913,13 +3415,10 @@ unsigned lodepng_get_color_profile(LodePNGColorProfile* profile, } } - if(!numcolors_done) - { - if(!color_tree_has(&tree, r, g, b, a)) - { + if(!numcolors_done) { + if(!color_tree_has(&tree, r, g, b, a)) { color_tree_add(&tree, r, g, b, a, profile->numcolors); - if(profile->numcolors < 256) - { + if(profile->numcolors < 256) { unsigned char* p = profile->palette; unsigned n = profile->numcolors; p[n * 4 + 0] = r; @@ -3935,13 +3434,10 @@ unsigned lodepng_get_color_profile(LodePNGColorProfile* profile, if(alpha_done && numcolors_done && colored_done && bits_done) break; } - if(profile->key && !profile->alpha) - { - for(i = 0; i != numpixels; ++i) - { + if(profile->key && !profile->alpha) { + for(i = 0; i != numpixels; ++i) { getPixelColorRGBA8(&r, &g, &b, &a, in, i, mode_in); - if(a != 0 && r == profile->key_r && g == profile->key_g && b == profile->key_b) - { + if(a != 0 && r == profile->key_r && g == profile->key_g && b == profile->key_b) { /* Color key cannot be used if an opaque pixel also has that RGB color. */ profile->alpha = 1; profile->key = 0; @@ -3966,8 +3462,7 @@ unsigned lodepng_get_color_profile(LodePNGColorProfile* profile, (with 2 bytes repeating for 8-bit and 65535 for opaque alpha channel). This function is expensive, do not call it for all pixels of an image but only for a few additional values. */ static unsigned lodepng_color_profile_add(LodePNGColorProfile* profile, - unsigned r, unsigned g, unsigned b, unsigned a) -{ + unsigned r, unsigned g, unsigned b, unsigned a) { unsigned error = 0; unsigned char image[8]; LodePNGColorMode mode; @@ -3986,8 +3481,7 @@ static unsigned lodepng_color_profile_add(LodePNGColorProfile* profile, when relevant.*/ static unsigned auto_choose_color_from_profile(LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in, - const LodePNGColorProfile* prof) -{ + const LodePNGColorProfile* prof) { unsigned error = 0; unsigned palettebits, palette_ok; size_t i, n; @@ -3999,8 +3493,7 @@ static unsigned auto_choose_color_from_profile(LodePNGColorMode* mode_out, mode_out->key_defined = 0; - if(key && numpixels <= 16) - { + if(key && numpixels <= 16) { alpha = 1; /*too few pixels to justify tRNS chunk overhead*/ key = 0; if(bits < 8) bits = 8; /*PNG has no alphachannel modes with less than 8-bit per channel*/ @@ -4011,12 +3504,10 @@ static unsigned auto_choose_color_from_profile(LodePNGColorMode* mode_out, if(numpixels < n * 2) palette_ok = 0; /*don't add palette overhead if image has only a few pixels*/ if(!prof->colored && bits <= palettebits) palette_ok = 0; /*grey is less overhead*/ - if(palette_ok) - { + if(palette_ok) { const unsigned char* p = prof->palette; lodepng_palette_clear(mode_out); /*remove potential earlier palette*/ - for(i = 0; i != prof->numcolors; ++i) - { + for(i = 0; i != prof->numcolors; ++i) { error = lodepng_palette_add(mode_out, p[i * 4 + 0], p[i * 4 + 1], p[i * 4 + 2], p[i * 4 + 3]); if(error) break; } @@ -4025,21 +3516,17 @@ static unsigned auto_choose_color_from_profile(LodePNGColorMode* mode_out, mode_out->bitdepth = palettebits; if(mode_in->colortype == LCT_PALETTE && mode_in->palettesize >= mode_out->palettesize - && mode_in->bitdepth == mode_out->bitdepth) - { + && mode_in->bitdepth == mode_out->bitdepth) { /*If input should have same palette colors, keep original to preserve its order and prevent conversion*/ lodepng_color_mode_cleanup(mode_out); lodepng_color_mode_copy(mode_out, mode_in); } - } - else /*8-bit or 16-bit per channel*/ - { + } else /*8-bit or 16-bit per channel*/ { mode_out->bitdepth = bits; mode_out->colortype = alpha ? (prof->colored ? LCT_RGBA : LCT_GREY_ALPHA) : (prof->colored ? LCT_RGB : LCT_GREY); - if(key) - { + if(key) { unsigned mask = (1u << mode_out->bitdepth) - 1u; /*profile always uses 16-bit, mask converts it*/ mode_out->key_r = prof->key_r & mask; mode_out->key_g = prof->key_g & mask; @@ -4058,8 +3545,7 @@ Updates values of mode with a potentially smaller color model. mode_out should contain the user chosen color model, but will be overwritten with the new chosen one.*/ unsigned lodepng_auto_choose_color(LodePNGColorMode* mode_out, const unsigned char* image, unsigned w, unsigned h, - const LodePNGColorMode* mode_in) -{ + const LodePNGColorMode* mode_in) { unsigned error = 0; LodePNGColorProfile prof; lodepng_color_profile_init(&prof); @@ -4075,8 +3561,7 @@ Paeth predicter, used by PNG filter type 4 The parameters are of type short, but should come from unsigned chars, the shorts are only needed to make the paeth calculation correct. */ -static unsigned char paethPredictor(short a, short b, short c) -{ +static unsigned char paethPredictor(short a, short b, short c) { short pa = abs(b - c); short pb = abs(a - c); short pc = abs(a + b - c - c); @@ -4109,14 +3594,12 @@ bpp: bits per pixel end at a full byte */ static void Adam7_getpassvalues(unsigned passw[7], unsigned passh[7], size_t filter_passstart[8], - size_t padded_passstart[8], size_t passstart[8], unsigned w, unsigned h, unsigned bpp) -{ + size_t padded_passstart[8], size_t passstart[8], unsigned w, unsigned h, unsigned bpp) { /*the passstart values have 8 values: the 8th one indicates the byte after the end of the 7th (= last) pass*/ unsigned i; /*calculate width and height in pixels of each pass*/ - for(i = 0; i != 7; ++i) - { + for(i = 0; i != 7; ++i) { passw[i] = (w + ADAM7_DX[i] - ADAM7_IX[i] - 1) / ADAM7_DX[i]; passh[i] = (h + ADAM7_DY[i] - ADAM7_IY[i] - 1) / ADAM7_DY[i]; if(passw[i] == 0) passh[i] = 0; @@ -4124,8 +3607,7 @@ static void Adam7_getpassvalues(unsigned passw[7], unsigned passh[7], size_t fil } filter_passstart[0] = padded_passstart[0] = passstart[0] = 0; - for(i = 0; i != 7; ++i) - { + for(i = 0; i != 7; ++i) { /*if passw[i] is 0, it's 0 bytes, not 1 (no filtertype-byte)*/ filter_passstart[i + 1] = filter_passstart[i] + ((passw[i] && passh[i]) ? passh[i] * (1 + (passw[i] * bpp + 7) / 8) : 0); @@ -4144,16 +3626,13 @@ static void Adam7_getpassvalues(unsigned passw[7], unsigned passh[7], size_t fil /*read the information from the header and store it in the LodePNGInfo. return value is error*/ unsigned lodepng_inspect(unsigned* w, unsigned* h, LodePNGState* state, - const unsigned char* in, size_t insize) -{ + const unsigned char* in, size_t insize) { unsigned width, height; LodePNGInfo* info = &state->info_png; - if(insize == 0 || in == 0) - { + if(insize == 0 || in == 0) { CERROR_RETURN_ERROR(state->error, 48); /*error: the given data is empty*/ } - if(insize < 33) - { + if(insize < 33) { CERROR_RETURN_ERROR(state->error, 27); /*error: the data length is smaller than the length of a PNG header*/ } @@ -4163,16 +3642,13 @@ unsigned lodepng_inspect(unsigned* w, unsigned* h, LodePNGState* state, lodepng_info_init(info); if(in[0] != 137 || in[1] != 80 || in[2] != 78 || in[3] != 71 - || in[4] != 13 || in[5] != 10 || in[6] != 26 || in[7] != 10) - { + || in[4] != 13 || in[5] != 10 || in[6] != 26 || in[7] != 10) { CERROR_RETURN_ERROR(state->error, 28); /*error: the first 8 bytes are not the correct PNG signature*/ } - if(lodepng_chunk_length(in + 8) != 13) - { + if(lodepng_chunk_length(in + 8) != 13) { CERROR_RETURN_ERROR(state->error, 94); /*error: header size must be 13 bytes*/ } - if(!lodepng_chunk_type_equals(in + 8, "IHDR")) - { + if(!lodepng_chunk_type_equals(in + 8, "IHDR")) { CERROR_RETURN_ERROR(state->error, 29); /*error: it doesn't start with a IHDR chunk!*/ } @@ -4185,20 +3661,17 @@ unsigned lodepng_inspect(unsigned* w, unsigned* h, LodePNGState* state, info->filter_method = in[27]; info->interlace_method = in[28]; - if(width == 0 || height == 0) - { + if(width == 0 || height == 0) { CERROR_RETURN_ERROR(state->error, 93); } if(w) *w = width; if(h) *h = height; - if(!state->decoder.ignore_crc) - { + if(!state->decoder.ignore_crc) { unsigned CRC = lodepng_read32bitInt(&in[29]); unsigned checksum = lodepng_crc32(&in[12], 17); - if(CRC != checksum) - { + if(CRC != checksum) { CERROR_RETURN_ERROR(state->error, 57); /*invalid CRC*/ } } @@ -4215,8 +3688,7 @@ unsigned lodepng_inspect(unsigned* w, unsigned* h, LodePNGState* state, } static unsigned unfilterScanline(unsigned char* recon, const unsigned char* scanline, const unsigned char* precon, - size_t bytewidth, unsigned char filterType, size_t length) -{ + size_t bytewidth, unsigned char filterType, size_t length) { /* For PNG filter method 0 unfilter a PNG image scanline by scanline. when the pixels are smaller than 1 byte, @@ -4227,8 +3699,7 @@ static unsigned unfilterScanline(unsigned char* recon, const unsigned char* scan */ size_t i; - switch(filterType) - { + switch(filterType) { case 0: for(i = 0; i != length; ++i) recon[i] = scanline[i]; break; @@ -4237,47 +3708,34 @@ static unsigned unfilterScanline(unsigned char* recon, const unsigned char* scan for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + recon[i - bytewidth]; break; case 2: - if(precon) - { + if(precon) { for(i = 0; i != length; ++i) recon[i] = scanline[i] + precon[i]; - } - else - { + } else { for(i = 0; i != length; ++i) recon[i] = scanline[i]; } break; case 3: - if(precon) - { + if(precon) { for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i] + (precon[i] >> 1); for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + ((recon[i - bytewidth] + precon[i]) >> 1); - } - else - { + } else { for(i = 0; i != bytewidth; ++i) recon[i] = scanline[i]; for(i = bytewidth; i < length; ++i) recon[i] = scanline[i] + (recon[i - bytewidth] >> 1); } break; case 4: - if(precon) - { - for(i = 0; i != bytewidth; ++i) - { + if(precon) { + for(i = 0; i != bytewidth; ++i) { recon[i] = (scanline[i] + precon[i]); /*paethPredictor(0, precon[i], 0) is always precon[i]*/ } - for(i = bytewidth; i < length; ++i) - { + for(i = bytewidth; i < length; ++i) { recon[i] = (scanline[i] + paethPredictor(recon[i - bytewidth], precon[i], precon[i - bytewidth])); } - } - else - { - for(i = 0; i != bytewidth; ++i) - { + } else { + for(i = 0; i != bytewidth; ++i) { recon[i] = scanline[i]; } - for(i = bytewidth; i < length; ++i) - { + for(i = bytewidth; i < length; ++i) { /*paethPredictor(recon[i - bytewidth], 0, 0) is always recon[i - bytewidth]*/ recon[i] = (scanline[i] + recon[i - bytewidth]); } @@ -4288,8 +3746,7 @@ static unsigned unfilterScanline(unsigned char* recon, const unsigned char* scan return 0; } -static unsigned unfilter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) -{ +static unsigned unfilter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) { /* For PNG filter method 0 this function unfilters a single image (e.g. without interlacing this is called once, with Adam7 seven times) @@ -4305,8 +3762,7 @@ static unsigned unfilter(unsigned char* out, const unsigned char* in, unsigned w size_t bytewidth = (bpp + 7) / 8; size_t linebytes = (w * bpp + 7) / 8; - for(y = 0; y < h; ++y) - { + for(y = 0; y < h; ++y) { size_t outindex = linebytes * y; size_t inindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/ unsigned char filterType = in[inindex]; @@ -4330,47 +3786,37 @@ out must be big enough AND must be 0 everywhere if bpp < 8 in the current implem (because that's likely a little bit faster) NOTE: comments about padding bits are only relevant if bpp < 8 */ -static void Adam7_deinterlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) -{ +static void Adam7_deinterlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) { unsigned passw[7], passh[7]; size_t filter_passstart[8], padded_passstart[8], passstart[8]; unsigned i; Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); - if(bpp >= 8) - { - for(i = 0; i != 7; ++i) - { + if(bpp >= 8) { + for(i = 0; i != 7; ++i) { unsigned x, y, b; size_t bytewidth = bpp / 8; for(y = 0; y < passh[i]; ++y) - for(x = 0; x < passw[i]; ++x) - { + for(x = 0; x < passw[i]; ++x) { size_t pixelinstart = passstart[i] + (y * passw[i] + x) * bytewidth; size_t pixeloutstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth; - for(b = 0; b < bytewidth; ++b) - { + for(b = 0; b < bytewidth; ++b) { out[pixeloutstart + b] = in[pixelinstart + b]; } } } - } - else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/ - { - for(i = 0; i != 7; ++i) - { + } else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/ { + for(i = 0; i != 7; ++i) { unsigned x, y, b; unsigned ilinebits = bpp * passw[i]; unsigned olinebits = bpp * w; size_t obp, ibp; /*bit pointers (for out and in buffer)*/ for(y = 0; y < passh[i]; ++y) - for(x = 0; x < passw[i]; ++x) - { + for(x = 0; x < passw[i]; ++x) { ibp = (8 * passstart[i]) + (y * ilinebits + x * bpp); obp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp; - for(b = 0; b < bpp; ++b) - { + for(b = 0; b < bpp; ++b) { unsigned char bit = readBitFromReversedStream(&ibp, in); /*note that this function assumes the out buffer is completely 0, use setBitOfReversedStream otherwise*/ setBitOfReversedStream0(&obp, out, bit); @@ -4381,8 +3827,7 @@ static void Adam7_deinterlace(unsigned char* out, const unsigned char* in, unsig } static void removePaddingBits(unsigned char* out, const unsigned char* in, - size_t olinebits, size_t ilinebits, unsigned h) -{ + size_t olinebits, size_t ilinebits, unsigned h) { /* After filtering there are still padding bits if scanlines have non multiple of 8 bit amounts. They need to be removed (except at last scanline of (Adam7-reduced) image) before working with pure image buffers @@ -4395,11 +3840,9 @@ static void removePaddingBits(unsigned char* out, const unsigned char* in, unsigned y; size_t diff = ilinebits - olinebits; size_t ibp = 0, obp = 0; /*input and output bit pointers*/ - for(y = 0; y < h; ++y) - { + for(y = 0; y < h; ++y) { size_t x; - for(x = 0; x < olinebits; ++x) - { + for(x = 0; x < olinebits; ++x) { unsigned char bit = readBitFromReversedStream(&ibp, in); setBitOfReversedStream(&obp, out, bit); } @@ -4411,8 +3854,7 @@ static void removePaddingBits(unsigned char* out, const unsigned char* in, the IDAT chunks (with filter index bytes and possible padding bits) return value is error*/ static unsigned postProcessScanlines(unsigned char* out, unsigned char* in, - unsigned w, unsigned h, const LodePNGInfo* info_png) -{ + unsigned w, unsigned h, const LodePNGInfo* info_png) { /* This function converts the filtered-padded-interlaced data into pure 2D image buffer with the PNG's colortype. Steps: @@ -4423,30 +3865,24 @@ static unsigned postProcessScanlines(unsigned char* out, unsigned char* in, unsigned bpp = lodepng_get_bpp(&info_png->color); if(bpp == 0) return 31; /*error: invalid colortype*/ - if(info_png->interlace_method == 0) - { - if(bpp < 8 && w * bpp != ((w * bpp + 7) / 8) * 8) - { + if(info_png->interlace_method == 0) { + if(bpp < 8 && w * bpp != ((w * bpp + 7) / 8) * 8) { CERROR_TRY_RETURN(unfilter(in, in, w, h, bpp)); removePaddingBits(out, in, w * bpp, ((w * bpp + 7) / 8) * 8, h); } /*we can immediately filter into the out buffer, no other steps needed*/ else CERROR_TRY_RETURN(unfilter(out, in, w, h, bpp)); - } - else /*interlace_method is 1 (Adam7)*/ - { + } else /*interlace_method is 1 (Adam7)*/ { unsigned passw[7], passh[7]; size_t filter_passstart[8], padded_passstart[8], passstart[8]; unsigned i; Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); - for(i = 0; i != 7; ++i) - { + for(i = 0; i != 7; ++i) { CERROR_TRY_RETURN(unfilter(&in[padded_passstart[i]], &in[filter_passstart[i]], passw[i], passh[i], bpp)); /*TODO: possible efficiency improvement: if in this reduced image the bits fit nicely in 1 scanline, move bytes instead of bits or move not at all*/ - if(bpp < 8) - { + if(bpp < 8) { /*remove padding bits in scanlines; after this there still may be padding bits between the different reduced images: each reduced image still starts nicely at a byte*/ removePaddingBits(&in[passstart[i]], &in[padded_passstart[i]], passw[i] * bpp, @@ -4460,21 +3896,18 @@ static unsigned postProcessScanlines(unsigned char* out, unsigned char* in, return 0; } -static unsigned readChunk_PLTE(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength) -{ +static unsigned readChunk_PLTE(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength) { unsigned pos = 0, i; if(color->palette) lodepng_free(color->palette); color->palettesize = chunkLength / 3; color->palette = (unsigned char*)lodepng_malloc(4 * color->palettesize); - if(!color->palette && color->palettesize) - { + if(!color->palette && color->palettesize) { color->palettesize = 0; return 83; /*alloc fail*/ } if(color->palettesize > 256) return 38; /*error: palette too big*/ - for(i = 0; i != color->palettesize; ++i) - { + for(i = 0; i != color->palettesize; ++i) { color->palette[4 * i + 0] = data[pos++]; /*R*/ color->palette[4 * i + 1] = data[pos++]; /*G*/ color->palette[4 * i + 2] = data[pos++]; /*B*/ @@ -4484,26 +3917,20 @@ static unsigned readChunk_PLTE(LodePNGColorMode* color, const unsigned char* dat return 0; /* OK */ } -static unsigned readChunk_tRNS(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength) -{ +static unsigned readChunk_tRNS(LodePNGColorMode* color, const unsigned char* data, size_t chunkLength) { unsigned i; - if(color->colortype == LCT_PALETTE) - { + if(color->colortype == LCT_PALETTE) { /*error: more alpha values given than there are palette entries*/ if(chunkLength > color->palettesize) return 39; for(i = 0; i != chunkLength; ++i) color->palette[4 * i + 3] = data[i]; - } - else if(color->colortype == LCT_GREY) - { + } else if(color->colortype == LCT_GREY) { /*error: this chunk must be 2 bytes for greyscale image*/ if(chunkLength != 2) return 30; color->key_defined = 1; color->key_r = color->key_g = color->key_b = 256u * data[0] + data[1]; - } - else if(color->colortype == LCT_RGB) - { + } else if(color->colortype == LCT_RGB) { /*error: this chunk must be 6 bytes for RGB image*/ if(chunkLength != 6) return 41; @@ -4520,10 +3947,8 @@ static unsigned readChunk_tRNS(LodePNGColorMode* color, const unsigned char* dat #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /*background color chunk (bKGD)*/ -static unsigned readChunk_bKGD(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) -{ - if(info->color.colortype == LCT_PALETTE) - { +static unsigned readChunk_bKGD(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { + if(info->color.colortype == LCT_PALETTE) { /*error: this chunk must be 1 byte for indexed color image*/ if(chunkLength != 1) return 43; @@ -4532,18 +3957,14 @@ static unsigned readChunk_bKGD(LodePNGInfo* info, const unsigned char* data, siz info->background_defined = 1; info->background_r = info->background_g = info->background_b = data[0]; - } - else if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) - { + } else if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) { /*error: this chunk must be 2 bytes for greyscale image*/ if(chunkLength != 2) return 44; /*the values are truncated to bitdepth in the PNG file*/ info->background_defined = 1; info->background_r = info->background_g = info->background_b = 256u * data[0] + data[1]; - } - else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) - { + } else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) { /*error: this chunk must be 6 bytes for greyscale image*/ if(chunkLength != 6) return 45; @@ -4558,14 +3979,12 @@ static unsigned readChunk_bKGD(LodePNGInfo* info, const unsigned char* data, siz } /*text chunk (tEXt)*/ -static unsigned readChunk_tEXt(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) -{ +static unsigned readChunk_tEXt(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { unsigned error = 0; char *key = 0, *str = 0; unsigned i; - while(!error) /*not really a while loop, only used to break on error*/ - { + while(!error) /*not really a while loop, only used to break on error*/ { unsigned length, string2_begin; length = 0; @@ -4602,8 +4021,7 @@ static unsigned readChunk_tEXt(LodePNGInfo* info, const unsigned char* data, siz /*compressed text chunk (zTXt)*/ static unsigned readChunk_zTXt(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings, - const unsigned char* data, size_t chunkLength) -{ + const unsigned char* data, size_t chunkLength) { unsigned error = 0; unsigned i; @@ -4613,8 +4031,7 @@ static unsigned readChunk_zTXt(LodePNGInfo* info, const LodePNGDecompressSetting ucvector_init(&decoded); - while(!error) /*not really a while loop, only used to break on error*/ - { + while(!error) /*not really a while loop, only used to break on error*/ { for(length = 0; length < chunkLength && data[length] != 0; ++length) ; if(length + 2 >= chunkLength) CERROR_BREAK(error, 75); /*no null termination, corrupt?*/ if(length < 1 || length > 79) CERROR_BREAK(error, 89); /*keyword too short or long*/ @@ -4651,8 +4068,7 @@ static unsigned readChunk_zTXt(LodePNGInfo* info, const LodePNGDecompressSetting /*international text chunk (iTXt)*/ static unsigned readChunk_iTXt(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings, - const unsigned char* data, size_t chunkLength) -{ + const unsigned char* data, size_t chunkLength) { unsigned error = 0; unsigned i; @@ -4661,8 +4077,7 @@ static unsigned readChunk_iTXt(LodePNGInfo* info, const LodePNGDecompressSetting ucvector decoded; ucvector_init(&decoded); /* TODO: only use in case of compressed text */ - while(!error) /*not really a while loop, only used to break on error*/ - { + while(!error) /*not really a while loop, only used to break on error*/ { /*Quick check if the chunk length isn't too small. Even without check it'd still fail with other error checks below if it's too short. This just gives a different error code.*/ if(chunkLength < 5) CERROR_BREAK(error, 30); /*iTXt chunk too short*/ @@ -4712,8 +4127,7 @@ static unsigned readChunk_iTXt(LodePNGInfo* info, const LodePNGDecompressSetting length = (unsigned)chunkLength < begin ? 0 : (unsigned)chunkLength - begin; - if(compressed) - { + if(compressed) { /*will fail if zlib error, e.g. if length is too small*/ error = zlib_decompress(&decoded.data, &decoded.size, (unsigned char*)(&data[begin]), @@ -4721,9 +4135,7 @@ static unsigned readChunk_iTXt(LodePNGInfo* info, const LodePNGDecompressSetting if(error) break; if(decoded.allocsize < decoded.size) decoded.allocsize = decoded.size; ucvector_push_back(&decoded, 0); - } - else - { + } else { if(!ucvector_resize(&decoded, length + 1)) CERROR_BREAK(error, 83 /*alloc fail*/); decoded.data[length] = 0; @@ -4743,8 +4155,7 @@ static unsigned readChunk_iTXt(LodePNGInfo* info, const LodePNGDecompressSetting return error; } -static unsigned readChunk_tIME(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) -{ +static unsigned readChunk_tIME(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { if(chunkLength != 7) return 73; /*invalid tIME chunk size*/ info->time_defined = 1; @@ -4758,8 +4169,7 @@ static unsigned readChunk_tIME(LodePNGInfo* info, const unsigned char* data, siz return 0; /* OK */ } -static unsigned readChunk_pHYs(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) -{ +static unsigned readChunk_pHYs(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { if(chunkLength != 9) return 74; /*invalid pHYs chunk size*/ info->phys_defined = 1; @@ -4770,8 +4180,7 @@ static unsigned readChunk_pHYs(LodePNGInfo* info, const unsigned char* data, siz return 0; /* OK */ } -static unsigned readChunk_gAMA(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) -{ +static unsigned readChunk_gAMA(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { if(chunkLength != 4) return 96; /*invalid gAMA chunk size*/ info->gama_defined = 1; @@ -4780,8 +4189,7 @@ static unsigned readChunk_gAMA(LodePNGInfo* info, const unsigned char* data, siz return 0; /* OK */ } -static unsigned readChunk_cHRM(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) -{ +static unsigned readChunk_cHRM(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { if(chunkLength != 32) return 97; /*invalid cHRM chunk size*/ info->chrm_defined = 1; @@ -4797,8 +4205,7 @@ static unsigned readChunk_cHRM(LodePNGInfo* info, const unsigned char* data, siz return 0; /* OK */ } -static unsigned readChunk_sRGB(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) -{ +static unsigned readChunk_sRGB(LodePNGInfo* info, const unsigned char* data, size_t chunkLength) { if(chunkLength != 1) return 98; /*invalid sRGB chunk size (this one is never ignored)*/ info->srgb_defined = 1; @@ -4808,8 +4215,7 @@ static unsigned readChunk_sRGB(LodePNGInfo* info, const unsigned char* data, siz } static unsigned readChunk_iCCP(LodePNGInfo* info, const LodePNGDecompressSettings* zlibsettings, - const unsigned char* data, size_t chunkLength) -{ + const unsigned char* data, size_t chunkLength) { unsigned error = 0; unsigned i; @@ -4854,8 +4260,7 @@ static unsigned readChunk_iCCP(LodePNGInfo* info, const LodePNGDecompressSetting #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ unsigned lodepng_inspect_chunk(LodePNGState* state, size_t pos, - const unsigned char* in, size_t insize) -{ + const unsigned char* in, size_t insize) { const unsigned char* chunk = in + pos; unsigned chunkLength; const unsigned char* data; @@ -4868,64 +4273,38 @@ unsigned lodepng_inspect_chunk(LodePNGState* state, size_t pos, data = lodepng_chunk_data_const(chunk); if(data + chunkLength + 4 > in + insize) return 30; - if(lodepng_chunk_type_equals(chunk, "PLTE")) - { + if(lodepng_chunk_type_equals(chunk, "PLTE")) { error = readChunk_PLTE(&state->info_png.color, data, chunkLength); - } - else if(lodepng_chunk_type_equals(chunk, "tRNS")) - { + } else if(lodepng_chunk_type_equals(chunk, "tRNS")) { error = readChunk_tRNS(&state->info_png.color, data, chunkLength); - } #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - else if(lodepng_chunk_type_equals(chunk, "bKGD")) - { + } else if(lodepng_chunk_type_equals(chunk, "bKGD")) { error = readChunk_bKGD(&state->info_png, data, chunkLength); - } - else if(lodepng_chunk_type_equals(chunk, "tEXt")) - { + } else if(lodepng_chunk_type_equals(chunk, "tEXt")) { error = readChunk_tEXt(&state->info_png, data, chunkLength); - } - else if(lodepng_chunk_type_equals(chunk, "zTXt")) - { + } else if(lodepng_chunk_type_equals(chunk, "zTXt")) { error = readChunk_zTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength); - } - else if(lodepng_chunk_type_equals(chunk, "iTXt")) - { + } else if(lodepng_chunk_type_equals(chunk, "iTXt")) { error = readChunk_iTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength); - } - else if(lodepng_chunk_type_equals(chunk, "tIME")) - { + } else if(lodepng_chunk_type_equals(chunk, "tIME")) { error = readChunk_tIME(&state->info_png, data, chunkLength); - } - else if(lodepng_chunk_type_equals(chunk, "pHYs")) - { + } else if(lodepng_chunk_type_equals(chunk, "pHYs")) { error = readChunk_pHYs(&state->info_png, data, chunkLength); - } - else if(lodepng_chunk_type_equals(chunk, "gAMA")) - { + } else if(lodepng_chunk_type_equals(chunk, "gAMA")) { error = readChunk_gAMA(&state->info_png, data, chunkLength); - } - else if(lodepng_chunk_type_equals(chunk, "cHRM")) - { + } else if(lodepng_chunk_type_equals(chunk, "cHRM")) { error = readChunk_cHRM(&state->info_png, data, chunkLength); - } - else if(lodepng_chunk_type_equals(chunk, "sRGB")) - { + } else if(lodepng_chunk_type_equals(chunk, "sRGB")) { error = readChunk_sRGB(&state->info_png, data, chunkLength); - } - else if(lodepng_chunk_type_equals(chunk, "iCCP")) - { + } else if(lodepng_chunk_type_equals(chunk, "iCCP")) { error = readChunk_iCCP(&state->info_png, &state->decoder.zlibsettings, data, chunkLength); - } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ - else - { + } else { /* unhandled chunk is ok (is not an error) */ unhandled = 1; } - if(!error && !unhandled && !state->decoder.ignore_crc) - { + if(!error && !unhandled && !state->decoder.ignore_crc) { if(lodepng_chunk_check_crc(chunk)) return 57; /*invalid CRC*/ } @@ -4935,8 +4314,7 @@ unsigned lodepng_inspect_chunk(LodePNGState* state, size_t pos, /*read a PNG, the result will be in the same color type as the PNG (hence "generic")*/ static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h, LodePNGState* state, - const unsigned char* in, size_t insize) -{ + const unsigned char* in, size_t insize) { unsigned char IEND = 0; const unsigned char* chunk; size_t i; @@ -4957,8 +4335,7 @@ static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h, state->error = lodepng_inspect(w, h, state, in, insize); /*reads header and resets other parameters in state->info_png*/ if(state->error) return; - if(lodepng_pixel_overflow(*w, *h, &state->info_png.color, &state->info_raw)) - { + if(lodepng_pixel_overflow(*w, *h, &state->info_png.color, &state->info_raw)) { CERROR_RETURN(state->error, 92); /*overflow possible due to amount of pixels*/ } @@ -4967,14 +4344,12 @@ static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h, /*loop through the chunks, ignoring unknown chunks and stopping at IEND chunk. IDAT data is put at the start of the in buffer*/ - while(!IEND && !state->error) - { + while(!IEND && !state->error) { unsigned chunkLength; const unsigned char* data; /*the data in the chunk*/ /*error: size of the in buffer too small to contain next chunk*/ - if((size_t)((chunk - in) + 12) > insize || chunk < in) - { + if((size_t)((chunk - in) + 12) > insize || chunk < in) { if(state->decoder.ignore_end) break; /*other errors may still happen though*/ CERROR_BREAK(state->error, 30); } @@ -4982,14 +4357,12 @@ static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h, /*length of the data of the chunk, excluding the length bytes, chunk type and CRC bytes*/ chunkLength = lodepng_chunk_length(chunk); /*error: chunk length larger than the max PNG chunk size*/ - if(chunkLength > 2147483647) - { + if(chunkLength > 2147483647) { if(state->decoder.ignore_end) break; /*other errors may still happen though*/ CERROR_BREAK(state->error, 63); } - if((size_t)((chunk - in) + chunkLength + 12) > insize || (chunk + chunkLength + 12) < in) - { + if((size_t)((chunk - in) + chunkLength + 12) > insize || (chunk + chunkLength + 12) < in) { CERROR_BREAK(state->error, 64); /*error: size of the in buffer too small to contain next chunk*/ } @@ -4998,8 +4371,7 @@ static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h, unknown = 0; /*IDAT chunk, containing compressed image data*/ - if(lodepng_chunk_type_equals(chunk, "IDAT")) - { + if(lodepng_chunk_type_equals(chunk, "IDAT")) { size_t oldsize = idat.size; size_t newsize; if(lodepng_addofl(oldsize, chunkLength, &newsize)) CERROR_BREAK(state->error, 95); @@ -5008,106 +4380,73 @@ static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h, #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS critical_pos = 3; #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ - } - /*IEND chunk*/ - else if(lodepng_chunk_type_equals(chunk, "IEND")) - { + } else if(lodepng_chunk_type_equals(chunk, "IEND")) { + /*IEND chunk*/ IEND = 1; - } - /*palette chunk (PLTE)*/ - else if(lodepng_chunk_type_equals(chunk, "PLTE")) - { + } else if(lodepng_chunk_type_equals(chunk, "PLTE")) { + /*palette chunk (PLTE)*/ state->error = readChunk_PLTE(&state->info_png.color, data, chunkLength); if(state->error) break; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS critical_pos = 2; #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ - } - /*palette transparency chunk (tRNS). Even though this one is an ancillary chunk , it is still compiled - in without 'LODEPNG_COMPILE_ANCILLARY_CHUNKS' because it contains essential color information that - affects the alpha channel of pixels. */ - else if(lodepng_chunk_type_equals(chunk, "tRNS")) - { + } else if(lodepng_chunk_type_equals(chunk, "tRNS")) { + /*palette transparency chunk (tRNS). Even though this one is an ancillary chunk , it is still compiled + in without 'LODEPNG_COMPILE_ANCILLARY_CHUNKS' because it contains essential color information that + affects the alpha channel of pixels. */ state->error = readChunk_tRNS(&state->info_png.color, data, chunkLength); if(state->error) break; - } #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - /*background color chunk (bKGD)*/ - else if(lodepng_chunk_type_equals(chunk, "bKGD")) - { + /*background color chunk (bKGD)*/ + } else if(lodepng_chunk_type_equals(chunk, "bKGD")) { state->error = readChunk_bKGD(&state->info_png, data, chunkLength); if(state->error) break; - } - /*text chunk (tEXt)*/ - else if(lodepng_chunk_type_equals(chunk, "tEXt")) - { - if(state->decoder.read_text_chunks) - { + } else if(lodepng_chunk_type_equals(chunk, "tEXt")) { + /*text chunk (tEXt)*/ + if(state->decoder.read_text_chunks) { state->error = readChunk_tEXt(&state->info_png, data, chunkLength); if(state->error) break; } - } - /*compressed text chunk (zTXt)*/ - else if(lodepng_chunk_type_equals(chunk, "zTXt")) - { - if(state->decoder.read_text_chunks) - { + } else if(lodepng_chunk_type_equals(chunk, "zTXt")) { + /*compressed text chunk (zTXt)*/ + if(state->decoder.read_text_chunks) { state->error = readChunk_zTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength); if(state->error) break; } - } - /*international text chunk (iTXt)*/ - else if(lodepng_chunk_type_equals(chunk, "iTXt")) - { - if(state->decoder.read_text_chunks) - { + } else if(lodepng_chunk_type_equals(chunk, "iTXt")) { + /*international text chunk (iTXt)*/ + if(state->decoder.read_text_chunks) { state->error = readChunk_iTXt(&state->info_png, &state->decoder.zlibsettings, data, chunkLength); if(state->error) break; } - } - else if(lodepng_chunk_type_equals(chunk, "tIME")) - { + } else if(lodepng_chunk_type_equals(chunk, "tIME")) { state->error = readChunk_tIME(&state->info_png, data, chunkLength); if(state->error) break; - } - else if(lodepng_chunk_type_equals(chunk, "pHYs")) - { + } else if(lodepng_chunk_type_equals(chunk, "pHYs")) { state->error = readChunk_pHYs(&state->info_png, data, chunkLength); if(state->error) break; - } - else if(lodepng_chunk_type_equals(chunk, "gAMA")) - { + } else if(lodepng_chunk_type_equals(chunk, "gAMA")) { state->error = readChunk_gAMA(&state->info_png, data, chunkLength); if(state->error) break; - } - else if(lodepng_chunk_type_equals(chunk, "cHRM")) - { + } else if(lodepng_chunk_type_equals(chunk, "cHRM")) { state->error = readChunk_cHRM(&state->info_png, data, chunkLength); if(state->error) break; - } - else if(lodepng_chunk_type_equals(chunk, "sRGB")) - { + } else if(lodepng_chunk_type_equals(chunk, "sRGB")) { state->error = readChunk_sRGB(&state->info_png, data, chunkLength); if(state->error) break; - } - else if(lodepng_chunk_type_equals(chunk, "iCCP")) - { + } else if(lodepng_chunk_type_equals(chunk, "iCCP")) { state->error = readChunk_iCCP(&state->info_png, &state->decoder.zlibsettings, data, chunkLength); if(state->error) break; - } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ - else /*it's not an implemented chunk type, so ignore it: skip over the data*/ - { + } else /*it's not an implemented chunk type, so ignore it: skip over the data*/ { /*error: unknown critical chunk (5th bit of first byte of chunk type is 0)*/ - if(!state->decoder.ignore_critical && !lodepng_chunk_ancillary(chunk)) - { + if(!state->decoder.ignore_critical && !lodepng_chunk_ancillary(chunk)) { CERROR_BREAK(state->error, 69); } unknown = 1; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - if(state->decoder.remember_unknown_chunks) - { + if(state->decoder.remember_unknown_chunks) { state->error = lodepng_chunk_append(&state->info_png.unknown_chunks_data[critical_pos - 1], &state->info_png.unknown_chunks_size[critical_pos - 1], chunk); if(state->error) break; @@ -5115,8 +4454,7 @@ static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h, #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ } - if(!state->decoder.ignore_crc && !unknown) /*check CRC if wanted, only on known chunk types*/ - { + if(!state->decoder.ignore_crc && !unknown) /*check CRC if wanted, only on known chunk types*/ { if(lodepng_chunk_check_crc(chunk)) CERROR_BREAK(state->error, 57); /*invalid CRC*/ } @@ -5126,12 +4464,9 @@ static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h, ucvector_init(&scanlines); /*predict output size, to allocate exact size for output buffer to avoid more dynamic allocation. If the decompressed size does not match the prediction, the image must be corrupt.*/ - if(state->info_png.interlace_method == 0) - { + if(state->info_png.interlace_method == 0) { predict = lodepng_get_raw_size_idat(*w, *h, &state->info_png.color); - } - else - { + } else { /*Adam-7 interlaced: predicted size is the sum of the 7 sub-images sizes*/ const LodePNGColorMode* color = &state->info_png.color; predict = 0; @@ -5144,22 +4479,19 @@ static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h, predict += lodepng_get_raw_size_idat((*w + 0), (*h + 0) >> 1, color); } if(!state->error && !ucvector_reserve(&scanlines, predict)) state->error = 83; /*alloc fail*/ - if(!state->error) - { + if(!state->error) { state->error = zlib_decompress(&scanlines.data, &scanlines.size, idat.data, idat.size, &state->decoder.zlibsettings); if(!state->error && scanlines.size != predict) state->error = 91; /*decompressed size doesn't match prediction*/ } ucvector_cleanup(&idat); - if(!state->error) - { + if(!state->error) { outsize = lodepng_get_raw_size(*w, *h, &state->info_png.color); *out = (unsigned char*)lodepng_malloc(outsize); if(!*out) state->error = 83; /*alloc fail*/ } - if(!state->error) - { + if(!state->error) { for(i = 0; i < outsize; i++) (*out)[i] = 0; state->error = postProcessScanlines(*out, scanlines.data, *w, *h, &state->info_png); } @@ -5168,24 +4500,19 @@ static void decodeGeneric(unsigned char** out, unsigned* w, unsigned* h, unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h, LodePNGState* state, - const unsigned char* in, size_t insize) -{ + const unsigned char* in, size_t insize) { *out = 0; decodeGeneric(out, w, h, state, in, insize); if(state->error) return state->error; - if(!state->decoder.color_convert || lodepng_color_mode_equal(&state->info_raw, &state->info_png.color)) - { + if(!state->decoder.color_convert || lodepng_color_mode_equal(&state->info_raw, &state->info_png.color)) { /*same color type, no copying or converting of data needed*/ /*store the info_png color settings on the info_raw so that the info_raw still reflects what colortype the raw image has to the end user*/ - if(!state->decoder.color_convert) - { + if(!state->decoder.color_convert) { state->error = lodepng_color_mode_copy(&state->info_raw, &state->info_png.color); if(state->error) return state->error; } - } - else - { + } else { /*color conversion needed; sort of copy of the data*/ unsigned char* data = *out; size_t outsize; @@ -5193,15 +4520,13 @@ unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h, /*TODO: check if this works according to the statement in the documentation: "The converter can convert from greyscale input color type, to 8-bit greyscale or greyscale with alpha"*/ if(!(state->info_raw.colortype == LCT_RGB || state->info_raw.colortype == LCT_RGBA) - && !(state->info_raw.bitdepth == 8)) - { + && !(state->info_raw.bitdepth == 8)) { return 56; /*unsupported color mode conversion*/ } outsize = lodepng_get_raw_size(*w, *h, &state->info_raw); *out = (unsigned char*)lodepng_malloc(outsize); - if(!(*out)) - { + if(!(*out)) { state->error = 83; /*alloc fail*/ } else state->error = lodepng_convert(*out, data, &state->info_raw, @@ -5212,8 +4537,7 @@ unsigned lodepng_decode(unsigned char** out, unsigned* w, unsigned* h, } unsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, - size_t insize, LodePNGColorType colortype, unsigned bitdepth) -{ + size_t insize, LodePNGColorType colortype, unsigned bitdepth) { unsigned error; LodePNGState state; lodepng_state_init(&state); @@ -5224,20 +4548,17 @@ unsigned lodepng_decode_memory(unsigned char** out, unsigned* w, unsigned* h, co return error; } -unsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize) -{ +unsigned lodepng_decode32(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize) { return lodepng_decode_memory(out, w, h, in, insize, LCT_RGBA, 8); } -unsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize) -{ +unsigned lodepng_decode24(unsigned char** out, unsigned* w, unsigned* h, const unsigned char* in, size_t insize) { return lodepng_decode_memory(out, w, h, in, insize, LCT_RGB, 8); } #ifdef LODEPNG_COMPILE_DISK unsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename, - LodePNGColorType colortype, unsigned bitdepth) -{ + LodePNGColorType colortype, unsigned bitdepth) { unsigned char* buffer = 0; size_t buffersize; unsigned error; @@ -5247,19 +4568,16 @@ unsigned lodepng_decode_file(unsigned char** out, unsigned* w, unsigned* h, cons return error; } -unsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename) -{ +unsigned lodepng_decode32_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename) { return lodepng_decode_file(out, w, h, filename, LCT_RGBA, 8); } -unsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename) -{ +unsigned lodepng_decode24_file(unsigned char** out, unsigned* w, unsigned* h, const char* filename) { return lodepng_decode_file(out, w, h, filename, LCT_RGB, 8); } #endif /*LODEPNG_COMPILE_DISK*/ -void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings) -{ +void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings) { settings->color_convert = 1; #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS settings->read_text_chunks = 1; @@ -5275,8 +4593,7 @@ void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings) #if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) -void lodepng_state_init(LodePNGState* state) -{ +void lodepng_state_init(LodePNGState* state) { #ifdef LODEPNG_COMPILE_DECODER lodepng_decoder_settings_init(&state->decoder); #endif /*LODEPNG_COMPILE_DECODER*/ @@ -5288,14 +4605,12 @@ void lodepng_state_init(LodePNGState* state) state->error = 1; } -void lodepng_state_cleanup(LodePNGState* state) -{ +void lodepng_state_cleanup(LodePNGState* state) { lodepng_color_mode_cleanup(&state->info_raw); lodepng_info_cleanup(&state->info_png); } -void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source) -{ +void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source) { lodepng_state_cleanup(dest); *dest = *source; lodepng_color_mode_init(&dest->info_raw); @@ -5313,15 +4628,13 @@ void lodepng_state_copy(LodePNGState* dest, const LodePNGState* source) /* ////////////////////////////////////////////////////////////////////////// */ /*chunkName must be string of 4 characters*/ -static unsigned addChunk(ucvector* out, const char* chunkName, const unsigned char* data, size_t length) -{ +static unsigned addChunk(ucvector* out, const char* chunkName, const unsigned char* data, size_t length) { CERROR_TRY_RETURN(lodepng_chunk_create(&out->data, &out->size, (unsigned)length, chunkName, data)); out->allocsize = out->size; /*fix the allocsize again*/ return 0; } -static void writeSignature(ucvector* out) -{ +static void writeSignature(ucvector* out) { /*8 bytes PNG signature, aka the magic bytes*/ ucvector_push_back(out, 137); ucvector_push_back(out, 80); @@ -5334,8 +4647,7 @@ static void writeSignature(ucvector* out) } static unsigned addChunk_IHDR(ucvector* out, unsigned w, unsigned h, - LodePNGColorType colortype, unsigned bitdepth, unsigned interlace_method) -{ + LodePNGColorType colortype, unsigned bitdepth, unsigned interlace_method) { unsigned error = 0; ucvector header; ucvector_init(&header); @@ -5354,14 +4666,12 @@ static unsigned addChunk_IHDR(ucvector* out, unsigned w, unsigned h, return error; } -static unsigned addChunk_PLTE(ucvector* out, const LodePNGColorMode* info) -{ +static unsigned addChunk_PLTE(ucvector* out, const LodePNGColorMode* info) { unsigned error = 0; size_t i; ucvector PLTE; ucvector_init(&PLTE); - for(i = 0; i != info->palettesize * 4; ++i) - { + for(i = 0; i != info->palettesize * 4; ++i) { /*add all channels except alpha channel*/ if(i % 4 != 3) ucvector_push_back(&PLTE, info->palette[i]); } @@ -5371,36 +4681,27 @@ static unsigned addChunk_PLTE(ucvector* out, const LodePNGColorMode* info) return error; } -static unsigned addChunk_tRNS(ucvector* out, const LodePNGColorMode* info) -{ +static unsigned addChunk_tRNS(ucvector* out, const LodePNGColorMode* info) { unsigned error = 0; size_t i; ucvector tRNS; ucvector_init(&tRNS); - if(info->colortype == LCT_PALETTE) - { + if(info->colortype == LCT_PALETTE) { size_t amount = info->palettesize; /*the tail of palette values that all have 255 as alpha, does not have to be encoded*/ - for(i = info->palettesize; i != 0; --i) - { + for(i = info->palettesize; i != 0; --i) { if(info->palette[4 * (i - 1) + 3] == 255) --amount; else break; } /*add only alpha channel*/ for(i = 0; i != amount; ++i) ucvector_push_back(&tRNS, info->palette[4 * i + 3]); - } - else if(info->colortype == LCT_GREY) - { - if(info->key_defined) - { + } else if(info->colortype == LCT_GREY) { + if(info->key_defined) { ucvector_push_back(&tRNS, (unsigned char)(info->key_r >> 8)); ucvector_push_back(&tRNS, (unsigned char)(info->key_r & 255)); } - } - else if(info->colortype == LCT_RGB) - { - if(info->key_defined) - { + } else if(info->colortype == LCT_RGB) { + if(info->key_defined) { ucvector_push_back(&tRNS, (unsigned char)(info->key_r >> 8)); ucvector_push_back(&tRNS, (unsigned char)(info->key_r & 255)); ucvector_push_back(&tRNS, (unsigned char)(info->key_g >> 8)); @@ -5417,8 +4718,7 @@ static unsigned addChunk_tRNS(ucvector* out, const LodePNGColorMode* info) } static unsigned addChunk_IDAT(ucvector* out, const unsigned char* data, size_t datasize, - LodePNGCompressSettings* zlibsettings) -{ + LodePNGCompressSettings* zlibsettings) { ucvector zlibdata; unsigned error = 0; @@ -5431,8 +4731,7 @@ static unsigned addChunk_IDAT(ucvector* out, const unsigned char* data, size_t d return error; } -static unsigned addChunk_IEND(ucvector* out) -{ +static unsigned addChunk_IEND(ucvector* out) { unsigned error = 0; error = addChunk(out, "IEND", 0, 0); return error; @@ -5440,8 +4739,7 @@ static unsigned addChunk_IEND(ucvector* out) #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS -static unsigned addChunk_tEXt(ucvector* out, const char* keyword, const char* textstring) -{ +static unsigned addChunk_tEXt(ucvector* out, const char* keyword, const char* textstring) { unsigned error = 0; size_t i; ucvector text; @@ -5457,8 +4755,7 @@ static unsigned addChunk_tEXt(ucvector* out, const char* keyword, const char* te } static unsigned addChunk_zTXt(ucvector* out, const char* keyword, const char* textstring, - LodePNGCompressSettings* zlibsettings) -{ + LodePNGCompressSettings* zlibsettings) { unsigned error = 0; ucvector data, compressed; size_t i, textsize = strlen(textstring); @@ -5472,8 +4769,7 @@ static unsigned addChunk_zTXt(ucvector* out, const char* keyword, const char* te error = zlib_compress(&compressed.data, &compressed.size, (unsigned char*)textstring, textsize, zlibsettings); - if(!error) - { + if(!error) { for(i = 0; i != compressed.size; ++i) ucvector_push_back(&data, compressed.data[i]); error = addChunk(out, "zTXt", data.data, data.size); } @@ -5484,8 +4780,7 @@ static unsigned addChunk_zTXt(ucvector* out, const char* keyword, const char* te } static unsigned addChunk_iTXt(ucvector* out, unsigned compressed, const char* keyword, const char* langtag, - const char* transkey, const char* textstring, LodePNGCompressSettings* zlibsettings) -{ + const char* transkey, const char* textstring, LodePNGCompressSettings* zlibsettings) { unsigned error = 0; ucvector data; size_t i, textsize = strlen(textstring); @@ -5502,20 +4797,16 @@ static unsigned addChunk_iTXt(ucvector* out, unsigned compressed, const char* ke for(i = 0; transkey[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)transkey[i]); ucvector_push_back(&data, 0); /*null termination char*/ - if(compressed) - { + if(compressed) { ucvector compressed_data; ucvector_init(&compressed_data); error = zlib_compress(&compressed_data.data, &compressed_data.size, (unsigned char*)textstring, textsize, zlibsettings); - if(!error) - { + if(!error) { for(i = 0; i != compressed_data.size; ++i) ucvector_push_back(&data, compressed_data.data[i]); } ucvector_cleanup(&compressed_data); - } - else /*not compressed*/ - { + } else /*not compressed*/ { for(i = 0; textstring[i] != 0; ++i) ucvector_push_back(&data, (unsigned char)textstring[i]); } @@ -5524,27 +4815,21 @@ static unsigned addChunk_iTXt(ucvector* out, unsigned compressed, const char* ke return error; } -static unsigned addChunk_bKGD(ucvector* out, const LodePNGInfo* info) -{ +static unsigned addChunk_bKGD(ucvector* out, const LodePNGInfo* info) { unsigned error = 0; ucvector bKGD; ucvector_init(&bKGD); - if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) - { + if(info->color.colortype == LCT_GREY || info->color.colortype == LCT_GREY_ALPHA) { ucvector_push_back(&bKGD, (unsigned char)(info->background_r >> 8)); ucvector_push_back(&bKGD, (unsigned char)(info->background_r & 255)); - } - else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) - { + } else if(info->color.colortype == LCT_RGB || info->color.colortype == LCT_RGBA) { ucvector_push_back(&bKGD, (unsigned char)(info->background_r >> 8)); ucvector_push_back(&bKGD, (unsigned char)(info->background_r & 255)); ucvector_push_back(&bKGD, (unsigned char)(info->background_g >> 8)); ucvector_push_back(&bKGD, (unsigned char)(info->background_g & 255)); ucvector_push_back(&bKGD, (unsigned char)(info->background_b >> 8)); ucvector_push_back(&bKGD, (unsigned char)(info->background_b & 255)); - } - else if(info->color.colortype == LCT_PALETTE) - { + } else if(info->color.colortype == LCT_PALETTE) { ucvector_push_back(&bKGD, (unsigned char)(info->background_r & 255)); /*palette index*/ } @@ -5554,8 +4839,7 @@ static unsigned addChunk_bKGD(ucvector* out, const LodePNGInfo* info) return error; } -static unsigned addChunk_tIME(ucvector* out, const LodePNGTime* time) -{ +static unsigned addChunk_tIME(ucvector* out, const LodePNGTime* time) { unsigned error = 0; unsigned char* data = (unsigned char*)lodepng_malloc(7); if(!data) return 83; /*alloc fail*/ @@ -5571,8 +4855,7 @@ static unsigned addChunk_tIME(ucvector* out, const LodePNGTime* time) return error; } -static unsigned addChunk_pHYs(ucvector* out, const LodePNGInfo* info) -{ +static unsigned addChunk_pHYs(ucvector* out, const LodePNGInfo* info) { unsigned error = 0; ucvector data; ucvector_init(&data); @@ -5587,8 +4870,7 @@ static unsigned addChunk_pHYs(ucvector* out, const LodePNGInfo* info) return error; } -static unsigned addChunk_gAMA(ucvector* out, const LodePNGInfo* info) -{ +static unsigned addChunk_gAMA(ucvector* out, const LodePNGInfo* info) { unsigned error = 0; ucvector data; ucvector_init(&data); @@ -5601,8 +4883,7 @@ static unsigned addChunk_gAMA(ucvector* out, const LodePNGInfo* info) return error; } -static unsigned addChunk_cHRM(ucvector* out, const LodePNGInfo* info) -{ +static unsigned addChunk_cHRM(ucvector* out, const LodePNGInfo* info) { unsigned error = 0; ucvector data; ucvector_init(&data); @@ -5622,14 +4903,12 @@ static unsigned addChunk_cHRM(ucvector* out, const LodePNGInfo* info) return error; } -static unsigned addChunk_sRGB(ucvector* out, const LodePNGInfo* info) -{ +static unsigned addChunk_sRGB(ucvector* out, const LodePNGInfo* info) { unsigned char data = info->srgb_intent; return addChunk(out, "sRGB", &data, 1); } -static unsigned addChunk_iCCP(ucvector* out, const LodePNGInfo* info, LodePNGCompressSettings* zlibsettings) -{ +static unsigned addChunk_iCCP(ucvector* out, const LodePNGInfo* info, LodePNGCompressSettings* zlibsettings) { unsigned error = 0; ucvector data, compressed; size_t i; @@ -5643,8 +4922,7 @@ static unsigned addChunk_iCCP(ucvector* out, const LodePNGInfo* info, LodePNGCom error = zlib_compress(&compressed.data, &compressed.size, info->iccp_profile, info->iccp_profile_size, zlibsettings); - if(!error) - { + if(!error) { for(i = 0; i != compressed.size; ++i) ucvector_push_back(&data, compressed.data[i]); error = addChunk(out, "iCCP", data.data, data.size); } @@ -5657,11 +4935,9 @@ static unsigned addChunk_iCCP(ucvector* out, const LodePNGInfo* info, LodePNGCom #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ static void filterScanline(unsigned char* out, const unsigned char* scanline, const unsigned char* prevline, - size_t length, size_t bytewidth, unsigned char filterType) -{ + size_t length, size_t bytewidth, unsigned char filterType) { size_t i; - switch(filterType) - { + switch(filterType) { case 0: /*None*/ for(i = 0; i != length; ++i) out[i] = scanline[i]; break; @@ -5670,39 +4946,29 @@ static void filterScanline(unsigned char* out, const unsigned char* scanline, co for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - scanline[i - bytewidth]; break; case 2: /*Up*/ - if(prevline) - { + if(prevline) { for(i = 0; i != length; ++i) out[i] = scanline[i] - prevline[i]; - } - else - { + } else { for(i = 0; i != length; ++i) out[i] = scanline[i]; } break; case 3: /*Average*/ - if(prevline) - { + if(prevline) { for(i = 0; i != bytewidth; ++i) out[i] = scanline[i] - (prevline[i] >> 1); for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - ((scanline[i - bytewidth] + prevline[i]) >> 1); - } - else - { + } else { for(i = 0; i != bytewidth; ++i) out[i] = scanline[i]; for(i = bytewidth; i < length; ++i) out[i] = scanline[i] - (scanline[i - bytewidth] >> 1); } break; case 4: /*Paeth*/ - if(prevline) - { + if(prevline) { /*paethPredictor(0, prevline[i], 0) is always prevline[i]*/ for(i = 0; i != bytewidth; ++i) out[i] = (scanline[i] - prevline[i]); - for(i = bytewidth; i < length; ++i) - { + for(i = bytewidth; i < length; ++i) { out[i] = (scanline[i] - paethPredictor(scanline[i - bytewidth], prevline[i], prevline[i - bytewidth])); } - } - else - { + } else { for(i = 0; i != bytewidth; ++i) out[i] = scanline[i]; /*paethPredictor(scanline[i - bytewidth], 0, 0) is always scanline[i - bytewidth]*/ for(i = bytewidth; i < length; ++i) out[i] = (scanline[i] - scanline[i - bytewidth]); @@ -5713,8 +4979,7 @@ static void filterScanline(unsigned char* out, const unsigned char* scanline, co } /* log2 approximation. A slight bit faster than std::log. */ -static float flog2(float f) -{ +static float flog2(float f) { float result = 0; while(f > 32) { result += 4; f /= 16; } while(f > 2) { ++result; f /= 2; } @@ -5722,8 +4987,7 @@ static float flog2(float f) } static unsigned filter(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, - const LodePNGColorMode* info, const LodePNGEncoderSettings* settings) -{ + const LodePNGColorMode* info, const LodePNGEncoderSettings* settings) { /* For PNG filter method 0 out must be a buffer with as size: h + (w * h * bpp + 7) / 8, because there are @@ -5758,50 +5022,38 @@ static unsigned filter(unsigned char* out, const unsigned char* in, unsigned w, if(bpp == 0) return 31; /*error: invalid color type*/ - if(strategy == LFS_ZERO) - { - for(y = 0; y != h; ++y) - { + if(strategy == LFS_ZERO) { + for(y = 0; y != h; ++y) { size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/ size_t inindex = linebytes * y; out[outindex] = 0; /*filter type byte*/ filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, 0); prevline = &in[inindex]; } - } - else if(strategy == LFS_MINSUM) - { + } else if(strategy == LFS_MINSUM) { /*adaptive filtering*/ size_t sum[5]; unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/ size_t smallest = 0; unsigned char type, bestType = 0; - for(type = 0; type != 5; ++type) - { + for(type = 0; type != 5; ++type) { attempt[type] = (unsigned char*)lodepng_malloc(linebytes); if(!attempt[type]) return 83; /*alloc fail*/ } - if(!error) - { - for(y = 0; y != h; ++y) - { + if(!error) { + for(y = 0; y != h; ++y) { /*try the 5 filter types*/ - for(type = 0; type != 5; ++type) - { + for(type = 0; type != 5; ++type) { filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type); /*calculate the sum of the result*/ sum[type] = 0; - if(type == 0) - { + if(type == 0) { for(x = 0; x != linebytes; ++x) sum[type] += (unsigned char)(attempt[type][x]); - } - else - { - for(x = 0; x != linebytes; ++x) - { + } else { + for(x = 0; x != linebytes; ++x) { /*For differences, each byte should be treated as signed, values above 127 are negative (converted to signed char). Filtertype 0 isn't a difference though, so use unsigned there. This means filtertype 0 is almost never chosen, but that is justified.*/ @@ -5811,8 +5063,7 @@ static unsigned filter(unsigned char* out, const unsigned char* in, unsigned w, } /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/ - if(type == 0 || sum[type] < smallest) - { + if(type == 0 || sum[type] < smallest) { bestType = type; smallest = sum[type]; } @@ -5827,39 +5078,32 @@ static unsigned filter(unsigned char* out, const unsigned char* in, unsigned w, } for(type = 0; type != 5; ++type) lodepng_free(attempt[type]); - } - else if(strategy == LFS_ENTROPY) - { + } else if(strategy == LFS_ENTROPY) { float sum[5]; unsigned char* attempt[5]; /*five filtering attempts, one for each filter type*/ float smallest = 0; unsigned type, bestType = 0; unsigned count[256]; - for(type = 0; type != 5; ++type) - { + for(type = 0; type != 5; ++type) { attempt[type] = (unsigned char*)lodepng_malloc(linebytes); if(!attempt[type]) return 83; /*alloc fail*/ } - for(y = 0; y != h; ++y) - { + for(y = 0; y != h; ++y) { /*try the 5 filter types*/ - for(type = 0; type != 5; ++type) - { + for(type = 0; type != 5; ++type) { filterScanline(attempt[type], &in[y * linebytes], prevline, linebytes, bytewidth, type); for(x = 0; x != 256; ++x) count[x] = 0; for(x = 0; x != linebytes; ++x) ++count[attempt[type][x]]; ++count[type]; /*the filter type itself is part of the scanline*/ sum[type] = 0; - for(x = 0; x != 256; ++x) - { + for(x = 0; x != 256; ++x) { float p = count[x] / (float)(linebytes + 1); sum[type] += count[x] == 0 ? 0 : flog2(1 / p) * p; } /*check if this is smallest sum (or if type == 0 it's the first case so always store the values)*/ - if(type == 0 || sum[type] < smallest) - { + if(type == 0 || sum[type] < smallest) { bestType = type; smallest = sum[type]; } @@ -5873,11 +5117,8 @@ static unsigned filter(unsigned char* out, const unsigned char* in, unsigned w, } for(type = 0; type != 5; ++type) lodepng_free(attempt[type]); - } - else if(strategy == LFS_PREDEFINED) - { - for(y = 0; y != h; ++y) - { + } else if(strategy == LFS_PREDEFINED) { + for(y = 0; y != h; ++y) { size_t outindex = (1 + linebytes) * y; /*the extra filterbyte added to each row*/ size_t inindex = linebytes * y; unsigned char type = settings->predefined_filters[y]; @@ -5885,9 +5126,7 @@ static unsigned filter(unsigned char* out, const unsigned char* in, unsigned w, filterScanline(&out[outindex + 1], &in[inindex], prevline, linebytes, bytewidth, type); prevline = &in[inindex]; } - } - else if(strategy == LFS_BRUTE_FORCE) - { + } else if(strategy == LFS_BRUTE_FORCE) { /*brute force filter chooser. deflate the scanline after every filter attempt to see which one deflates best. This is very slow and gives only slightly smaller, sometimes even larger, result*/ @@ -5906,15 +5145,12 @@ static unsigned filter(unsigned char* out, const unsigned char* in, unsigned w, images only, so disable it*/ zlibsettings.custom_zlib = 0; zlibsettings.custom_deflate = 0; - for(type = 0; type != 5; ++type) - { + for(type = 0; type != 5; ++type) { attempt[type] = (unsigned char*)lodepng_malloc(linebytes); if(!attempt[type]) return 83; /*alloc fail*/ } - for(y = 0; y != h; ++y) /*try the 5 filter types*/ - { - for(type = 0; type != 5; ++type) - { + for(y = 0; y != h; ++y) /*try the 5 filter types*/ { + for(type = 0; type != 5; ++type) { unsigned testsize = (unsigned)linebytes; /*if(testsize > 8) testsize /= 8;*/ /*it already works good enough by testing a part of the row*/ @@ -5924,8 +5160,7 @@ static unsigned filter(unsigned char* out, const unsigned char* in, unsigned w, zlib_compress(&dummy, &size[type], attempt[type], testsize, &zlibsettings); lodepng_free(dummy); /*check if this is smallest size (or if type == 0 it's the first case so always store the values)*/ - if(type == 0 || size[type] < smallest) - { + if(type == 0 || size[type] < smallest) { bestType = type; smallest = size[type]; } @@ -5942,18 +5177,15 @@ static unsigned filter(unsigned char* out, const unsigned char* in, unsigned w, } static void addPaddingBits(unsigned char* out, const unsigned char* in, - size_t olinebits, size_t ilinebits, unsigned h) -{ + size_t olinebits, size_t ilinebits, unsigned h) { /*The opposite of the removePaddingBits function olinebits must be >= ilinebits*/ unsigned y; size_t diff = olinebits - ilinebits; size_t obp = 0, ibp = 0; /*bit pointers*/ - for(y = 0; y != h; ++y) - { + for(y = 0; y != h; ++y) { size_t x; - for(x = 0; x < ilinebits; ++x) - { + for(x = 0; x < ilinebits; ++x) { unsigned char bit = readBitFromReversedStream(&ibp, in); setBitOfReversedStream(&obp, out, bit); } @@ -5974,47 +5206,37 @@ in has the following size in bits: w * h * bpp. out is possibly bigger due to padding bits between reduced images NOTE: comments about padding bits are only relevant if bpp < 8 */ -static void Adam7_interlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) -{ +static void Adam7_interlace(unsigned char* out, const unsigned char* in, unsigned w, unsigned h, unsigned bpp) { unsigned passw[7], passh[7]; size_t filter_passstart[8], padded_passstart[8], passstart[8]; unsigned i; Adam7_getpassvalues(passw, passh, filter_passstart, padded_passstart, passstart, w, h, bpp); - if(bpp >= 8) - { - for(i = 0; i != 7; ++i) - { + if(bpp >= 8) { + for(i = 0; i != 7; ++i) { unsigned x, y, b; size_t bytewidth = bpp / 8; for(y = 0; y < passh[i]; ++y) - for(x = 0; x < passw[i]; ++x) - { + for(x = 0; x < passw[i]; ++x) { size_t pixelinstart = ((ADAM7_IY[i] + y * ADAM7_DY[i]) * w + ADAM7_IX[i] + x * ADAM7_DX[i]) * bytewidth; size_t pixeloutstart = passstart[i] + (y * passw[i] + x) * bytewidth; - for(b = 0; b < bytewidth; ++b) - { + for(b = 0; b < bytewidth; ++b) { out[pixeloutstart + b] = in[pixelinstart + b]; } } } - } - else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/ - { - for(i = 0; i != 7; ++i) - { + } else /*bpp < 8: Adam7 with pixels < 8 bit is a bit trickier: with bit pointers*/ { + for(i = 0; i != 7; ++i) { unsigned x, y, b; unsigned ilinebits = bpp * passw[i]; unsigned olinebits = bpp * w; size_t obp, ibp; /*bit pointers (for out and in buffer)*/ for(y = 0; y < passh[i]; ++y) - for(x = 0; x < passw[i]; ++x) - { + for(x = 0; x < passw[i]; ++x) { ibp = (ADAM7_IY[i] + y * ADAM7_DY[i]) * olinebits + (ADAM7_IX[i] + x * ADAM7_DX[i]) * bpp; obp = (8 * passstart[i]) + (y * ilinebits + x * bpp); - for(b = 0; b < bpp; ++b) - { + for(b = 0; b < bpp; ++b) { unsigned char bit = readBitFromReversedStream(&ibp, in); setBitOfReversedStream(&obp, out, bit); } @@ -6027,8 +5249,7 @@ static void Adam7_interlace(unsigned char* out, const unsigned char* in, unsigne return value is error**/ static unsigned preProcessScanlines(unsigned char** out, size_t* outsize, const unsigned char* in, unsigned w, unsigned h, - const LodePNGInfo* info_png, const LodePNGEncoderSettings* settings) -{ + const LodePNGInfo* info_png, const LodePNGEncoderSettings* settings) { /* This function converts the pure 2D image with the PNG's colortype, into filtered-padded-interlaced data. Steps: *) if no Adam7: 1) add padding bits (= posible extra bits per scanline if bpp < 8) 2) filter @@ -6037,35 +5258,27 @@ static unsigned preProcessScanlines(unsigned char** out, size_t* outsize, const unsigned bpp = lodepng_get_bpp(&info_png->color); unsigned error = 0; - if(info_png->interlace_method == 0) - { + if(info_png->interlace_method == 0) { *outsize = h + (h * ((w * bpp + 7) / 8)); /*image size plus an extra byte per scanline + possible padding bits*/ *out = (unsigned char*)lodepng_malloc(*outsize); if(!(*out) && (*outsize)) error = 83; /*alloc fail*/ - if(!error) - { + if(!error) { /*non multiple of 8 bits per scanline, padding bits needed per scanline*/ - if(bpp < 8 && w * bpp != ((w * bpp + 7) / 8) * 8) - { + if(bpp < 8 && w * bpp != ((w * bpp + 7) / 8) * 8) { unsigned char* padded = (unsigned char*)lodepng_malloc(h * ((w * bpp + 7) / 8)); if(!padded) error = 83; /*alloc fail*/ - if(!error) - { + if(!error) { addPaddingBits(padded, in, ((w * bpp + 7) / 8) * 8, w * bpp, h); error = filter(*out, padded, w, h, &info_png->color, settings); } lodepng_free(padded); - } - else - { + } else { /*we can immediately filter into the out buffer, no other steps needed*/ error = filter(*out, in, w, h, &info_png->color, settings); } } - } - else /*interlace_method is 1 (Adam7)*/ - { + } else /*interlace_method is 1 (Adam7)*/ { unsigned passw[7], passh[7]; size_t filter_passstart[8], padded_passstart[8], passstart[8]; unsigned char* adam7; @@ -6079,15 +5292,12 @@ static unsigned preProcessScanlines(unsigned char** out, size_t* outsize, const adam7 = (unsigned char*)lodepng_malloc(passstart[7]); if(!adam7 && passstart[7]) error = 83; /*alloc fail*/ - if(!error) - { + if(!error) { unsigned i; Adam7_interlace(adam7, in, w, h, bpp); - for(i = 0; i != 7; ++i) - { - if(bpp < 8) - { + for(i = 0; i != 7; ++i) { + if(bpp < 8) { unsigned char* padded = (unsigned char*)lodepng_malloc(padded_passstart[i + 1] - padded_passstart[i]); if(!padded) ERROR_BREAK(83); /*alloc fail*/ addPaddingBits(padded, &adam7[passstart[i]], @@ -6095,9 +5305,7 @@ static unsigned preProcessScanlines(unsigned char** out, size_t* outsize, const error = filter(&(*out)[filter_passstart[i]], padded, passw[i], passh[i], &info_png->color, settings); lodepng_free(padded); - } - else - { + } else { error = filter(&(*out)[filter_passstart[i]], &adam7[padded_passstart[i]], passw[i], passh[i], &info_png->color, settings); } @@ -6118,15 +5326,12 @@ returns 0 if the palette is opaque, returns 1 if the palette has a single color with alpha 0 ==> color key returns 2 if the palette is semi-translucent. */ -static unsigned getPaletteTranslucency(const unsigned char* palette, size_t palettesize) -{ +static unsigned getPaletteTranslucency(const unsigned char* palette, size_t palettesize) { size_t i; unsigned key = 0; unsigned r = 0, g = 0, b = 0; /*the value of the color with alpha 0, so long as color keying is possible*/ - for(i = 0; i != palettesize; ++i) - { - if(!key && palette[4 * i + 3] == 0) - { + for(i = 0; i != palettesize; ++i) { + if(!key && palette[4 * i + 3] == 0) { r = palette[4 * i + 0]; g = palette[4 * i + 1]; b = palette[4 * i + 2]; key = 1; i = (size_t)(-1); /*restart from beginning, to detect earlier opaque colors with key's value*/ @@ -6139,11 +5344,9 @@ static unsigned getPaletteTranslucency(const unsigned char* palette, size_t pale } #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS -static unsigned addUnknownChunks(ucvector* out, unsigned char* data, size_t datasize) -{ +static unsigned addUnknownChunks(ucvector* out, unsigned char* data, size_t datasize) { unsigned char* inchunk = data; - while((size_t)(inchunk - data) < datasize) - { + while((size_t)(inchunk - data) < datasize) { CERROR_TRY_RETURN(lodepng_chunk_append(&out->data, &out->size, inchunk)); out->allocsize = out->size; /*fix the allocsize again*/ inchunk = lodepng_chunk_next(inchunk); @@ -6151,8 +5354,7 @@ static unsigned addUnknownChunks(ucvector* out, unsigned char* data, size_t data return 0; } -static unsigned isGreyICCProfile(const unsigned char* profile, unsigned size) -{ +static unsigned isGreyICCProfile(const unsigned char* profile, unsigned size) { /* It is a grey profile if bytes 16-19 are "GRAY", rgb profile if bytes 16-19 are "RGB ". We do not perform any full parsing of the ICC profile here, other @@ -6166,8 +5368,7 @@ static unsigned isGreyICCProfile(const unsigned char* profile, unsigned size) return profile[16] == 'G' && profile[17] == 'R' && profile[18] == 'A' && profile[19] == 'Y'; } -static unsigned isRGBICCProfile(const unsigned char* profile, unsigned size) -{ +static unsigned isRGBICCProfile(const unsigned char* profile, unsigned size) { /* See comment in isGreyICCProfile*/ if(size < 20) return 0; return profile[16] == 'R' && profile[17] == 'G' && profile[18] == 'B' && profile[19] == ' '; @@ -6176,8 +5377,7 @@ static unsigned isRGBICCProfile(const unsigned char* profile, unsigned size) unsigned lodepng_encode(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h, - LodePNGState* state) -{ + LodePNGState* state) { unsigned char* data = 0; /*uncompressed version of the IDAT chunk data*/ size_t datasize = 0; ucvector outv; @@ -6193,18 +5393,15 @@ unsigned lodepng_encode(unsigned char** out, size_t* outsize, /*check input values validity*/ if((state->info_png.color.colortype == LCT_PALETTE || state->encoder.force_palette) - && (state->info_png.color.palettesize == 0 || state->info_png.color.palettesize > 256)) - { + && (state->info_png.color.palettesize == 0 || state->info_png.color.palettesize > 256)) { state->error = 68; /*invalid palette size, it is only allowed to be 1-256*/ goto cleanup; } - if(state->encoder.zlibsettings.btype > 2) - { + if(state->encoder.zlibsettings.btype > 2) { state->error = 61; /*error: unexisting btype*/ goto cleanup; } - if(state->info_png.interlace_method > 1) - { + if(state->info_png.interlace_method > 1) { state->error = 71; /*error: unexisting interlace mode*/ goto cleanup; } @@ -6215,11 +5412,9 @@ unsigned lodepng_encode(unsigned char** out, size_t* outsize, /* color convert and compute scanline filter types */ lodepng_info_copy(&info, &state->info_png); - if(state->encoder.auto_convert) - { + if(state->encoder.auto_convert) { #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - if(state->info_png.background_defined) - { + if(state->info_png.background_defined) { unsigned bg_r = state->info_png.background_r; unsigned bg_g = state->info_png.background_g; unsigned bg_b = state->info_png.background_b; @@ -6234,8 +5429,7 @@ unsigned lodepng_encode(unsigned char** out, size_t* outsize, state->error = auto_choose_color_from_profile(&info.color, &state->info_raw, &prof); if(state->error) goto cleanup; if(lodepng_convert_rgb(&info.background_r, &info.background_g, &info.background_b, - bg_r, bg_g, bg_b, &info.color, &state->info_png.color)) - { + bg_r, bg_g, bg_b, &info.color, &state->info_png.color)) { state->error = 104; goto cleanup; } @@ -6248,34 +5442,29 @@ unsigned lodepng_encode(unsigned char** out, size_t* outsize, } } #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS - if(state->info_png.iccp_defined) - { + if(state->info_png.iccp_defined) { unsigned grey_icc = isGreyICCProfile(state->info_png.iccp_profile, state->info_png.iccp_profile_size); unsigned grey_png = info.color.colortype == LCT_GREY || info.color.colortype == LCT_GREY_ALPHA; /* TODO: perhaps instead of giving errors or less optimal compression, we can automatically modify the ICC profile here to say "GRAY" or "RGB " to match the PNG color type, unless this will require non trivial changes to the rest of the ICC profile */ - if(!grey_icc && !isRGBICCProfile(state->info_png.iccp_profile, state->info_png.iccp_profile_size)) - { + if(!grey_icc && !isRGBICCProfile(state->info_png.iccp_profile, state->info_png.iccp_profile_size)) { state->error = 100; /* Disallowed profile color type for PNG */ goto cleanup; } - if(!state->encoder.auto_convert && grey_icc != grey_png) - { + if(!state->encoder.auto_convert && grey_icc != grey_png) { /* Non recoverable: encoder not allowed to convert color type, and requested color type not compatible with ICC color type */ state->error = 101; goto cleanup; } - if(grey_icc && !grey_png) - { + if(grey_icc && !grey_png) { /* Non recoverable: trying to set greyscale ICC profile while colored pixels were given */ state->error = 102; goto cleanup; /* NOTE: this relies on the fact that lodepng_auto_choose_color never returns palette for greyscale pixels */ } - if(!grey_icc && grey_png) - { + if(!grey_icc && grey_png) { /* Recoverable but an unfortunate loss in compression density: We have greyscale pixels but are forced to store them in more expensive RGB format that will repeat each value 3 times because the PNG spec does not allow an RGB ICC profile with internal greyscale color data */ @@ -6285,15 +5474,13 @@ unsigned lodepng_encode(unsigned char** out, size_t* outsize, } } #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ - if(!lodepng_color_mode_equal(&state->info_raw, &info.color)) - { + if(!lodepng_color_mode_equal(&state->info_raw, &info.color)) { unsigned char* converted; size_t size = ((size_t)w * (size_t)h * (size_t)lodepng_get_bpp(&info.color) + 7) / 8; converted = (unsigned char*)lodepng_malloc(size); if(!converted && size) state->error = 83; /*alloc fail*/ - if(!state->error) - { + if(!state->error) { state->error = lodepng_convert(converted, image, &info.color, &state->info_raw, w, h); } if(!state->error) preProcessScanlines(&data, &datasize, converted, w, h, &info, &state->encoder); @@ -6302,8 +5489,7 @@ unsigned lodepng_encode(unsigned char** out, size_t* outsize, } else preProcessScanlines(&data, &datasize, image, w, h, &info, &state->encoder); - /* output all PNG chunks */ - { + /* output all PNG chunks */ { #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS size_t i; #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ @@ -6313,8 +5499,7 @@ unsigned lodepng_encode(unsigned char** out, size_t* outsize, addChunk_IHDR(&outv, w, h, info.color.colortype, info.color.bitdepth, info.interlace_method); #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /*unknown chunks between IHDR and PLTE*/ - if(info.unknown_chunks_data[0]) - { + if(info.unknown_chunks_data[0]) { state->error = addUnknownChunks(&outv, info.unknown_chunks_data[0], info.unknown_chunks_size[0]); if(state->error) goto cleanup; } @@ -6325,27 +5510,22 @@ unsigned lodepng_encode(unsigned char** out, size_t* outsize, if(info.chrm_defined) addChunk_cHRM(&outv, &info); #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ /*PLTE*/ - if(info.color.colortype == LCT_PALETTE) - { + if(info.color.colortype == LCT_PALETTE) { addChunk_PLTE(&outv, &info.color); } - if(state->encoder.force_palette && (info.color.colortype == LCT_RGB || info.color.colortype == LCT_RGBA)) - { + if(state->encoder.force_palette && (info.color.colortype == LCT_RGB || info.color.colortype == LCT_RGBA)) { addChunk_PLTE(&outv, &info.color); } /*tRNS*/ - if(info.color.colortype == LCT_PALETTE && getPaletteTranslucency(info.color.palette, info.color.palettesize) != 0) - { + if(info.color.colortype == LCT_PALETTE && getPaletteTranslucency(info.color.palette, info.color.palettesize) != 0) { addChunk_tRNS(&outv, &info.color); } - if((info.color.colortype == LCT_GREY || info.color.colortype == LCT_RGB) && info.color.key_defined) - { + if((info.color.colortype == LCT_GREY || info.color.colortype == LCT_RGB) && info.color.key_defined) { addChunk_tRNS(&outv, &info.color); } #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /*bKGD (must come between PLTE and the IDAt chunks*/ - if(info.background_defined) - { + if(info.background_defined) { state->error = addChunk_bKGD(&outv, &info); if(state->error) goto cleanup; } @@ -6353,8 +5533,7 @@ unsigned lodepng_encode(unsigned char** out, size_t* outsize, if(info.phys_defined) addChunk_pHYs(&outv, &info); /*unknown chunks between PLTE and IDAT*/ - if(info.unknown_chunks_data[1]) - { + if(info.unknown_chunks_data[1]) { state->error = addUnknownChunks(&outv, info.unknown_chunks_data[1], info.unknown_chunks_size[1]); if(state->error) goto cleanup; } @@ -6366,54 +5545,41 @@ unsigned lodepng_encode(unsigned char** out, size_t* outsize, /*tIME*/ if(info.time_defined) addChunk_tIME(&outv, &info.time); /*tEXt and/or zTXt*/ - for(i = 0; i != info.text_num; ++i) - { - if(strlen(info.text_keys[i]) > 79) - { + for(i = 0; i != info.text_num; ++i) { + if(strlen(info.text_keys[i]) > 79) { state->error = 66; /*text chunk too large*/ goto cleanup; } - if(strlen(info.text_keys[i]) < 1) - { + if(strlen(info.text_keys[i]) < 1) { state->error = 67; /*text chunk too small*/ goto cleanup; } - if(state->encoder.text_compression) - { + if(state->encoder.text_compression) { addChunk_zTXt(&outv, info.text_keys[i], info.text_strings[i], &state->encoder.zlibsettings); - } - else - { + } else { addChunk_tEXt(&outv, info.text_keys[i], info.text_strings[i]); } } /*LodePNG version id in text chunk*/ - if(state->encoder.add_id) - { + if(state->encoder.add_id) { unsigned already_added_id_text = 0; - for(i = 0; i != info.text_num; ++i) - { - if(!strcmp(info.text_keys[i], "LodePNG")) - { + for(i = 0; i != info.text_num; ++i) { + if(!strcmp(info.text_keys[i], "LodePNG")) { already_added_id_text = 1; break; } } - if(already_added_id_text == 0) - { + if(already_added_id_text == 0) { addChunk_tEXt(&outv, "LodePNG", LODEPNG_VERSION_STRING); /*it's shorter as tEXt than as zTXt chunk*/ } } /*iTXt*/ - for(i = 0; i != info.itext_num; ++i) - { - if(strlen(info.itext_keys[i]) > 79) - { + for(i = 0; i != info.itext_num; ++i) { + if(strlen(info.itext_keys[i]) > 79) { state->error = 66; /*text chunk too large*/ goto cleanup; } - if(strlen(info.itext_keys[i]) < 1) - { + if(strlen(info.itext_keys[i]) < 1) { state->error = 67; /*text chunk too small*/ goto cleanup; } @@ -6423,8 +5589,7 @@ unsigned lodepng_encode(unsigned char** out, size_t* outsize, } /*unknown chunks between IDAT and IEND*/ - if(info.unknown_chunks_data[2]) - { + if(info.unknown_chunks_data[2]) { state->error = addUnknownChunks(&outv, info.unknown_chunks_data[2], info.unknown_chunks_size[2]); if(state->error) goto cleanup; } @@ -6444,8 +5609,7 @@ unsigned lodepng_encode(unsigned char** out, size_t* outsize, } unsigned lodepng_encode_memory(unsigned char** out, size_t* outsize, const unsigned char* image, - unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) -{ + unsigned w, unsigned h, LodePNGColorType colortype, unsigned bitdepth) { unsigned error; LodePNGState state; lodepng_state_init(&state); @@ -6459,20 +5623,17 @@ unsigned lodepng_encode_memory(unsigned char** out, size_t* outsize, const unsig return error; } -unsigned lodepng_encode32(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h) -{ +unsigned lodepng_encode32(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h) { return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGBA, 8); } -unsigned lodepng_encode24(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h) -{ +unsigned lodepng_encode24(unsigned char** out, size_t* outsize, const unsigned char* image, unsigned w, unsigned h) { return lodepng_encode_memory(out, outsize, image, w, h, LCT_RGB, 8); } #ifdef LODEPNG_COMPILE_DISK unsigned lodepng_encode_file(const char* filename, const unsigned char* image, unsigned w, unsigned h, - LodePNGColorType colortype, unsigned bitdepth) -{ + LodePNGColorType colortype, unsigned bitdepth) { unsigned char* buffer; size_t buffersize; unsigned error = lodepng_encode_memory(&buffer, &buffersize, image, w, h, colortype, bitdepth); @@ -6481,19 +5642,16 @@ unsigned lodepng_encode_file(const char* filename, const unsigned char* image, u return error; } -unsigned lodepng_encode32_file(const char* filename, const unsigned char* image, unsigned w, unsigned h) -{ +unsigned lodepng_encode32_file(const char* filename, const unsigned char* image, unsigned w, unsigned h) { return lodepng_encode_file(filename, image, w, h, LCT_RGBA, 8); } -unsigned lodepng_encode24_file(const char* filename, const unsigned char* image, unsigned w, unsigned h) -{ +unsigned lodepng_encode24_file(const char* filename, const unsigned char* image, unsigned w, unsigned h) { return lodepng_encode_file(filename, image, w, h, LCT_RGB, 8); } #endif /*LODEPNG_COMPILE_DISK*/ -void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings) -{ +void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings) { lodepng_compress_settings_init(&settings->zlibsettings); settings->filter_palette_zero = 1; settings->filter_strategy = LFS_MINSUM; @@ -6514,10 +5672,8 @@ void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings) This returns the description of a numerical error code in English. This is also the documentation of all the error codes. */ -const char* lodepng_error_text(unsigned code) -{ - switch(code) - { +const char* lodepng_error_text(unsigned code) { + switch(code) { case 0: return "no error, everything went ok"; case 1: return "nothing done yet"; /*the Encoder/Decoder has done nothing yet, error checking makes no sense yet*/ case 10: return "end of input memory reached without huffman end code"; /*while huffman decoding*/ @@ -6531,10 +5687,11 @@ const char* lodepng_error_text(unsigned code) case 19: return "end of out buffer memory reached while inflating"; case 20: return "invalid deflate block BTYPE encountered while decoding"; case 21: return "NLEN is not ones complement of LEN in a deflate block"; - /*end of out buffer memory reached while inflating: - This can happen if the inflated deflate data is longer than the amount of bytes required to fill up - all the pixels of the image, given the color depth and image dimensions. Something that doesn't - happen in a normal, well encoded, PNG image.*/ + + /*end of out buffer memory reached while inflating: + This can happen if the inflated deflate data is longer than the amount of bytes required to fill up + all the pixels of the image, given the color depth and image dimensions. Something that doesn't + happen in a normal, well encoded, PNG image.*/ case 22: return "end of out buffer memory reached while inflating"; case 23: return "end of in buffer memory reached while inflating"; case 24: return "invalid FCHECK in zlib header"; @@ -6579,7 +5736,8 @@ const char* lodepng_error_text(unsigned code) case 61: return "invalid BTYPE given in the settings of the encoder (only 0, 1 and 2 are allowed)"; /*LodePNG leaves the choice of RGB to greyscale conversion formula to the user.*/ case 62: return "conversion from color to greyscale not supported"; - case 63: return "length of a chunk too long, max allowed for PNG is 2147483647 bytes per chunk"; /*(2^31-1)*/ + /*(2^31-1)*/ + case 63: return "length of a chunk too long, max allowed for PNG is 2147483647 bytes per chunk"; /*this would result in the inability of a deflated block to ever contain an end code. It must be at least 1.*/ case 64: return "the length of the END symbol 256 in the Huffman tree is 0"; case 66: return "the length of a text chunk keyword given to the encoder is longer than the maximum of 79 bytes"; @@ -6633,12 +5791,10 @@ const char* lodepng_error_text(unsigned code) /* ////////////////////////////////////////////////////////////////////////// */ #ifdef LODEPNG_COMPILE_CPP -namespace lodepng -{ +namespace lodepng { #ifdef LODEPNG_COMPILE_DISK -unsigned load_file(std::vector& buffer, const std::string& filename) -{ +unsigned load_file(std::vector& buffer, const std::string& filename) { long size = lodepng_filesize(filename.c_str()); if(size < 0) return 78; buffer.resize((size_t)size); @@ -6646,8 +5802,7 @@ unsigned load_file(std::vector& buffer, const std::string& filena } /*write given buffer to the file, overwriting the file, it doesn't append to it.*/ -unsigned save_file(const std::vector& buffer, const std::string& filename) -{ +unsigned save_file(const std::vector& buffer, const std::string& filename) { return lodepng_save_file(buffer.empty() ? 0 : &buffer[0], buffer.size(), filename.c_str()); } #endif /* LODEPNG_COMPILE_DISK */ @@ -6655,13 +5810,11 @@ unsigned save_file(const std::vector& buffer, const std::string& #ifdef LODEPNG_COMPILE_ZLIB #ifdef LODEPNG_COMPILE_DECODER unsigned decompress(std::vector& out, const unsigned char* in, size_t insize, - const LodePNGDecompressSettings& settings) -{ + const LodePNGDecompressSettings& settings) { unsigned char* buffer = 0; size_t buffersize = 0; unsigned error = zlib_decompress(&buffer, &buffersize, in, insize, &settings); - if(buffer) - { + if(buffer) { out.insert(out.end(), &buffer[0], &buffer[buffersize]); lodepng_free(buffer); } @@ -6669,21 +5822,18 @@ unsigned decompress(std::vector& out, const unsigned char* in, si } unsigned decompress(std::vector& out, const std::vector& in, - const LodePNGDecompressSettings& settings) -{ + const LodePNGDecompressSettings& settings) { return decompress(out, in.empty() ? 0 : &in[0], in.size(), settings); } #endif /* LODEPNG_COMPILE_DECODER */ #ifdef LODEPNG_COMPILE_ENCODER unsigned compress(std::vector& out, const unsigned char* in, size_t insize, - const LodePNGCompressSettings& settings) -{ + const LodePNGCompressSettings& settings) { unsigned char* buffer = 0; size_t buffersize = 0; unsigned error = zlib_compress(&buffer, &buffersize, in, insize, &settings); - if(buffer) - { + if(buffer) { out.insert(out.end(), &buffer[0], &buffer[buffersize]); lodepng_free(buffer); } @@ -6691,8 +5841,7 @@ unsigned compress(std::vector& out, const unsigned char* in, size } unsigned compress(std::vector& out, const std::vector& in, - const LodePNGCompressSettings& settings) -{ + const LodePNGCompressSettings& settings) { return compress(out, in.empty() ? 0 : &in[0], in.size(), settings); } #endif /* LODEPNG_COMPILE_ENCODER */ @@ -6701,24 +5850,20 @@ unsigned compress(std::vector& out, const std::vector& out, unsigned& w, unsigned& h, const unsigned char* in, - size_t insize, LodePNGColorType colortype, unsigned bitdepth) -{ + size_t insize, LodePNGColorType colortype, unsigned bitdepth) { unsigned char* buffer; unsigned error = lodepng_decode_memory(&buffer, &w, &h, in, insize, colortype, bitdepth); - if(buffer && !error) - { + if(buffer && !error) { State state; state.info_raw.colortype = colortype; state.info_raw.bitdepth = bitdepth; @@ -6743,19 +5886,16 @@ unsigned decode(std::vector& out, unsigned& w, unsigned& h, const } unsigned decode(std::vector& out, unsigned& w, unsigned& h, - const std::vector& in, LodePNGColorType colortype, unsigned bitdepth) -{ + const std::vector& in, LodePNGColorType colortype, unsigned bitdepth) { return decode(out, w, h, in.empty() ? 0 : &in[0], (unsigned)in.size(), colortype, bitdepth); } unsigned decode(std::vector& out, unsigned& w, unsigned& h, State& state, - const unsigned char* in, size_t insize) -{ + const unsigned char* in, size_t insize) { unsigned char* buffer = NULL; unsigned error = lodepng_decode(&buffer, &w, &h, &state, in, insize); - if(buffer && !error) - { + if(buffer && !error) { size_t buffersize = lodepng_get_raw_size(w, h, &state.info_raw); out.insert(out.end(), &buffer[0], &buffer[buffersize]); } @@ -6765,15 +5905,13 @@ unsigned decode(std::vector& out, unsigned& w, unsigned& h, unsigned decode(std::vector& out, unsigned& w, unsigned& h, State& state, - const std::vector& in) -{ + const std::vector& in) { return decode(out, w, h, state, in.empty() ? 0 : &in[0], in.size()); } #ifdef LODEPNG_COMPILE_DISK unsigned decode(std::vector& out, unsigned& w, unsigned& h, const std::string& filename, - LodePNGColorType colortype, unsigned bitdepth) -{ + LodePNGColorType colortype, unsigned bitdepth) { std::vector buffer; unsigned error = load_file(buffer, filename); if(error) return error; @@ -6784,13 +5922,11 @@ unsigned decode(std::vector& out, unsigned& w, unsigned& h, const #ifdef LODEPNG_COMPILE_ENCODER unsigned encode(std::vector& out, const unsigned char* in, unsigned w, unsigned h, - LodePNGColorType colortype, unsigned bitdepth) -{ + LodePNGColorType colortype, unsigned bitdepth) { unsigned char* buffer; size_t buffersize; unsigned error = lodepng_encode_memory(&buffer, &buffersize, in, w, h, colortype, bitdepth); - if(buffer) - { + if(buffer) { out.insert(out.end(), &buffer[0], &buffer[buffersize]); lodepng_free(buffer); } @@ -6799,21 +5935,18 @@ unsigned encode(std::vector& out, const unsigned char* in, unsign unsigned encode(std::vector& out, const std::vector& in, unsigned w, unsigned h, - LodePNGColorType colortype, unsigned bitdepth) -{ + LodePNGColorType colortype, unsigned bitdepth) { if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84; return encode(out, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth); } unsigned encode(std::vector& out, const unsigned char* in, unsigned w, unsigned h, - State& state) -{ + State& state) { unsigned char* buffer; size_t buffersize; unsigned error = lodepng_encode(&buffer, &buffersize, in, w, h, &state); - if(buffer) - { + if(buffer) { out.insert(out.end(), &buffer[0], &buffer[buffersize]); lodepng_free(buffer); } @@ -6822,8 +5955,7 @@ unsigned encode(std::vector& out, unsigned encode(std::vector& out, const std::vector& in, unsigned w, unsigned h, - State& state) -{ + State& state) { if(lodepng_get_raw_size(w, h, &state.info_raw) > in.size()) return 84; return encode(out, in.empty() ? 0 : &in[0], w, h, state); } @@ -6831,8 +5963,7 @@ unsigned encode(std::vector& out, #ifdef LODEPNG_COMPILE_DISK unsigned encode(const std::string& filename, const unsigned char* in, unsigned w, unsigned h, - LodePNGColorType colortype, unsigned bitdepth) -{ + LodePNGColorType colortype, unsigned bitdepth) { std::vector buffer; unsigned error = encode(buffer, in, w, h, colortype, bitdepth); if(!error) error = save_file(buffer, filename); @@ -6841,8 +5972,7 @@ unsigned encode(const std::string& filename, unsigned encode(const std::string& filename, const std::vector& in, unsigned w, unsigned h, - LodePNGColorType colortype, unsigned bitdepth) -{ + LodePNGColorType colortype, unsigned bitdepth) { if(lodepng_get_raw_size_lct(w, h, colortype, bitdepth) > in.size()) return 84; return encode(filename, in.empty() ? 0 : &in[0], w, h, colortype, bitdepth); } diff --git a/lodepng.h b/lodepng.h index 2780e095..6f161606 100644 --- a/lodepng.h +++ b/lodepng.h @@ -1,5 +1,5 @@ /* -LodePNG version 20180910 +LodePNG version 20181230 Copyright (c) 2005-2018 Lode Vandevenne @@ -88,8 +88,7 @@ source files with custom allocators.*/ #ifdef LODEPNG_COMPILE_PNG /*The PNG color types (also used for raw).*/ -typedef enum LodePNGColorType -{ +typedef enum LodePNGColorType { LCT_GREY = 0, /*greyscale: 1,2,4,8,16 bit*/ LCT_RGB = 2, /*RGB: 8,16 bit*/ LCT_PALETTE = 3, /*palette: 1,2,4,8 bit*/ @@ -196,8 +195,7 @@ unsigned lodepng_encode24_file(const char* filename, #ifdef LODEPNG_COMPILE_CPP -namespace lodepng -{ +namespace lodepng { #ifdef LODEPNG_COMPILE_DECODER /*Same as lodepng_decode_memory, but decodes to an std::vector. The colortype is the format to output the pixels to. Default is RGBA 8-bit per channel.*/ @@ -253,8 +251,7 @@ const char* lodepng_error_text(unsigned code); #ifdef LODEPNG_COMPILE_DECODER /*Settings for zlib decompression*/ typedef struct LodePNGDecompressSettings LodePNGDecompressSettings; -struct LodePNGDecompressSettings -{ +struct LodePNGDecompressSettings { /* Check LodePNGDecoderSettings for more ignorable errors such as ignore_crc */ unsigned ignore_adler32; /*if 1, continue and don't give an error message if the Adler32 checksum is corrupted*/ @@ -282,8 +279,7 @@ Settings for zlib compression. Tweaking these settings tweaks the balance between speed and compression ratio. */ typedef struct LodePNGCompressSettings LodePNGCompressSettings; -struct LodePNGCompressSettings /*deflate = compress*/ -{ +struct LodePNGCompressSettings /*deflate = compress*/ { /*LZ77 related settings*/ unsigned btype; /*the block type for LZ (0, 1, 2 or 3, see zlib standard). Should be 2 for proper compression.*/ unsigned use_lz77; /*whether or not to use LZ77. Should be 1 for proper compression.*/ @@ -316,8 +312,7 @@ Color mode of an image. Contains all information required to decode the pixel bits to RGBA colors. This information is the same as used in the PNG file format, and is used both for PNG and raw image data in LodePNG. */ -typedef struct LodePNGColorMode -{ +typedef struct LodePNGColorMode { /*header (IHDR)*/ LodePNGColorType colortype; /*color type, see PNG standard or documentation further in this header file*/ unsigned bitdepth; /*bits per sample, see PNG standard or documentation further in this header file*/ @@ -395,8 +390,7 @@ size_t lodepng_get_raw_size(unsigned w, unsigned h, const LodePNGColorMode* colo #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS /*The information of a Time chunk in PNG.*/ -typedef struct LodePNGTime -{ +typedef struct LodePNGTime { unsigned year; /*2 bytes used (0-65535)*/ unsigned month; /*1-12*/ unsigned day; /*1-31*/ @@ -407,8 +401,7 @@ typedef struct LodePNGTime #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ /*Information about the PNG image, except pixels, width and height.*/ -typedef struct LodePNGInfo -{ +typedef struct LodePNGInfo { /*header (IHDR), palette (PLTE) and transparency (tRNS) chunks*/ unsigned compression_method;/*compression method of the original file. Always 0.*/ unsigned filter_method; /*filter method of the original file*/ @@ -614,8 +607,7 @@ unsigned lodepng_convert(unsigned char* out, const unsigned char* in, Settings for the decoder. This contains settings for the PNG and the Zlib decoder, but not the Info settings from the Info structs. */ -typedef struct LodePNGDecoderSettings -{ +typedef struct LodePNGDecoderSettings { LodePNGDecompressSettings zlibsettings; /*in here is the setting to ignore Adler32 checksums*/ /* Check LodePNGDecompressSettings for more ignorable errors such as ignore_adler32 */ @@ -641,8 +633,7 @@ void lodepng_decoder_settings_init(LodePNGDecoderSettings* settings); #ifdef LODEPNG_COMPILE_ENCODER /*automatically use color type with less bits per pixel if losslessly possible. Default: AUTO*/ -typedef enum LodePNGFilterStrategy -{ +typedef enum LodePNGFilterStrategy { /*every filter at zero*/ LFS_ZERO, /*Use filter that gives minimum sum, as described in the official PNG filter heuristic.*/ @@ -664,8 +655,7 @@ which helps decide which color model to use for encoding. Used internally by default if "auto_convert" is enabled. Public because it's useful for custom algorithms. NOTE: This is not related to the ICC color profile, search "iccp_profile" instead to find the ICC/chromacity/... fields in this header file.*/ -typedef struct LodePNGColorProfile -{ +typedef struct LodePNGColorProfile { unsigned colored; /*not greyscale*/ unsigned key; /*image is not opaque and color key is possible instead of full alpha*/ unsigned short key_r; /*key values, always as 16-bit, in 8-bit case the byte is duplicated, e.g. 65535 means 255*/ @@ -693,8 +683,7 @@ unsigned lodepng_auto_choose_color(LodePNGColorMode* mode_out, const LodePNGColorMode* mode_in); /*Settings for the encoder.*/ -typedef struct LodePNGEncoderSettings -{ +typedef struct LodePNGEncoderSettings { LodePNGCompressSettings zlibsettings; /*settings for the zlib encoder, such as window size, ...*/ unsigned auto_convert; /*automatically choose output PNG color type. Default: true*/ @@ -730,8 +719,7 @@ void lodepng_encoder_settings_init(LodePNGEncoderSettings* settings); #if defined(LODEPNG_COMPILE_DECODER) || defined(LODEPNG_COMPILE_ENCODER) /*The settings, state and information for extended encoding and decoding.*/ -typedef struct LodePNGState -{ +typedef struct LodePNGState { #ifdef LODEPNG_COMPILE_DECODER LodePNGDecoderSettings decoder; /*the decoding settings*/ #endif /*LODEPNG_COMPILE_DECODER*/ @@ -965,11 +953,9 @@ unsigned lodepng_save_file(const unsigned char* buffer, size_t buffersize, const #ifdef LODEPNG_COMPILE_CPP /* The LodePNG C++ wrapper uses std::vectors instead of manually allocated memory buffers. */ -namespace lodepng -{ +namespace lodepng { #ifdef LODEPNG_COMPILE_PNG -class State : public LodePNGState -{ +class State : public LodePNGState { public: State(); State(const State& other); @@ -1673,8 +1659,7 @@ examples can be found on the LodePNG website. #include "lodepng.h" #include -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { const char* filename = argc > 1 ? argv[1] : "test.png"; //load and decode @@ -1693,8 +1678,7 @@ int main(int argc, char *argv[]) #include "lodepng.h" -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { unsigned error; unsigned char* image; size_t width, height; @@ -1763,6 +1747,7 @@ yyyymmdd. Some changes aren't backwards compatible. Those are indicated with a (!) symbol. +*) 30 dec 2018: code style changes only: removed newlines before opening braces. *) 10 sep 2018: added way to inspect metadata chunks without full decoding. *) 19 aug 2018 (!): fixed color mode bKGD is encoded with and made it use palette index in case of palette. diff --git a/lodepng_benchmark.cpp b/lodepng_benchmark.cpp index 66de1239..b3272266 100644 --- a/lodepng_benchmark.cpp +++ b/lodepng_benchmark.cpp @@ -50,31 +50,25 @@ bool verbose = false; //////////////////////////////////////////////////////////////////////////////// -double getTime() -{ +double getTime() { return SDL_GetTicks() / 1000.0; } -void fail() -{ +void fail() { throw 1; //that's how to let a unittest fail } template -void assertEquals(const T& expected, const U& actual, const std::string& message = "") -{ - if(expected != (T)actual) - { +void assertEquals(const T& expected, const U& actual, const std::string& message = "") { + if(expected != (T)actual) { std::cout << "Error: Not equal! Expected " << expected << " got " << actual << "." << std::endl; std::cout << "Message: " << message << std::endl; fail(); } } -void assertTrue(bool value, const std::string& message = "") -{ - if(!value) - { +void assertTrue(bool value, const std::string& message = "") { + if(!value) { std::cout << "Error: expected true." << std::endl; std::cout << "Message: " << message << std::endl; fail(); @@ -82,8 +76,7 @@ void assertTrue(bool value, const std::string& message = "") } //Test image data -struct Image -{ +struct Image { std::vector data; unsigned width; unsigned height; @@ -93,28 +86,24 @@ struct Image //Utility for debug messages template -std::string valtostr(const T& val) -{ +std::string valtostr(const T& val) { std::ostringstream sstream; sstream << val; return sstream.str(); } template -void printValue(const std::string& name, const T& value, const std::string& unit = "") -{ +void printValue(const std::string& name, const T& value, const std::string& unit = "") { std::cout << name << ": " << value << unit << std::endl; } template -void printValue(const std::string& name, const T& value, const std::string& s2, const U& value2, const std::string& unit = "") -{ +void printValue(const std::string& name, const T& value, const std::string& s2, const U& value2, const std::string& unit = "") { std::cout << name << ": " << value << s2 << value2 << unit << std::endl; } //Test LodePNG encoding and decoding the encoded result, using the C interface -void doCodecTest(Image& image) -{ +void doCodecTest(Image& image) { unsigned char* encoded = 0; size_t encoded_size = 0; unsigned char* decoded = 0; @@ -131,8 +120,7 @@ void doCodecTest(Image& image) assertEquals(0, error_enc, "encoder error C"); double t_dec0 = getTime(); - for(int i = 0; i < NUM_DECODE; i++) - { + for(int i = 0; i < NUM_DECODE; i++) { unsigned error_dec = lodepng_decode_memory(&decoded, &decoded_w, &decoded_h, encoded, encoded_size, image.colorType, image.bitDepth); assertEquals(0, error_dec, "decoder error C"); @@ -151,8 +139,7 @@ void doCodecTest(Image& image) colormode.bitdepth = image.bitDepth; total_in_size += lodepng_get_raw_size(image.width, image.height, &colormode); - if(verbose) - { + if(verbose) { printValue("encoding time", t_enc1 - t_enc0, "s"); std::cout << "compression: " << ((double)(encoded_size) / (double)(image.data.size())) * 100 << "%" << " ratio: " << ((double)(image.data.size()) / (double)(encoded_size)) @@ -169,8 +156,7 @@ void doCodecTest(Image& image) static const int IMGSIZE = 4096; -void testPatternSine() -{ +void testPatternSine() { if(verbose) std::cout << "sine pattern" << std::endl; /* @@ -188,8 +174,7 @@ void testPatternSine() image.bitDepth = 8; image.data.resize(w * h * 4); for(int y = 0; y < h; y++) - for(int x = 0; x < w; x++) - { + for(int x = 0; x < w; x++) { //pattern 1 image.data[4 * w * y + 4 * x + 0] = (unsigned char)(127 * (1 + std::sin(( x * x + y * y) / (w * h / 8.0)))); image.data[4 * w * y + 4 * x + 1] = (unsigned char)(127 * (1 + std::sin(((w - x - 1) * (w - x - 1) + y * y) / (w * h / 8.0)))); @@ -200,8 +185,7 @@ void testPatternSine() doCodecTest(image); } -void testPatternSineNoAlpha() -{ +void testPatternSineNoAlpha() { if(verbose) std::cout << "sine pattern w/o alpha" << std::endl; /* @@ -219,8 +203,7 @@ void testPatternSineNoAlpha() image.bitDepth = 8; image.data.resize(w * h * 3); for(int y = 0; y < h; y++) - for(int x = 0; x < w; x++) - { + for(int x = 0; x < w; x++) { //pattern 1 image.data[3 * w * y + 3 * x + 0] = (unsigned char)(127 * (1 + std::sin(( x * x + y * y) / (w * h / 8.0)))); image.data[3 * w * y + 3 * x + 1] = (unsigned char)(127 * (1 + std::sin(((w - x - 1) * (w - x - 1) + y * y) / (w * h / 8.0)))); @@ -230,8 +213,7 @@ void testPatternSineNoAlpha() doCodecTest(image); } -void testPatternXor() -{ +void testPatternXor() { if(verbose) std::cout << "xor pattern" << std::endl; Image image; @@ -243,8 +225,7 @@ void testPatternXor() image.bitDepth = 8; image.data.resize(w * h * 3); for(int y = 0; y < h; y++) - for(int x = 0; x < w; x++) - { + for(int x = 0; x < w; x++) { image.data[3 * w * y + 3 * x + 0] = x ^ y; image.data[3 * w * y + 3 * x + 1] = x ^ y; image.data[3 * w * y + 3 * x + 2] = x ^ y; @@ -257,15 +238,13 @@ static unsigned int m_w = 1; static unsigned int m_z = 2; //"Multiply-With-Carry" generator of G. Marsaglia -unsigned int getRandomUint() -{ +unsigned int getRandomUint() { m_z = 36969 * (m_z & 65535) + (m_z >> 16); m_w = 18000 * (m_w & 65535) + (m_w >> 16); return (m_z << 16) + m_w; //32-bit result } -void testPatternPseudoRan() -{ +void testPatternPseudoRan() { if(verbose) std::cout << "pseudorandom pattern" << std::endl; Image image; @@ -277,8 +256,7 @@ void testPatternPseudoRan() image.bitDepth = 8; image.data.resize(w * h * 3); for(int y = 0; y < h; y++) - for(int x = 0; x < w; x++) - { + for(int x = 0; x < w; x++) { unsigned int random = getRandomUint(); image.data[3 * w * y + 3 * x + 0] = random % 256; image.data[3 * w * y + 3 * x + 1] = (random >> 8) % 256; @@ -288,8 +266,7 @@ void testPatternPseudoRan() doCodecTest(image); } -void testPatternSineXor() -{ +void testPatternSineXor() { if(verbose) std::cout << "sine+xor pattern" << std::endl; Image image; @@ -301,8 +278,7 @@ void testPatternSineXor() image.bitDepth = 8; image.data.resize(w * h * 4); for(int y = 0; y < h; y++) - for(int x = 0; x < w; x++) - { + for(int x = 0; x < w; x++) { //pattern 1 image.data[4 * w * y + 4 * x + 0] = (unsigned char)(127 * (1 + std::sin(( x * x + y * y) / (w * h / 8.0)))); image.data[4 * w * y + 4 * x + 1] = (unsigned char)(127 * (1 + std::sin(((w - x - 1) * (w - x - 1) + y * y) / (w * h / 8.0)))); @@ -317,8 +293,7 @@ void testPatternSineXor() doCodecTest(image); } -void testPatternGreyMandel() -{ +void testPatternGreyMandel() { if(verbose) std::cout << "grey mandelbrot pattern" << std::endl; Image image; @@ -337,14 +312,12 @@ void testPatternGreyMandel() int maxIterations = 300; for(int y = 0; y < h; y++) - for(int x = 0; x < w; x++) - { + for(int x = 0; x < w; x++) { pr = 1.5 * (x - w / 2) / (0.5 * zoom * w) + moveX; pi = (y - h / 2) / (0.5 * zoom * h) + moveY; newRe = newIm = oldRe = oldIm = 0; //these should start at 0,0 int i; - for(i = 0; i < maxIterations; i++) - { + for(i = 0; i < maxIterations; i++) { oldRe = newRe; oldIm = newIm; newRe = oldRe * oldRe - oldIm * oldIm + pr; @@ -357,8 +330,7 @@ void testPatternGreyMandel() doCodecTest(image); } -void testPatternGreyMandelSmall() -{ +void testPatternGreyMandelSmall() { if(verbose) std::cout << "grey mandelbrot pattern" << std::endl; Image image; @@ -377,14 +349,12 @@ void testPatternGreyMandelSmall() int maxIterations = 300; for(int y = 0; y < h; y++) - for(int x = 0; x < w; x++) - { + for(int x = 0; x < w; x++) { pr = 1.5 * (x - w / 2) / (0.5 * zoom * w) + moveX; pi = (y - h / 2) / (0.5 * zoom * h) + moveY; newRe = newIm = oldRe = oldIm = 0; //these should start at 0,0 int i; - for(i = 0; i < maxIterations; i++) - { + for(i = 0; i < maxIterations; i++) { oldRe = newRe; oldIm = newIm; newRe = oldRe * oldRe - oldIm * oldIm + pr; @@ -397,8 +367,7 @@ void testPatternGreyMandelSmall() doCodecTest(image); } -void testPatternX() -{ +void testPatternX() { if(verbose) std::cout << "x pattern" << std::endl; Image image; @@ -410,16 +379,14 @@ void testPatternX() image.bitDepth = 8; image.data.resize(w * h * 4); for(int y = 0; y < h; y++) - for(int x = 0; x < w; x++) - { + for(int x = 0; x < w; x++) { image.data[w * y + x + 0] = x % 256; } doCodecTest(image); } -void testPatternY() -{ +void testPatternY() { if(verbose) std::cout << "y pattern" << std::endl; Image image; @@ -431,16 +398,14 @@ void testPatternY() image.bitDepth = 8; image.data.resize(w * h * 4); for(int y = 0; y < h; y++) - for(int x = 0; x < w; x++) - { + for(int x = 0; x < w; x++) { image.data[w * y + x + 0] = y % 256; } doCodecTest(image); } -void testPatternDisk(const std::string& filename) -{ +void testPatternDisk(const std::string& filename) { if(verbose) std::cout << "file " << filename << std::endl; Image image; @@ -451,14 +416,12 @@ void testPatternDisk(const std::string& filename) doCodecTest(image); } -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { verbose = false; std::vector files; - for(int i = 1; i < argc; i++) - { + for(int i = 1; i < argc; i++) { std::string arg = argv[i]; if(arg == "-v") verbose = true; else files.push_back(arg); @@ -466,8 +429,7 @@ int main(int argc, char *argv[]) std::cout << "NUM_DECODE: " << NUM_DECODE << std::endl; - if(files.empty()) - { + if(files.empty()) { //testPatternDisk("testdata/frymire.png"); //testPatternGreyMandel(); @@ -490,11 +452,8 @@ int main(int argc, char *argv[]) /*testPatternDisk("testdata/Ecce_homo_by_Hieronymus_Bosch.png"); testPatternSine();*/ - } - else - { - for(size_t i = 0; i < files.size(); i++) - { + } else { + for(size_t i = 0; i < files.size(); i++) { testPatternDisk(files[i]); } } diff --git a/lodepng_unittest.cpp b/lodepng_unittest.cpp index 5087d072..da996fdf 100644 --- a/lodepng_unittest.cpp +++ b/lodepng_unittest.cpp @@ -118,16 +118,13 @@ git difftool -y //////////////////////////////////////////////////////////////////////////////// -void fail() -{ +void fail() { throw 1; //that's how to let a unittest fail } template -void assertEquals(const T& expected, const U& actual, const std::string& message = "") -{ - if(expected != (T)actual) - { +void assertEquals(const T& expected, const U& actual, const std::string& message = "") { + if(expected != (T)actual) { std::cout << "Error: Not equal! Expected " << expected << " got " << (T)actual << ". " << "Message: " << message << std::endl; fail(); @@ -135,52 +132,42 @@ void assertEquals(const T& expected, const U& actual, const std::string& message } template -void assertNotEquals(const T& expected, const U& actual, const std::string& message = "") -{ - if(expected == (T)actual) - { +void assertNotEquals(const T& expected, const U& actual, const std::string& message = "") { + if(expected == (T)actual) { std::cout << "Error: Equal but expected not equal! Expected not " << expected << " got " << (T)actual << ". " << "Message: " << message << std::endl; fail(); } } -void assertTrue(bool value, const std::string& message = "") -{ - if(!value) - { +void assertTrue(bool value, const std::string& message = "") { + if(!value) { std::cout << "Error: expected true. " << "Message: " << message << std::endl; fail(); } } //assert that no error -void assertNoPNGError(unsigned error, const std::string& message = "") -{ - if(error) - { +void assertNoPNGError(unsigned error, const std::string& message = "") { + if(error) { std::string msg = (message == "") ? lodepng_error_text(error) : message + std::string(": ") + lodepng_error_text(error); assertEquals(0, error, msg); } } -void assertNoError(unsigned error) -{ - if(error) - { +void assertNoError(unsigned error) { + if(error) { assertEquals(0, error, "Expected no error"); } } #define STR_EXPAND(s) #s #define STR(s) STR_EXPAND(s) -#define ASSERT_EQUALS(e, v) \ -{\ +#define ASSERT_EQUALS(e, v) {\ assertEquals(e, v, std::string() + "line " + STR(__LINE__) + ": " + STR(v) + " ASSERT_EQUALS(" + #e + ", " + #v + ")");\ } -#define ASSERT_NOT_EQUALS(e, v) \ -{\ +#define ASSERT_NOT_EQUALS(e, v) {\ assertNotEquals(e, v, std::string() + "line " + STR(__LINE__) + ": " + STR(v) + " ASSERT_NOT_EQUALS(" + #e + ", " + #v + ")");\ } #define ASSERT_STRING_EQUALS(e, v) ASSERT_EQUALS(std::string(e), std::string(v)) @@ -193,10 +180,8 @@ static const std::string BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrs //T and U can be std::string or std::vector template -void toBase64(T& out, const U& in) -{ - for(size_t i = 0; i < in.size(); i += 3) - { +void toBase64(T& out, const U& in) { + for(size_t i = 0; i < in.size(); i += 3) { int v = 65536 * in[i]; if(i + 1 < in.size()) v += 256 * in[i + 1]; if(i + 2 < in.size()) v += in[i + 2]; @@ -209,8 +194,7 @@ void toBase64(T& out, const U& in) } } -int fromBase64(int v) -{ +int fromBase64(int v) { if(v >= 'A' && v <= 'Z') return (v - 'A'); if(v >= 'a' && v <= 'z') return (v - 'a' + 26); if(v >= '0' && v <= '9') return (v - '0' + 52); @@ -221,10 +205,8 @@ int fromBase64(int v) //T and U can be std::string or std::vector template -void fromBase64(T& out, const U& in) -{ - for(size_t i = 0; i + 3 < in.size(); i += 4) - { +void fromBase64(T& out, const U& in) { + for(size_t i = 0; i + 3 < in.size(); i += 4) { int v = 262144 * fromBase64(in[i]) + 4096 * fromBase64(in[i + 1]) + 64 * fromBase64(in[i + 2]) + fromBase64(in[i + 3]); out.push_back((v >> 16) & 0xff); if(in[i + 2] != '=') out.push_back((v >> 8) & 0xff); @@ -235,8 +217,7 @@ void fromBase64(T& out, const U& in) //////////////////////////////////////////////////////////////////////////////// //Test image data -struct Image -{ +struct Image { std::vector data; unsigned width; unsigned height; @@ -246,18 +227,15 @@ struct Image //Utility for debug messages template -std::string valtostr(const T& val) -{ +std::string valtostr(const T& val) { std::ostringstream sstream; sstream << val; return sstream.str(); } //Get number of color channels for a given PNG color type -unsigned getNumColorChannels(unsigned colorType) -{ - switch(colorType) - { +unsigned getNumColorChannels(unsigned colorType) { + switch(colorType) { case 0: return 1; /*grey*/ case 2: return 3; /*RGB*/ case 3: return 1; /*palette*/ @@ -269,8 +247,7 @@ unsigned getNumColorChannels(unsigned colorType) //Generate a test image with some data in it, the contents of the data is unspecified, //except the content is not just one plain color, and not true random either to be compressible. -void generateTestImage(Image& image, unsigned width, unsigned height, LodePNGColorType colorType = LCT_RGBA, unsigned bitDepth = 8) -{ +void generateTestImage(Image& image, unsigned width, unsigned height, LodePNGColorType colorType = LCT_RGBA, unsigned bitDepth = 8) { image.width = width; image.height = height; image.colorType = colorType; @@ -280,8 +257,7 @@ void generateTestImage(Image& image, unsigned width, unsigned height, LodePNGCol size_t size = (width * height * bits + 7) / 8; //total image size in bytes image.data.resize(size); unsigned char value = 128; - for(size_t i = 0; i < size; i++) - { + for(size_t i = 0; i < size; i++) { image.data[i] = value++; } } @@ -289,8 +265,7 @@ void generateTestImage(Image& image, unsigned width, unsigned height, LodePNGCol //Generate a 16-bit test image with minimal size that requires at minimum the given color type (bit depth, greyscaleness, ...) //If key is true, makes it such that exactly one color is transparent, so it can use a key. If false, adds a translucent color depending on //whether it's an alpha color type or not. -void generateTestImageRequiringColorType16(Image& image, LodePNGColorType colorType, unsigned bitDepth, bool key) -{ +void generateTestImageRequiringColorType16(Image& image, LodePNGColorType colorType, unsigned bitDepth, bool key) { image.colorType = colorType; image.bitDepth = bitDepth; unsigned w = 1; @@ -299,15 +274,12 @@ void generateTestImageRequiringColorType16(Image& image, LodePNGColorType colorT bool grey = colorType == LCT_GREY || colorType == LCT_GREY_ALPHA; bool alpha = colorType == LCT_RGBA || colorType == LCT_GREY_ALPHA; - if(colorType == LCT_PALETTE) - { + if(colorType == LCT_PALETTE) { w = 1u << bitDepth; h = 256; // ensure it'll really choose palette, not omit it due to small image size image.data.resize(w * h * 8); - for(size_t y = 0; y < h; y++) - { - for(size_t x = 0; x < w; x++) - { + for(size_t y = 0; y < h; y++) { + for(size_t x = 0; x < w; x++) { size_t i = y * w * 8 + x * 8; image.data[i + 0] = image.data[i + 1] = y; image.data[i + 2] = image.data[i + 3] = 255; @@ -315,9 +287,7 @@ void generateTestImageRequiringColorType16(Image& image, LodePNGColorType colorT image.data[i + 6] = image.data[i + 7] = (key && y == 0) ? 0 : 255; } } - } - else if(bitDepth == 16) - { + } else if(bitDepth == 16) { // one color suffices for this model. But add one more to support key. w = 2; image.data.resize(w * h * 8); @@ -330,9 +300,7 @@ void generateTestImageRequiringColorType16(Image& image, LodePNGColorType colorT image.data[10] = 40; image.data[11] = 50; image.data[12] = grey ? 40 : 140; image.data[13] = grey ? 50 : 150; image.data[14] = key ? 0 : 255; image.data[15] = key ? 0 : 255; - } - else if(grey) - { + } else if(grey) { w = 2; unsigned v = 255u / ((1u << bitDepth) - 1u); // value that forces at least this bitdepth image.data.resize(w * h * 8); @@ -345,16 +313,12 @@ void generateTestImageRequiringColorType16(Image& image, LodePNGColorType colorT image.data[10] = image.data[11] = 0; image.data[12] = image.data[13] = 0; image.data[14] = image.data[15] = key ? 0 : 255; - } - else - { + } else { // now it's RGB or RGBA with bitdepth 8 w = 257; // must have at least more than 256 colors so it won't use palette image.data.resize(w * h * 8); - for(size_t y = 0; y < h; y++) - { - for(size_t x = 0; x < w; x++) - { + for(size_t y = 0; y < h; y++) { + for(size_t x = 0; x < w; x++) { size_t i = y * w * 8 + x * 8; image.data[i + 0] = image.data[i + 1] = i / 2; image.data[i + 2] = image.data[i + 3] = i / 3; @@ -371,8 +335,7 @@ void generateTestImageRequiringColorType16(Image& image, LodePNGColorType colorT //Generate a 8-bit test image with minimal size that requires at minimum the given color type (bit depth, greyscaleness, ...). bitDepth max 8 here. //If key is true, makes it such that exactly one color is transparent, so it can use a key. If false, adds a translucent color depending on //whether it's an alpha color type or not. -void generateTestImageRequiringColorType8(Image& image, LodePNGColorType colorType, unsigned bitDepth, bool key) -{ +void generateTestImageRequiringColorType8(Image& image, LodePNGColorType colorType, unsigned bitDepth, bool key) { image.colorType = colorType; image.bitDepth = bitDepth; unsigned w = 1; @@ -381,15 +344,12 @@ void generateTestImageRequiringColorType8(Image& image, LodePNGColorType colorTy bool grey = colorType == LCT_GREY || colorType == LCT_GREY_ALPHA; bool alpha = colorType == LCT_RGBA || colorType == LCT_GREY_ALPHA; - if(colorType == LCT_PALETTE) - { + if(colorType == LCT_PALETTE) { w = 1u << bitDepth; h = 256; // ensure it'll really choose palette, not omit it due to small image size image.data.resize(w * h * 4); - for(size_t y = 0; y < h; y++) - { - for(size_t x = 0; x < w; x++) - { + for(size_t y = 0; y < h; y++) { + for(size_t x = 0; x < w; x++) { size_t i = y * w * 4 + x * 4; image.data[i + 0] = x; image.data[i + 1] = 255; @@ -397,9 +357,7 @@ void generateTestImageRequiringColorType8(Image& image, LodePNGColorType colorTy image.data[i + 3] = (key && x == 0) ? 0 : 255; } } - } - else if(grey) - { + } else if(grey) { w = 2; unsigned v = 255u / ((1u << bitDepth) - 1u); // value that forces at least this bitdepth image.data.resize(w * h * 4); @@ -412,16 +370,12 @@ void generateTestImageRequiringColorType8(Image& image, LodePNGColorType colorTy image.data[5] = 0; image.data[6] = 0; image.data[7] = key ? 0 : 255; - } - else - { + } else { // now it's RGB or RGBA with bitdepth 8 w = 257; // must have at least more than 256 colors so it won't use palette image.data.resize(w * h * 4); - for(size_t y = 0; y < h; y++) - { - for(size_t x = 0; x < w; x++) - { + for(size_t y = 0; y < h; y++) { + for(size_t x = 0; x < w; x++) { size_t i = y * w * 4 + x * 4; image.data[i + 0] = i / 2; image.data[i + 1] = i / 3; @@ -436,23 +390,18 @@ void generateTestImageRequiringColorType8(Image& image, LodePNGColorType colorTy } //Check that the decoded PNG pixels are the same as the pixels in the image -void assertPixels(Image& image, const unsigned char* decoded, const std::string& message) -{ - for(size_t i = 0; i < image.data.size(); i++) - { +void assertPixels(Image& image, const unsigned char* decoded, const std::string& message) { + for(size_t i = 0; i < image.data.size(); i++) { int byte_expected = image.data[i]; int byte_actual = decoded[i]; //last byte is special due to possible random padding bits which need not to be equal - if(i == image.data.size() - 1) - { + if(i == image.data.size() - 1) { size_t numbits = getNumColorChannels(image.colorType) * image.bitDepth * image.width * image.height; size_t padding = 8u - (numbits - 8u * (numbits / 8u)); - if(padding != 8u) - { + if(padding != 8u) { //set all padding bits of both to 0 - for(size_t j = 0; j < padding; j++) - { + for(size_t j = 0; j < padding; j++) { byte_expected = (byte_expected & (~(1 << j))) % 256; byte_actual = (byte_actual & (~(1 << j))) % 256; } @@ -464,16 +413,14 @@ void assertPixels(Image& image, const unsigned char* decoded, const std::string& } //Test LodePNG encoding and decoding the encoded result, using the C interface -void doCodecTestC(Image& image) -{ +void doCodecTestC(Image& image) { unsigned char* encoded = 0; size_t encoded_size = 0; unsigned char* decoded = 0; unsigned decoded_w; unsigned decoded_h; - struct OnExitScope - { + struct OnExitScope { unsigned char** a; unsigned char** b; OnExitScope(unsigned char** ca, unsigned char** cb) : a(ca), b(cb) {} @@ -501,8 +448,7 @@ void doCodecTestC(Image& image) } //Test LodePNG encoding and decoding the encoded result, using the C++ interface -void doCodecTestCPP(Image& image) -{ +void doCodecTestCPP(Image& image) { std::vector encoded; std::vector decoded; unsigned decoded_w; @@ -551,23 +497,20 @@ void doCodecTestWithEncState(Image& image, lodepng::State& state) { //Test LodePNG encoding and decoding the encoded result, using the C++ interface -void doCodecTestUncompressed(Image& image) -{ +void doCodecTestUncompressed(Image& image) { lodepng::State state; state.encoder.zlibsettings.btype = 0; doCodecTestWithEncState(image, state); } -void doCodecTestNoLZ77(Image& image) -{ +void doCodecTestNoLZ77(Image& image) { lodepng::State state; state.encoder.zlibsettings.use_lz77 = 0; doCodecTestWithEncState(image, state); } //Test LodePNG encoding and decoding the encoded result, using the C++ interface, with interlace -void doCodecTestInterlaced(Image& image) -{ +void doCodecTestInterlaced(Image& image) { std::vector encoded; std::vector decoded; unsigned decoded_w; @@ -598,8 +541,7 @@ void doCodecTestInterlaced(Image& image) } //Test LodePNG encoding and decoding the encoded result -void doCodecTest(Image& image) -{ +void doCodecTest(Image& image) { doCodecTestC(image); doCodecTestCPP(image); doCodecTestInterlaced(image); @@ -609,27 +551,23 @@ void doCodecTest(Image& image) //Test LodePNG encoding and decoding using some image generated with the given parameters -void codecTest(unsigned width, unsigned height, LodePNGColorType colorType = LCT_RGBA, unsigned bitDepth = 8) -{ +void codecTest(unsigned width, unsigned height, LodePNGColorType colorType = LCT_RGBA, unsigned bitDepth = 8) { std::cout << "codec test " << width << " " << height << std::endl; Image image; generateTestImage(image, width, height, colorType, bitDepth); doCodecTest(image); } -std::string removeSpaces(const std::string& s) -{ +std::string removeSpaces(const std::string& s) { std::string result; for(size_t i = 0; i < s.size(); i++) if(s[i] != ' ') result += s[i]; return result; } -void bitStringToBytes(std::vector& bytes, const std::string& bits_) -{ +void bitStringToBytes(std::vector& bytes, const std::string& bits_) { std::string bits = removeSpaces(bits_); bytes.resize((bits.size()) + 7 / 8); - for(size_t i = 0; i < bits.size(); i++) - { + for(size_t i = 0; i < bits.size(); i++) { size_t j = i / 8; size_t k = i % 8; char c = bits[i]; @@ -644,8 +582,7 @@ not supported by this function. Pixel values given using bits in an std::string of 0's and 1's. */ void colorConvertTest(const std::string& bits_in, LodePNGColorType colorType_in, unsigned bitDepth_in, - const std::string& bits_out, LodePNGColorType colorType_out, unsigned bitDepth_out) -{ + const std::string& bits_out, LodePNGColorType colorType_out, unsigned bitDepth_out) { std::cout << "color convert test " << bits_in << " - " << bits_out << std::endl; std::vector expected, actual, image; @@ -663,8 +600,7 @@ void colorConvertTest(const std::string& bits_in, LodePNGColorType colorType_in, ASSERT_NO_PNG_ERROR_MSG(error, "convert error"); - for(size_t i = 0; i < expected.size(); i++) - { + for(size_t i = 0; i < expected.size(); i++) { assertEquals((int)expected[i], (int)actual[i], "byte " + valtostr(i)); } @@ -672,8 +608,7 @@ void colorConvertTest(const std::string& bits_in, LodePNGColorType colorType_in, lodepng_color_mode_cleanup(&mode_out); } -void testOtherPattern1() -{ +void testOtherPattern1() { std::cout << "codec other pattern 1" << std::endl; Image image1; @@ -685,8 +620,7 @@ void testOtherPattern1() image1.bitDepth = 8; image1.data.resize(w * h * 4u); for(size_t y = 0; y < h; y++) - for(size_t x = 0; x < w; x++) - { + for(size_t x = 0; x < w; x++) { //pattern 1 image1.data[4u * w * y + 4u * x + 0u] = (unsigned char)(127 * (1 + std::sin(( x * x + y * y) / (w * h / 8.0)))); image1.data[4u * w * y + 4u * x + 1u] = (unsigned char)(127 * (1 + std::sin(((w - x - 1) * (w - x - 1) + y * y) / (w * h / 8.0)))); @@ -697,8 +631,7 @@ void testOtherPattern1() doCodecTest(image1); } -void testOtherPattern2() -{ +void testOtherPattern2() { std::cout << "codec other pattern 2" << std::endl; Image image1; @@ -710,8 +643,7 @@ void testOtherPattern2() image1.bitDepth = 8; image1.data.resize(w * h * 4u); for(size_t y = 0; y < h; y++) - for(size_t x = 0; x < w; x++) - { + for(size_t x = 0; x < w; x++) { image1.data[4u * w * y + 4u * x + 0u] = 255 * !(x & y); image1.data[4u * w * y + 4u * x + 1u] = x ^ y; image1.data[4u * w * y + 4u * x + 2u] = x | y; @@ -721,8 +653,7 @@ void testOtherPattern2() doCodecTest(image1); } -void testSinglePixel(int r, int g, int b, int a) -{ +void testSinglePixel(int r, int g, int b, int a) { std::cout << "codec single pixel " << r << " " << g << " " << b << " " << a << std::endl; Image pixel; pixel.width = 1; @@ -738,8 +669,7 @@ void testSinglePixel(int r, int g, int b, int a) doCodecTest(pixel); } -void testColor(int r, int g, int b, int a) -{ +void testColor(int r, int g, int b, int a) { std::cout << "codec test color " << r << " " << g << " " << b << " " << a << std::endl; Image image; image.width = 20; @@ -748,8 +678,7 @@ void testColor(int r, int g, int b, int a) image.bitDepth = 8; image.data.resize(20 * 20 * 4); for(size_t y = 0; y < 20; y++) - for(size_t x = 0; x < 20; x++) - { + for(size_t x = 0; x < 20; x++) { image.data[20 * 4 * y + 4 * x + 0] = r; image.data[20 * 4 * y + 4 * x + 0] = g; image.data[20 * 4 * y + 4 * x + 0] = b; @@ -784,8 +713,7 @@ void testColor(int r, int g, int b, int a) } // Tests combinations of various colors in different orders -void testFewColors() -{ +void testFewColors() { std::cout << "codec test few colors " << std::endl; Image image; image.width = 20; @@ -803,14 +731,11 @@ void testFewColors() for(size_t i = 0; i < colors.size(); i += 4) for(size_t j = 0; j < colors.size(); j += 4) for(size_t k = 0; k < colors.size(); k += 4) - for(size_t l = 0; l < colors.size(); l += 4) - { + for(size_t l = 0; l < colors.size(); l += 4) { //std::cout << (i/4) << " " << (j/4) << " " << (k/4) << " " << (l/4) << std::endl; - for(size_t c = 0; c < 4; c++) - { + for(size_t c = 0; c < 4; c++) { for(unsigned y = 0; y < image.height; y++) - for(unsigned x = 0; x < image.width; x++) - { + for(unsigned x = 0; x < image.width; x++) { image.data[y * image.width * 4 + x * 4 + c] = (x ^ y) ? colors[i + c] : colors[j + c]; } image.data[c] = colors[k + c]; @@ -820,8 +745,7 @@ void testFewColors() } } -void testSize(unsigned w, unsigned h) -{ +void testSize(unsigned w, unsigned h) { std::cout << "codec test size " << w << " " << h << std::endl; Image image; image.width = w; @@ -830,8 +754,7 @@ void testSize(unsigned w, unsigned h) image.bitDepth = 8; image.data.resize(w * h * 4); for(size_t y = 0; y < h; y++) - for(size_t x = 0; x < w; x++) - { + for(size_t x = 0; x < w; x++) { image.data[w * 4 * y + 4 * x + 0] = x % 256; image.data[w * 4 * y + 4 * x + 0] = y % 256; image.data[w * 4 * y + 4 * x + 0] = 255; @@ -841,8 +764,7 @@ void testSize(unsigned w, unsigned h) doCodecTest(image); } -void testPNGCodec() -{ +void testPNGCodec() { codecTest(1, 1); codecTest(2, 2); codecTest(1, 1, LCT_GREY, 1); @@ -882,15 +804,13 @@ void testPNGCodec() // This is mainly to test the Adam7 interlacing for(unsigned h = 1; h < 12; h++) - for(unsigned w = 1; w < 12; w++) - { + for(unsigned w = 1; w < 12; w++) { testSize(w, h); } } //Tests some specific color conversions with specific color bit combinations -void testColorConvert() -{ +void testColorConvert() { //test color conversions to RGBA8 colorConvertTest("1", LCT_GREY, 1, "11111111 11111111 11111111 11111111", LCT_RGBA, 8); colorConvertTest("10", LCT_GREY, 2, "10101010 10101010 10101010 11111111", LCT_RGBA, 8); @@ -940,32 +860,14 @@ void testColorConvert() //This tests color conversions from any color model to any color model, with any bit depth //But it tests only with colors black and white, because that are the only colors every single model supports -void testColorConvert2() -{ +void testColorConvert2() { std::cout << "testColorConvert2" << std::endl; - struct Combo - { + struct Combo { LodePNGColorType colortype; unsigned bitdepth; }; - Combo combos[15] = - { - { LCT_GREY, 1}, - { LCT_GREY, 2}, - { LCT_GREY, 4}, - { LCT_GREY, 8}, - { LCT_GREY, 16}, - { LCT_RGB, 8}, - { LCT_RGB, 16}, - { LCT_PALETTE, 1}, - { LCT_PALETTE, 2}, - { LCT_PALETTE, 4}, - { LCT_PALETTE, 8}, - { LCT_GREY_ALPHA, 8}, - { LCT_GREY_ALPHA, 16}, - { LCT_RGBA, 8}, - { LCT_RGBA, 16}, + Combo combos[15] = { { LCT_GREY, 1}, { LCT_GREY, 2}, { LCT_GREY, 4}, { LCT_GREY, 8}, { LCT_GREY, 16}, { LCT_RGB, 8}, { LCT_RGB, 16}, { LCT_PALETTE, 1}, { LCT_PALETTE, 2}, { LCT_PALETTE, 4}, { LCT_PALETTE, 8}, { LCT_GREY_ALPHA, 8}, { LCT_GREY_ALPHA, 16}, { LCT_RGBA, 8}, { LCT_RGBA, 16}, }; lodepng::State state; @@ -974,20 +876,17 @@ void testColorConvert2() LodePNGColorMode mode_8; lodepng_color_mode_init(&mode_8); - for(size_t i = 0; i < 256; i++) - { + for(size_t i = 0; i < 256; i++) { size_t j = i == 1 ? 255 : i; lodepng_palette_add(&mode_in, j, j, j, 255); lodepng_palette_add(&mode_out, j, j, j, 255); } - for(size_t i = 0; i < 15; i++) - { + for(size_t i = 0; i < 15; i++) { mode_in.colortype = combos[i].colortype; mode_in.bitdepth = combos[i].bitdepth; - for(size_t j = 0; j < 15; j++) - { + for(size_t j = 0; j < 15; j++) { mode_out.colortype = combos[i].colortype; mode_out.bitdepth = combos[i].bitdepth; @@ -1006,20 +905,16 @@ void testColorConvert2() if(!error) error |= lodepng_convert(out, in, &mode_out, &mode_in, 3, 3); //Test input to output type if(!error) error |= lodepng_convert(eight2, out, &mode_8, &mode_out, 3, 3); - if(!error) - { - for(size_t k = 0; k < 36; k++) - { - if(eight[k] != eight2[k]) - { + if(!error) { + for(size_t k = 0; k < 36; k++) { + if(eight[k] != eight2[k]) { error = 99999; break; } } } - if(error) - { + if(error) { std::cout << "Error " << error << " i: " << i << " j: " << j << " colortype i: " << combos[i].colortype << " bitdepth i: " << combos[i].bitdepth @@ -1034,8 +929,7 @@ void testColorConvert2() } //if compressible is true, the test will also assert that the compressed string is smaller -void testCompressStringZlib(const std::string& text, bool compressible) -{ +void testCompressStringZlib(const std::string& text, bool compressible) { if(text.size() < 500) std::cout << "compress test with text: " << text << std::endl; else std::cout << "compress test with text length: " << text.size() << std::endl; @@ -1061,8 +955,7 @@ void testCompressStringZlib(const std::string& text, bool compressible) free(out2); } -void testCompressZlib() -{ +void testCompressZlib() { testCompressStringZlib("", false); testCompressStringZlib("a", false); testCompressStringZlib("aa", false); @@ -1081,8 +974,7 @@ void testCompressZlib() testCompressStringZlib("lodepng_zlib_decompress(&out2, &outsize2, out, outsize, &lodepng_default_decompress_settings);", true); } -void testDiskCompressZlib(const std::string& filename) -{ +void testDiskCompressZlib(const std::string& filename) { std::cout << "testDiskCompressZlib: File " << filename << std::endl; std::vector buffer; @@ -1092,8 +984,7 @@ void testDiskCompressZlib(const std::string& filename) testCompressStringZlib(f, false); } -void testDiskPNG(const std::string& filename) -{ +void testDiskPNG(const std::string& filename) { std::cout << "testDiskPNG: File " << filename << std::endl; Image image; @@ -1105,8 +996,7 @@ void testDiskPNG(const std::string& filename) doCodecTest(image); } -std::vector strtovector(const std::string& numbers) -{ +std::vector strtovector(const std::string& numbers) { std::vector result; std::stringstream ss(numbers); unsigned i; @@ -1114,8 +1004,7 @@ std::vector strtovector(const std::string& numbers) return result; } -void doTestHuffmanCodeLengths(const std::string& expectedstr, const std::string& counts, size_t bitlength) -{ +void doTestHuffmanCodeLengths(const std::string& expectedstr, const std::string& counts, size_t bitlength) { std::vector expected = strtovector(expectedstr); std::vector count = strtovector(counts); std::cout << "doTestHuffmanCodeLengths: " << counts << std::endl; @@ -1123,19 +1012,16 @@ void doTestHuffmanCodeLengths(const std::string& expectedstr, const std::string& unsigned error = lodepng_huffman_code_lengths(&result[0], &count[0], count.size(), bitlength); ASSERT_NO_PNG_ERROR_MSG(error, "errorcode"); std::stringstream ss1, ss2; - for(size_t i = 0; i < count.size(); i++) - { + for(size_t i = 0; i < count.size(); i++) { ss1 << expected[i] << " "; ss2 << result[i] << " "; } assertEquals(ss1.str(), ss2.str(), "value"); } -void testHuffmanCodeLengths() -{ +void testHuffmanCodeLengths() { bool atleasttwo = true; //LodePNG generates at least two, instead of at least one, symbol - if(atleasttwo) - { + if(atleasttwo) { doTestHuffmanCodeLengths("1 1", "0 0", 16); doTestHuffmanCodeLengths("1 1 0", "0 0 0", 16); doTestHuffmanCodeLengths("1 1", "1 0", 16); @@ -1144,9 +1030,7 @@ void testHuffmanCodeLengths() doTestHuffmanCodeLengths("1 1 0 0 0 0 0 0 0", "0 1 0 0 0 0 0 0 0", 16); doTestHuffmanCodeLengths("1 0 0 0 0 0 0 0 1", "0 0 0 0 0 0 0 0 1", 16); doTestHuffmanCodeLengths("0 0 0 0 0 0 0 1 1", "0 0 0 0 0 0 0 1 1", 16); - } - else - { + } else { doTestHuffmanCodeLengths("1 0", "0 0", 16); doTestHuffmanCodeLengths("1 0 0", "0 0 0", 16); doTestHuffmanCodeLengths("1 0", "1 0", 16); @@ -1167,12 +1051,10 @@ void testHuffmanCodeLengths() Create a PNG image with all known chunks (except only one of tEXt or zTXt) plus unknown chunks, and a palette. */ -void createComplexPNG(std::vector& png) -{ +void createComplexPNG(std::vector& png) { unsigned w = 16, h = 17; std::vector image(w * h); - for(size_t i = 0; i < w * h; i++) - { + for(size_t i = 0; i < w * h; i++) { image[i] = i % 256; } @@ -1185,8 +1067,7 @@ void createComplexPNG(std::vector& png) state.encoder.auto_convert = false; state.encoder.text_compression = 1; state.encoder.add_id = 1; - for(size_t i = 0; i < 256; i++) - { + for(size_t i = 0; i < 256; i++) { lodepng_palette_add(&info.color, i, i, i, i); lodepng_palette_add(&state.info_raw, i, i, i, i); } @@ -1222,13 +1103,11 @@ void createComplexPNG(std::vector& png) ASSERT_NO_PNG_ERROR(error); } -std::string extractChunkNames(const std::vector& png) -{ +std::string extractChunkNames(const std::vector& png) { const unsigned char* chunk = &png[8]; char name[5]; std::string result = ""; - for(;;) - { + for(;;) { lodepng_chunk_type(name, chunk); result += (std::string(" ") + name); if(std::string(name) == "IEND") break; @@ -1238,14 +1117,12 @@ std::string extractChunkNames(const std::vector& png) return result; } -void testComplexPNG() -{ +void testComplexPNG() { std::cout << "testComplexPNG" << std::endl; std::vector png; createComplexPNG(png); - - { + { lodepng::State state; LodePNGInfo& info = state.info_png; unsigned w, h; @@ -1314,8 +1191,7 @@ void testComplexPNG() } // Tests lodepng_inspect_chunk, and also lodepng_chunk_find to find the chunk to inspect -void testInspectChunk() -{ +void testInspectChunk() { std::cout << "testInspectChunk" << std::endl; std::vector png; @@ -1348,8 +1224,7 @@ void testInspectChunk() } //test that, by default, it chooses filter type zero for all scanlines if the image has a palette -void testPaletteFilterTypesZero() -{ +void testPaletteFilterTypesZero() { std::cout << "testPaletteFilterTypesZero" << std::endl; std::vector png; @@ -1363,8 +1238,7 @@ void testPaletteFilterTypesZero() } //tests that there are no crashes with auto color chooser in case of palettes with translucency etc... -void testPaletteToPaletteConvert() -{ +void testPaletteToPaletteConvert() { std::cout << "testPaletteToPaletteConvert" << std::endl; unsigned error; unsigned w = 16, h = 16; @@ -1375,13 +1249,11 @@ void testPaletteToPaletteConvert() info.color.colortype = state.info_raw.colortype = LCT_PALETTE; info.color.bitdepth = state.info_raw.bitdepth = 8; ASSERT_EQUALS(true, state.encoder.auto_convert); - for(size_t i = 0; i < 256; i++) - { + for(size_t i = 0; i < 256; i++) { lodepng_palette_add(&info.color, i, i, i, i); } std::vector png; - for(size_t i = 0; i < 256; i++) - { + for(size_t i = 0; i < 256; i++) { lodepng_palette_add(&state.info_raw, i, i, i, i); } error = lodepng::encode(png, &image[0], w, h, state); @@ -1390,8 +1262,7 @@ void testPaletteToPaletteConvert() //for this test, you have to choose palette colors that cause LodePNG to actually use a palette, //so don't use all greyscale colors for example -void doRGBAToPaletteTest(unsigned char* palette, size_t size, LodePNGColorType expectedType = LCT_PALETTE) -{ +void doRGBAToPaletteTest(unsigned char* palette, size_t size, LodePNGColorType expectedType = LCT_PALETTE) { std::cout << "testRGBToPaletteConvert " << size << std::endl; unsigned error; unsigned w = size, h = 257 /*LodePNG encodes no palette if image is too small*/; @@ -1408,16 +1279,14 @@ void doRGBAToPaletteTest(unsigned char* palette, size_t size, LodePNGColorType e for(size_t i = 0; i < image.size(); i++) ASSERT_EQUALS(image[i], image2[i]); ASSERT_EQUALS(expectedType, state.info_png.color.colortype); - if(expectedType == LCT_PALETTE) - { + if(expectedType == LCT_PALETTE) { ASSERT_EQUALS(size, state.info_png.color.palettesize); for(size_t i = 0; i < size * 4; i++) ASSERT_EQUALS(state.info_png.color.palette[i], image[i]); } } -void testRGBToPaletteConvert() -{ +void testRGBToPaletteConvert() { unsigned char palette1[4] = {1,2,3,4}; doRGBAToPaletteTest(palette1, 1); unsigned char palette2[8] = {1,2,3,4, 5,6,7,8}; @@ -1426,8 +1295,7 @@ void testRGBToPaletteConvert() doRGBAToPaletteTest(palette3, 3); std::vector palette; - for(int i = 0; i < 256; i++) - { + for(int i = 0; i < 256; i++) { palette.push_back(i); palette.push_back(5); palette.push_back(6); @@ -1441,14 +1309,12 @@ void testRGBToPaletteConvert() doRGBAToPaletteTest(&palette[0], 257, LCT_RGBA); } -void testColorKeyConvert() -{ +void testColorKeyConvert() { std::cout << "testColorKeyConvert" << std::endl; unsigned error; unsigned w = 32, h = 32; std::vector image(w * h * 4); - for(size_t i = 0; i < w * h; i++) - { + for(size_t i = 0; i < w * h; i++) { image[i * 4 + 0] = i % 256; image[i * 4 + 1] = i / 256; image[i * 4 + 2] = 0; @@ -1469,20 +1335,17 @@ void testColorKeyConvert() ASSERT_EQUALS(0, state.info_png.color.key_g); ASSERT_EQUALS(0, state.info_png.color.key_b); ASSERT_EQUALS(image.size(), image2.size()); - for(size_t i = 0; i < image.size(); i++) - { + for(size_t i = 0; i < image.size(); i++) { ASSERT_EQUALS(image[i], image2[i]); } } -void testNoAutoConvert() -{ +void testNoAutoConvert() { std::cout << "testNoAutoConvert" << std::endl; unsigned error; unsigned w = 32, h = 32; std::vector image(w * h * 4); - for(size_t i = 0; i < w * h; i++) - { + for(size_t i = 0; i < w * h; i++) { image[i * 4 + 0] = (i % 2) ? 255 : 0; image[i * 4 + 1] = (i % 2) ? 255 : 0; image[i * 4 + 2] = (i % 2) ? 255 : 0; @@ -1505,22 +1368,19 @@ void testNoAutoConvert() ASSERT_EQUALS(LCT_RGBA, state2.info_png.color.colortype); ASSERT_EQUALS(8, state2.info_png.color.bitdepth); ASSERT_EQUALS(image.size(), image2.size()); - for(size_t i = 0; i < image.size(); i++) - { + for(size_t i = 0; i < image.size(); i++) { ASSERT_EQUALS(image[i], image2[i]); } } -unsigned char flipBit(unsigned char c, int bitpos) -{ +unsigned char flipBit(unsigned char c, int bitpos) { return c ^ (1 << bitpos); } //Test various broken inputs. Returned errors are not checked, what is tested is //that is doesn't crash, and, when run with valgrind, no memory warnings are //given. -void testFuzzing() -{ +void testFuzzing() { std::cout << "testFuzzing" << std::endl; std::vector png; createComplexPNG(png); @@ -1531,15 +1391,13 @@ void testFuzzing() lodepng::State state; state.decoder.ignore_crc = 1; state.decoder.zlibsettings.ignore_adler32 = 1; - for(size_t i = 0; i < png.size(); i++) - { + for(size_t i = 0; i < png.size(); i++) { result.clear(); broken[i] = ~png[i]; errors[lodepng::decode(result, w, h, state, broken)]++; broken[i] = 0; errors[lodepng::decode(result, w, h, state, broken)]++; - for(int j = 0; j < 8; j++) - { + for(int j = 0; j < 8; j++) { broken[i] = flipBit(png[i], j); errors[lodepng::decode(result, w, h, state, broken)]++; } @@ -1549,23 +1407,20 @@ void testFuzzing() } std::cout << "testFuzzing shrinking" << std::endl; broken = png; - while(broken.size() > 0) - { + while(broken.size() > 0) { broken.resize(broken.size() - 1); errors[lodepng::decode(result, w, h, state, broken)]++; } //For fun, print the number of each error std::cout << "Fuzzing error code counts: "; - for(std::map::iterator it = errors.begin(); it != errors.end(); ++it) - { + for(std::map::iterator it = errors.begin(); it != errors.end(); ++it) { std::cout << it->first << ":" << it->second << ", "; } std::cout << std::endl; } -void testCustomZlibCompress() -{ +void testCustomZlibCompress() { std::cout << "testCustomZlibCompress" << std::endl; Image image; generateTestImage(image, 5, 5, LCT_RGBA, 8); @@ -1576,8 +1431,7 @@ void testCustomZlibCompress() struct TestFun { static unsigned custom_zlib(unsigned char**, size_t*, const unsigned char*, size_t, - const LodePNGCompressSettings* settings) - { + const LodePNGCompressSettings* settings) { ASSERT_EQUALS(5, *(int*)(settings->custom_context)); return 5555; //return a custom error code to prove this function was called } @@ -1593,8 +1447,7 @@ void testCustomZlibCompress() ASSERT_EQUALS(5555, error); } -void testCustomZlibCompress2() -{ +void testCustomZlibCompress2() { std::cout << "testCustomZlibCompress2" << std::endl; Image image; generateTestImage(image, 5, 5, LCT_RGBA, 8); @@ -1618,8 +1471,7 @@ void testCustomZlibCompress2() ASSERT_EQUALS(5, h); } -void testCustomDeflate() -{ +void testCustomDeflate() { std::cout << "testCustomDeflate" << std::endl; Image image; generateTestImage(image, 5, 5, LCT_RGBA, 8); @@ -1630,8 +1482,7 @@ void testCustomDeflate() struct TestFun { static unsigned custom_deflate(unsigned char**, size_t*, const unsigned char*, size_t, - const LodePNGCompressSettings* settings) - { + const LodePNGCompressSettings* settings) { ASSERT_EQUALS(5, *(int*)(settings->custom_context)); return 5555; //return a custom error code to prove this function was called } @@ -1647,8 +1498,7 @@ void testCustomDeflate() ASSERT_EQUALS(5555, error); } -void testCustomZlibDecompress() -{ +void testCustomZlibDecompress() { std::cout << "testCustomZlibDecompress" << std::endl; Image image; generateTestImage(image, 5, 5, LCT_RGBA, 8); @@ -1667,8 +1517,7 @@ void testCustomZlibDecompress() struct TestFun { static unsigned custom_zlib(unsigned char**, size_t*, const unsigned char*, size_t, - const LodePNGDecompressSettings* settings) - { + const LodePNGDecompressSettings* settings) { ASSERT_EQUALS(5, *(int*)(settings->custom_context)); return 5555; //return a custom error code to prove this function was called } @@ -1684,8 +1533,7 @@ void testCustomZlibDecompress() ASSERT_EQUALS(5555, error); } -void testCustomInflate() -{ +void testCustomInflate() { std::cout << "testCustomInflate" << std::endl; Image image; generateTestImage(image, 5, 5, LCT_RGBA, 8); @@ -1704,8 +1552,7 @@ void testCustomInflate() struct TestFun { static unsigned custom_inflate(unsigned char**, size_t*, const unsigned char*, size_t, - const LodePNGDecompressSettings* settings) - { + const LodePNGDecompressSettings* settings) { ASSERT_EQUALS(5, *(int*)(settings->custom_context)); return 5555; //return a custom error code to prove this function was called } @@ -1722,8 +1569,7 @@ void testCustomInflate() } void doPngSuiteTinyTest(const std::string& base64, unsigned w, unsigned h, - unsigned char r, unsigned char g, unsigned char b, unsigned char a) -{ + unsigned char r, unsigned char g, unsigned char b, unsigned char a) { lodepng::State state; std::vector png; fromBase64(png, base64); @@ -1750,8 +1596,7 @@ void doPngSuiteTinyTest(const std::string& base64, unsigned w, unsigned h, /*checks that both png suite images have the exact same pixel content, e.g. to check that it decodes an interlaced and non-interlaced corresponding png suite image equally*/ -void doPngSuiteEqualTest(const std::string& base64a, const std::string& base64b) -{ +void doPngSuiteEqualTest(const std::string& base64a, const std::string& base64b) { lodepng::State state; std::vector pnga, pngb; fromBase64(pnga, base64a); @@ -1764,18 +1609,15 @@ void doPngSuiteEqualTest(const std::string& base64a, const std::string& base64b) ASSERT_EQUALS(ha, hb); size_t size = wa * ha * 4; - for(size_t i = 0; i < size; i++) - { - if(imagea[i] != imageb[i]) - { + for(size_t i = 0; i < size; i++) { + if(imagea[i] != imageb[i]) { std::cout << "x: " << ((i / 4) % wa) << " y: " << ((i / 4) / wa) << " c: " << i % 4 << std::endl; ASSERT_EQUALS((int)imagea[i], (int)imageb[i]); } } } -void testPngSuiteTiny() -{ +void testPngSuiteTiny() { std::cout << "testPngSuiteTiny" << std::endl; doPngSuiteTinyTest("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAFS3GZcAAAABGdBTUEAAYagMeiWXwAAAANzQklU" "BAQEd/i1owAAAANQTFRFAAD/injSVwAAAApJREFUeJxjYAAAAAIAAUivpHEAAAAASUVORK5CYII=", @@ -1834,8 +1676,7 @@ void testPngSuiteTiny() "//4AAAAASUVORK5CYII="); } -void testChunkUtil() -{ +void testChunkUtil() { std::cout << "testChunkUtil" << std::endl; std::vector png; createComplexPNG(png); @@ -1865,8 +1706,7 @@ void testChunkUtil() //Test that when decoding to 16-bit per channel, it always uses big endian consistently. //It should always output big endian, the convention used inside of PNG, even though x86 CPU's are little endian. -void test16bitColorEndianness() -{ +void test16bitColorEndianness() { std::cout << "test16bitColorEndianness" << std::endl; //basn0g16.png from the PNG test suite @@ -2013,16 +1853,14 @@ void testEncoderErrors() { ASSERT_EQUALS(61, lodepng::encode(png, &image.data[0], w, h, state)); } -void addColor(std::vector& colors, unsigned char r, unsigned char g, unsigned char b, unsigned char a) -{ +void addColor(std::vector& colors, unsigned char r, unsigned char g, unsigned char b, unsigned char a) { colors.push_back(r); colors.push_back(g); colors.push_back(b); colors.push_back(a); } -void addColor16(std::vector& colors, unsigned short r, unsigned short g, unsigned short b, unsigned short a) -{ +void addColor16(std::vector& colors, unsigned short r, unsigned short g, unsigned short b, unsigned short a) { colors.push_back(r & 255); colors.push_back((r >> 8) & 255); colors.push_back(g & 255); @@ -2035,8 +1873,7 @@ void addColor16(std::vector& colors, unsigned short r, unsigned s // colors is in RGBA, inbitdepth must be 8 or 16, the amount of bits per channel. // colortype and bitdepth are the expected values. insize is amount of pixels. So the amount of bytes is insize * 4 * (inbitdepth / 8) -void testAutoColorModel(const std::vector& colors, unsigned inbitdepth, LodePNGColorType colortype, unsigned bitdepth, bool key) -{ +void testAutoColorModel(const std::vector& colors, unsigned inbitdepth, LodePNGColorType colortype, unsigned bitdepth, bool key) { std::cout << "testAutoColorModel " << inbitdepth << " " << colortype << " " << bitdepth << " " << key << std::endl; size_t innum = colors.size() / 4 * inbitdepth / 8; size_t num = innum < 65536 ? 65536 : innum; // Make image bigger so the convert doesn't avoid palette due to small image. @@ -2061,8 +1898,7 @@ void testAutoColorModel(const std::vector& colors, unsigned inbit else { for(size_t i = 0; i < colors.size() / 2; i++) ASSERT_EQUALS(colors[i * 2], decoded[i]); } } -void testAutoColorModels() -{ +void testAutoColorModels() { // 1-bit grey std::vector grey1; for(size_t i = 0; i < 2; i++) addColor(grey1, i * 255, i * 255, i * 255, 255); @@ -2280,17 +2116,14 @@ void testPaletteToPaletteDecode2() { free(image2); } -void assertColorProfileDataEqual(const lodepng::State& a, const lodepng::State& b) -{ +void assertColorProfileDataEqual(const lodepng::State& a, const lodepng::State& b) { ASSERT_EQUALS(a.info_png.gama_defined, b.info_png.gama_defined); - if(a.info_png.gama_defined) - { + if(a.info_png.gama_defined) { ASSERT_EQUALS(a.info_png.gama_gamma, b.info_png.gama_gamma); } ASSERT_EQUALS(a.info_png.chrm_defined, b.info_png.chrm_defined); - if(a.info_png.chrm_defined) - { + if(a.info_png.chrm_defined) { ASSERT_EQUALS(a.info_png.chrm_white_x, b.info_png.chrm_white_x); ASSERT_EQUALS(a.info_png.chrm_white_y, b.info_png.chrm_white_y); ASSERT_EQUALS(a.info_png.chrm_red_x, b.info_png.chrm_red_x); @@ -2302,14 +2135,12 @@ void assertColorProfileDataEqual(const lodepng::State& a, const lodepng::State& } ASSERT_EQUALS(a.info_png.srgb_defined, b.info_png.srgb_defined); - if(a.info_png.srgb_defined) - { + if(a.info_png.srgb_defined) { ASSERT_EQUALS(a.info_png.srgb_intent, b.info_png.srgb_intent); } ASSERT_EQUALS(a.info_png.iccp_defined, b.info_png.iccp_defined); - if(a.info_png.iccp_defined) - { + if(a.info_png.iccp_defined) { //ASSERT_EQUALS(std::string(a.info_png.iccp_name), std::string(b.info_png.iccp_name)); ASSERT_EQUALS(a.info_png.iccp_profile_size, b.info_png.iccp_profile_size); for(size_t i = 0; i < a.info_png.iccp_profile_size; ++i) { @@ -2319,11 +2150,9 @@ void assertColorProfileDataEqual(const lodepng::State& a, const lodepng::State& } // Tests the gAMA, cHRM, sRGB, iCCP chunks -void testColorProfile() -{ +void testColorProfile() { std::cout << "testColorProfile" << std::endl; - - { + { unsigned error; unsigned w = 32, h = 32; std::vector image(w * h * 4); @@ -2354,8 +2183,7 @@ void testColorProfile() ASSERT_EQUALS(image.size(), image2.size()); for(size_t i = 0; i < image.size(); i++) ASSERT_EQUALS(image[i], image2[i]); } - - { + { unsigned error; unsigned w = 32, h = 32; std::vector image(w * h * 4); @@ -2377,8 +2205,7 @@ void testColorProfile() ASSERT_EQUALS(image.size(), image2.size()); for(size_t i = 0; i < image.size(); i++) ASSERT_EQUALS(image[i], image2[i]); } - - { + { unsigned error; unsigned w = 32, h = 32; std::vector image(w * h * 4); @@ -2408,8 +2235,7 @@ void testColorProfile() unsigned error; unsigned w = 32, h = 32; std::vector image(w * h * 4); - for(size_t i = 0; i + 4 < image.size(); i += 4) - { + for(size_t i = 0; i + 4 < image.size(); i += 4) { image[i] = image[i + 1] = image[i + 2] = image[i + 3] = i; } std::vector png; @@ -2442,8 +2268,7 @@ void testBkgdChunk(unsigned r, unsigned g, unsigned b, unsigned w, unsigned h, const LodePNGColorMode& mode_raw, const LodePNGColorMode& mode_png, - bool auto_convert, bool expect_encoder_error = false) -{ + bool auto_convert, bool expect_encoder_error = false) { unsigned error; lodepng::State state; @@ -2459,8 +2284,7 @@ void testBkgdChunk(unsigned r, unsigned g, unsigned b, std::vector png; error = lodepng::encode(png, pixels, w, h, state); - if(expect_encoder_error) - { + if(expect_encoder_error) { ASSERT_NOT_EQUALS(0, error); return; } @@ -2488,8 +2312,7 @@ void testBkgdChunk(unsigned r, unsigned g, unsigned b, error = lodepng_convert(image3.data(), image2.data(), &mode_raw, &mode_temp, w, h); ASSERT_NO_PNG_ERROR(error); ASSERT_EQUALS(pixels.size(), image3.size()); - for(size_t i = 0; i < image3.size(); i++) - { + for(size_t i = 0; i < image3.size(); i++) { ASSERT_EQUALS((int)image3[i], (int)pixels[i]); } } @@ -2501,8 +2324,7 @@ void testBkgdChunk(unsigned r, unsigned g, unsigned b, LodePNGColorType type_pixels, unsigned bitdepth_pixels, LodePNGColorType type_raw, unsigned bitdepth_raw, LodePNGColorType type_png, unsigned bitdepth_png, - bool auto_convert, bool expect_encoder_error = false) -{ + bool auto_convert, bool expect_encoder_error = false) { unsigned error; Image image; generateTestImageRequiringColorType16(image, type_pixels, bitdepth_pixels, false); @@ -2520,8 +2342,7 @@ void testBkgdChunk(unsigned r, unsigned g, unsigned b, mode_raw, mode_png, auto_convert, expect_encoder_error); } -void testBkgdChunk() -{ +void testBkgdChunk() { std::cout << "testBkgdChunk" << std::endl; // color param order is: generated, raw, png ( == bKGD) // here generated means: what color values the pixels will get, so what auto_convert will make it choose @@ -2541,8 +2362,7 @@ void testBkgdChunk() testBkgdChunk(255, 0, 0, 255, 0, 0, LCT_RGBA, 8, LCT_RGBA, 8, LCT_RGBA, 8, false); testBkgdChunk(60000, 0, 0, 60000, 0, 0, LCT_RGBA, 8, LCT_RGBA, 8, LCT_RGBA, 16, false); testBkgdChunk(128, 128, 128, 128, 128, 128, LCT_GREY, 8, LCT_RGBA, 8, LCT_GREY, 8, false); - - { + { LodePNGColorMode pal; lodepng_color_mode_init(&pal); for(int i = 0; i < 200; i++) lodepng_palette_add(&pal, i, i / 2, 0, 255); @@ -2552,8 +2372,7 @@ void testBkgdChunk() unsigned h = 200; std::vector img(w * h); for(unsigned y = 0; y < h; y++) - for(unsigned x = 0; x < w; x++) - { + for(unsigned x = 0; x < w; x++) { img[y * w + x] = x; } @@ -2563,8 +2382,7 @@ void testBkgdChunk() std::vector fourcolor(w * h); for(unsigned y = 0; y < h; y++) - for(unsigned x = 0; x < w; x++) - { + for(unsigned x = 0; x < w; x++) { fourcolor[y * w + x] = x & 3; } // palette index 4 expected for output bKGD: auto_convert should turn the 200-sized @@ -2583,8 +2401,7 @@ void testBkgdChunk() } } -void testBkgdChunk2() -{ +void testBkgdChunk2() { std::cout << "testBkgdChunk2" << std::endl; Image image; generateTestImageRequiringColorType8(image, LCT_GREY, 2, false); @@ -2631,8 +2448,7 @@ void testBkgdChunk2() ASSERT_EQUALS(LCT_GREY, state2.info_png.color.colortype); } -void doMain() -{ +void doMain() { //PNG testPNGCodec(); testPngSuiteTiny(); @@ -2676,14 +2492,11 @@ void doMain() std::cout << "\ntest successful" << std::endl; } -int main() -{ - try - { +int main() { + try { doMain(); } - catch(...) - { + catch(...) { std::cout << "error!" << std::endl; } diff --git a/lodepng_util.cpp b/lodepng_util.cpp index 5f0d1f3c..65a32b52 100644 --- a/lodepng_util.cpp +++ b/lodepng_util.cpp @@ -27,11 +27,9 @@ freely, subject to the following restrictions: #include #include -namespace lodepng -{ +namespace lodepng { -LodePNGInfo getPNGHeaderInfo(const std::vector& png) -{ +LodePNGInfo getPNGHeaderInfo(const std::vector& png) { unsigned w, h; lodepng::State state; lodepng_inspect(&w, &h, &state, &png[0], png.size()); @@ -39,15 +37,13 @@ LodePNGInfo getPNGHeaderInfo(const std::vector& png) } unsigned getChunkInfo(std::vector& names, std::vector& sizes, - const std::vector& png) -{ + const std::vector& png) { // Listing chunks is based on the original file, not the decoded png info. const unsigned char *chunk, *begin, *end, *next; end = &png.back() + 1; begin = chunk = &png.front() + 8; - while(chunk + 8 < end && chunk >= begin) - { + while(chunk + 8 < end && chunk >= begin) { char type[5]; lodepng_chunk_type(type, chunk); if(std::string(type).size() != 4) return 1; @@ -66,16 +62,14 @@ unsigned getChunkInfo(std::vector& names, std::vector& size unsigned getChunks(std::vector names[3], std::vector > chunks[3], - const std::vector& png) -{ + const std::vector& png) { const unsigned char *chunk, *next, *begin, *end; end = &png.back() + 1; begin = chunk = &png.front() + 8; int location = 0; - while(chunk + 8 < end && chunk >= begin) - { + while(chunk + 8 < end && chunk >= begin) { char type[5]; lodepng_chunk_type(type, chunk); std::string name(type); @@ -84,24 +78,15 @@ unsigned getChunks(std::vector names[3], next = lodepng_chunk_next_const(chunk); if (next <= chunk) return 1; // integer overflow - if(name == "IHDR") - { + if(name == "IHDR") { location = 0; - } - else if(name == "PLTE") - { + } else if(name == "PLTE") { location = 1; - } - else if(name == "IDAT") - { + } else if(name == "IDAT") { location = 2; - } - else if(name == "IEND") - { + } else if(name == "IEND") { break; // anything after IEND is not part of the PNG or the 3 groups here. - } - else - { + } else { if(next > end) return 1; // invalid chunk, content too far names[location].push_back(name); chunks[location].push_back(std::vector(chunk, next)); @@ -114,8 +99,7 @@ unsigned getChunks(std::vector names[3], unsigned insertChunks(std::vector& png, - const std::vector > chunks[3]) -{ + const std::vector > chunks[3]) { const unsigned char *chunk, *next, *begin, *end; end = &png.back() + 1; begin = chunk = &png.front() + 8; @@ -124,8 +108,7 @@ unsigned insertChunks(std::vector& png, long l1 = 0; //location 1: PLTE-l1-IDAT (or IHDR-l0-l1-IDAT) long l2 = 0; //location 2: IDAT-l2-IEND - while(chunk + 8 < end && chunk >= begin) - { + while(chunk + 8 < end && chunk >= begin) { char type[5]; lodepng_chunk_type(type, chunk); std::string name(type); @@ -134,17 +117,12 @@ unsigned insertChunks(std::vector& png, next = lodepng_chunk_next_const(chunk); if (next <= chunk) return 1; // integer overflow - if(name == "PLTE") - { + if(name == "PLTE") { if(l0 == 0) l0 = chunk - begin + 8; - } - else if(name == "IDAT") - { + } else if(name == "IDAT") { if(l0 == 0) l0 = chunk - begin + 8; if(l1 == 0) l1 = chunk - begin + 8; - } - else if(name == "IEND") - { + } else if(name == "IEND") { if(l2 == 0) l2 = chunk - begin + 8; } @@ -165,8 +143,7 @@ unsigned insertChunks(std::vector& png, } unsigned getFilterTypesInterlaced(std::vector >& filterTypes, - const std::vector& png) -{ + const std::vector& png) { //Get color type and interlace type lodepng::State state; unsigned w, h; @@ -182,14 +159,12 @@ unsigned getFilterTypesInterlaced(std::vector >& filt std::vector zdata; - while(chunk + 8 < end && chunk >= begin) - { + while(chunk + 8 < end && chunk >= begin) { char type[5]; lodepng_chunk_type(type, chunk); if(std::string(type).size() != 4) break; //Probably not a PNG file - if(std::string(type) == "IDAT") - { + if(std::string(type) == "IDAT") { const unsigned char* cdata = lodepng_chunk_data_const(chunk); unsigned clength = lodepng_chunk_length(chunk); if(chunk + clength + 12 > end || clength > png.size() || chunk + clength + 12 < begin) { @@ -197,8 +172,7 @@ unsigned getFilterTypesInterlaced(std::vector >& filt return 1; } - for(unsigned i = 0; i < clength; i++) - { + for(unsigned i = 0; i < clength; i++) { zdata.push_back(cdata[i]); } } @@ -214,20 +188,16 @@ unsigned getFilterTypesInterlaced(std::vector >& filt if(error) return 1; - if(state.info_png.interlace_method == 0) - { + if(state.info_png.interlace_method == 0) { filterTypes.resize(1); //A line is 1 filter byte + all pixels size_t linebytes = 1 + lodepng_get_raw_size(w, 1, &state.info_png.color); - for(size_t i = 0; i < data.size(); i += linebytes) - { + for(size_t i = 0; i < data.size(); i += linebytes) { filterTypes[0].push_back(data[i]); } - } - else - { + } else { //Interlaced filterTypes.resize(7); static const unsigned ADAM7_IX[7] = { 0, 4, 0, 2, 0, 1, 0 }; /*x start values*/ @@ -235,15 +205,13 @@ unsigned getFilterTypesInterlaced(std::vector >& filt static const unsigned ADAM7_DX[7] = { 8, 8, 4, 4, 2, 2, 1 }; /*x delta values*/ static const unsigned ADAM7_DY[7] = { 8, 8, 8, 4, 4, 2, 2 }; /*y delta values*/ size_t pos = 0; - for(size_t j = 0; j < 7; j++) - { + for(size_t j = 0; j < 7; j++) { unsigned w2 = (w - ADAM7_IX[j] + ADAM7_DX[j] - 1) / ADAM7_DX[j]; unsigned h2 = (h - ADAM7_IY[j] + ADAM7_DY[j] - 1) / ADAM7_DY[j]; if(ADAM7_IX[j] >= w) w2 = 0; if(ADAM7_IY[j] >= h) h2 = 0; size_t linebytes = 1 + lodepng_get_raw_size(w2, 1, &state.info_png.color); - for(size_t i = 0; i < h2; i++) - { + for(size_t i = 0; i < h2; i++) { filterTypes[j].push_back(data[pos]); pos += linebytes; } @@ -253,18 +221,14 @@ unsigned getFilterTypesInterlaced(std::vector >& filt } -unsigned getFilterTypes(std::vector& filterTypes, const std::vector& png) -{ +unsigned getFilterTypes(std::vector& filterTypes, const std::vector& png) { std::vector > passes; unsigned error = getFilterTypesInterlaced(passes, png); if(error) return error; - if(passes.size() == 1) - { + if(passes.size() == 1) { filterTypes.swap(passes[0]); - } - else - { + } else { lodepng::State state; unsigned w, h; lodepng_inspect(&w, &h, &state, &png[0], png.size()); @@ -274,16 +238,14 @@ unsigned getFilterTypes(std::vector& filterTypes, const std::vect filter corresponding the closest to what it would be for non-interlaced image. */ - for(size_t i = 0; i < h; i++) - { + for(size_t i = 0; i < h; i++) { filterTypes.push_back(i % 2 == 0 ? passes[5][i / 2] : passes[6][i / 2]); } } return 0; /* OK */ } -int getPaletteValue(const unsigned char* data, size_t i, int bits) -{ +int getPaletteValue(const unsigned char* data, size_t i, int bits) { if(bits == 8) return data[i]; else if(bits == 4) return (data[i / 2] >> ((i % 2) * 4)) & 15; else if(bits == 2) return (data[i / 4] >> ((i % 4) * 2)) & 3; @@ -291,21 +253,16 @@ int getPaletteValue(const unsigned char* data, size_t i, int bits) else return 0; } - - - #ifdef LODEPNG_COMPILE_ANCILLARY_CHUNKS // Multiplies values with 3x3 matrix -void mulMatrix(float* x2, float* y2, float* z2, const float* m, float x, float y, float z) -{ +void mulMatrix(float* x2, float* y2, float* z2, const float* m, float x, float y, float z) { *x2 = x * m[0] + y * m[1] + z * m[2]; *y2 = x * m[3] + y * m[4] + z * m[5]; *z2 = x * m[6] + y * m[7] + z * m[8]; } // Inverts 3x3 matrix in place -void invMatrix(float* matrix) -{ +void invMatrix(float* matrix) { float e0 = matrix[4] * matrix[8] - matrix[5] * matrix[7]; float e3 = matrix[5] * matrix[6] - matrix[3] * matrix[8]; float e6 = matrix[3] * matrix[7] - matrix[4] * matrix[6]; @@ -325,8 +282,7 @@ void invMatrix(float* matrix) } // Get the matrix to go from linear RGB to XYZ given the RGB whitepoint and chromaticities in xy colorspace -void getChrmMatrix(float* m, float wx, float wy, float rx, float ry, float gx, float gy, float bx, float by) -{ +void getChrmMatrix(float* m, float wx, float wy, float rx, float ry, float gx, float gy, float bx, float by) { float wX = wx / wy, wY = 1, wZ = (1 - wx - wy) / wy; float rX = rx / ry, rY = 1, rZ = (1 - rx - ry) / ry; float gX = gx / gy, gY = 1, gZ = (1 - gx - gy) / gy; @@ -341,44 +297,33 @@ void getChrmMatrix(float* m, float wx, float wy, float rx, float ry, float gx, f unsigned convertToXYZ(float* out, const unsigned char* in, unsigned w, unsigned h, const LodePNGColorMode* mode_in, - const LodePNGInfo* info) -{ + const LodePNGInfo* info) { std::vector data(w * h * 8); LodePNGColorMode mode16 = lodepng_color_mode_make(LCT_RGBA, 16); lodepng_convert(data.data(), in, &mode16, mode_in, w, h); - if(info->iccp_defined && !info->gama_defined && !info->chrm_defined) - { + if(info->iccp_defined && !info->gama_defined && !info->chrm_defined) { return 1; // fail: iCCP chunk not supported and no fallback gamma/chrm available } size_t n = w * h; - for(unsigned i = 0; i < n; i++) - { - for(unsigned c = 0; c < 4; c++) - { + for(unsigned i = 0; i < n; i++) { + for(unsigned c = 0; c < 4; c++) { size_t j = i * 8 + c * 2; out[i * 4 + c] = (data[j + 0] * 256 + data[j + 1]) / 65535.0; } } - if(info->gama_defined && !info->srgb_defined) - { + if(info->gama_defined && !info->srgb_defined) { float gamma = 100000.0f / info->gama_gamma; - for(unsigned i = 0; i < n; i++) - { - for(unsigned c = 0; c < 3; c++) - { + for(unsigned i = 0; i < n; i++) { + for(unsigned c = 0; c < 3; c++) { out[i * 4 + c] = std::pow(out[i * 4 + c], gamma); } } - } - else - { - for(unsigned i = 0; i < n; i++) - { - for(unsigned c = 0; c < 3; c++) - { + } else { + for(unsigned i = 0; i < n; i++) { + for(unsigned c = 0; c < 3; c++) { // sRGB gamma expand float& v = out[i * 4 + c]; if(v < 0.04045) v = c / 12.92; @@ -387,26 +332,21 @@ unsigned convertToXYZ(float* out, const unsigned char* in, } } - if(info->chrm_defined && !info->srgb_defined) - { + if(info->chrm_defined && !info->srgb_defined) { float wx = info->chrm_white_x / 100000.0f, wy = info->chrm_white_y / 100000.0f; float rx = info->chrm_red_x / 100000.0f, ry = info->chrm_red_y / 100000.0f; float gx = info->chrm_green_x / 100000.0f, gy = info->chrm_green_y / 100000.0f; float bx = info->chrm_blue_x / 100000.0f, by = info->chrm_blue_y / 100000.0f; float m[9]; getChrmMatrix(m, wx, wy, rx, ry, gx, gy, bx, by); - for(unsigned i = 0; i < n; i++) - { + for(unsigned i = 0; i < n; i++) { size_t j = i * 4; mulMatrix(&out[j + 0], &out[j + 1], &out[j + 2], m, out[j + 0], out[j + 1], out[j + 2]); } - } - else - { + } else { // linear sRGB to XYZ matrix float m[9] = {0.4124564, 0.3575761, 0.1804375, 0.2126729, 0.7151522, 0.0721750, 0.0193339, 0.1191920, 0.9503041}; - for(unsigned i = 0; i < n; i++) - { + for(unsigned i = 0; i < n; i++) { size_t j = i * 4; mulMatrix(&out[j + 0], &out[j + 1], &out[j + 2], m, out[j + 0], out[j + 1], out[j + 2]); } @@ -417,20 +357,17 @@ unsigned convertToXYZ(float* out, const unsigned char* in, unsigned convertFromXYZ(unsigned char* out, const float* in, unsigned w, unsigned h, const LodePNGColorMode* mode_out, - const LodePNGInfo* info) -{ + const LodePNGInfo* info) { std::vector im(in, in + w * h * 4); std::vector data(w * h * 8); - if(info->iccp_defined && !info->gama_defined && !info->chrm_defined) - { + if(info->iccp_defined && !info->gama_defined && !info->chrm_defined) { return 1; // fail: iCCP chunk not supported and no fallback gamma/chrm available } size_t n = w * h; - if(info->chrm_defined && !info->srgb_defined) - { + if(info->chrm_defined && !info->srgb_defined) { float wx = info->chrm_white_x / 100000.0f, wy = info->chrm_white_y / 100000.0f; float rx = info->chrm_red_x / 100000.0f, ry = info->chrm_red_y / 100000.0f; float gx = info->chrm_green_x / 100000.0f, gy = info->chrm_green_y / 100000.0f; @@ -438,41 +375,30 @@ unsigned convertFromXYZ(unsigned char* out, const float* in, float m[9]; getChrmMatrix(m, wx, wy, rx, ry, gx, gy, bx, by); invMatrix(m); - for(unsigned i = 0; i < n; i++) - { + for(unsigned i = 0; i < n; i++) { size_t j = i * 4; mulMatrix(&im[j + 0], &im[j + 1], &im[j + 2], m, im[j + 0], im[j + 1], im[j + 2]); } - } - else - { + } else { // XYZ to linear sRGB matrix float m[9] = {3.2404542, -1.5371385, -0.4985314, -0.9692660, 1.8760108, 0.0415560, 0.0556434, -0.2040259, 1.0572252}; - for(unsigned i = 0; i < n; i++) - { + for(unsigned i = 0; i < n; i++) { size_t j = i * 4; mulMatrix(&im[j + 0], &im[j + 1], &im[j + 2], m, im[j + 0], im[j + 1], im[j + 2]); } } - if(info->gama_defined && !info->srgb_defined) - { + if(info->gama_defined && !info->srgb_defined) { float gamma = info->gama_gamma / 100000.0f; - for(unsigned i = 0; i < n; i++) - { - for(unsigned c = 0; c < 3; c++) - { + for(unsigned i = 0; i < n; i++) { + for(unsigned c = 0; c < 3; c++) { im[i * 4 + c] = std::pow(im[i * 4 + c], gamma); } } - } - else - { - for(unsigned i = 0; i < n; i++) - { - for(unsigned c = 0; c < 3; c++) - { + } else { + for(unsigned i = 0; i < n; i++) { + for(unsigned c = 0; c < 3; c++) { // sRGB gamma compress float& v = im[i * 4 + c]; if(v < 0.0031308) v *= 12.92; @@ -481,10 +407,8 @@ unsigned convertFromXYZ(unsigned char* out, const float* in, } } - for(unsigned i = 0; i < n; i++) - { - for(unsigned c = 0; c < 4; c++) - { + for(unsigned i = 0; i < n; i++) { + for(unsigned c = 0; c < 4; c++) { size_t j = i * 8 + c * 2; int i16 = (int)(0.5 + 65535.0 * std::min(std::max(0.0f, im[i * 4 + c]), 1.0f)); data[j + 0] = i16 >> 8; @@ -500,67 +424,51 @@ unsigned convertFromXYZ(unsigned char* out, const float* in, #endif /*LODEPNG_COMPILE_ANCILLARY_CHUNKS*/ //This uses a stripped down version of picoPNG to extract detailed zlib information while decompressing. -static const unsigned long LENBASE[29] = - {3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258}; -static const unsigned long LENEXTRA[29] = - {0,0,0,0,0,0,0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0}; -static const unsigned long DISTBASE[30] = - {1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577}; -static const unsigned long DISTEXTRA[30] = - {0,0,0,0,1,1,2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; -static const unsigned long CLCL[19] = - {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; //code length code lengths - -struct ExtractZlib // Zlib decompression and information extraction -{ +static const unsigned long LENBASE[29] = {3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258}; +static const unsigned long LENEXTRA[29] = {0,0,0,0,0,0,0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0}; +static const unsigned long DISTBASE[30] = {1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577}; +static const unsigned long DISTEXTRA[30] = {0,0,0,0,1,1,2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; +static const unsigned long CLCL[19] = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; //code length code lengths + +struct ExtractZlib { // Zlib decompression and information extraction std::vector* zlibinfo; ExtractZlib(std::vector* info) : zlibinfo(info) {}; int error; - unsigned long readBitFromStream(size_t& bitp, const unsigned char* bits) - { + unsigned long readBitFromStream(size_t& bitp, const unsigned char* bits) { unsigned long result = (bits[bitp >> 3] >> (bitp & 0x7)) & 1; bitp++; return result; } - unsigned long readBitsFromStream(size_t& bitp, const unsigned char* bits, size_t nbits) - { + unsigned long readBitsFromStream(size_t& bitp, const unsigned char* bits, size_t nbits) { unsigned long result = 0; for(size_t i = 0; i < nbits; i++) result += (readBitFromStream(bitp, bits)) << i; return result; } - struct HuffmanTree - { - int makeFromLengths(const std::vector& bitlen, unsigned long maxbitlen) - { //make tree given the lengths + struct HuffmanTree { + int makeFromLengths(const std::vector& bitlen, unsigned long maxbitlen) { //make tree given the lengths unsigned long numcodes = (unsigned long)(bitlen.size()), treepos = 0, nodefilled = 0; std::vector tree1d(numcodes), blcount(maxbitlen + 1, 0), nextcode(maxbitlen + 1, 0); //count number of instances of each code length for(unsigned long bits = 0; bits < numcodes; bits++) blcount[bitlen[bits]]++; - for(unsigned long bits = 1; bits <= maxbitlen; bits++) - { + for(unsigned long bits = 1; bits <= maxbitlen; bits++) { nextcode[bits] = (nextcode[bits - 1] + blcount[bits - 1]) << 1; } //generate all the codes for(unsigned long n = 0; n < numcodes; n++) if(bitlen[n] != 0) tree1d[n] = nextcode[bitlen[n]]++; tree2d.clear(); tree2d.resize(numcodes * 2, 32767); //32767 here means the tree2d isn't filled there yet for(unsigned long n = 0; n < numcodes; n++) //the codes - for(unsigned long i = 0; i < bitlen[n]; i++) //the bits for this code - { + for(unsigned long i = 0; i < bitlen[n]; i++) { //the bits for this code unsigned long bit = (tree1d[n] >> (bitlen[n] - i - 1)) & 1; if(treepos > numcodes - 2) return 55; - if(tree2d[2 * treepos + bit] == 32767) //not yet filled in - { - if(i + 1 == bitlen[n]) - { + if(tree2d[2 * treepos + bit] == 32767) { //not yet filled in + if(i + 1 == bitlen[n]) { //last bit tree2d[2 * treepos + bit] = n; treepos = 0; - } - else - { + } else { //addresses are encoded as values > numcodes tree2d[2 * treepos + bit] = ++nodefilled + numcodes; treepos = nodefilled; @@ -570,8 +478,7 @@ struct ExtractZlib // Zlib decompression and information extraction } return 0; } - int decode(bool& decoded, unsigned long& result, size_t& treepos, unsigned long bit) const - { //Decodes a symbol from the tree + int decode(bool& decoded, unsigned long& result, size_t& treepos, unsigned long bit) const { //Decodes a symbol from the tree unsigned long numcodes = (unsigned long)tree2d.size() / 2; if(treepos >= numcodes) return 11; //error: you appeared outside the codetree result = tree2d[2 * treepos + bit]; @@ -583,13 +490,11 @@ struct ExtractZlib // Zlib decompression and information extraction std::vector tree2d; }; - void inflate(std::vector& out, const std::vector& in, size_t inpos = 0) - { + void inflate(std::vector& out, const std::vector& in, size_t inpos = 0) { size_t bp = 0, pos = 0; //bit pointer and byte pointer error = 0; unsigned long BFINAL = 0; - while(!BFINAL && !error) - { + while(!BFINAL && !error) { size_t uncomprblockstart = pos; size_t bpstart = bp; if(bp >> 3 >= in.size()) { error = 52; return; } //error, bit pointer will jump past memory @@ -606,8 +511,7 @@ struct ExtractZlib // Zlib decompression and information extraction } } - void generateFixedTrees(HuffmanTree& tree, HuffmanTree& treeD) //get the tree of a deflated block with fixed tree - { + void generateFixedTrees(HuffmanTree& tree, HuffmanTree& treeD) { //get the tree of a deflated block with fixed tree std::vector bitlen(288, 8), bitlenD(32, 5);; for(size_t i = 144; i <= 255; i++) bitlen[i] = 9; for(size_t i = 256; i <= 279; i++) bitlen[i] = 7; @@ -617,12 +521,10 @@ struct ExtractZlib // Zlib decompression and information extraction //the code tree for Huffman codes, dist codes, and code length codes HuffmanTree codetree, codetreeD, codelengthcodetree; - unsigned long huffmanDecodeSymbol(const unsigned char* in, size_t& bp, const HuffmanTree& tree, size_t inlength) - { + unsigned long huffmanDecodeSymbol(const unsigned char* in, size_t& bp, const HuffmanTree& tree, size_t inlength) { //decode a single symbol from given list of bits with given code tree. return value is the symbol bool decoded; unsigned long ct; - for(size_t treepos = 0;;) - { + for(size_t treepos = 0;;) { if((bp & 0x07) == 0 && (bp >> 3) > inlength) { error = 10; return 0; } //error: end reached without endcode error = tree.decode(decoded, ct, treepos, readBitFromStream(bp, in)); if(error) return 0; //stop, an error happened @@ -631,8 +533,7 @@ struct ExtractZlib // Zlib decompression and information extraction } void getTreeInflateDynamic(HuffmanTree& tree, HuffmanTree& treeD, - const unsigned char* in, size_t& bp, size_t inlength) - { + const unsigned char* in, size_t& bp, size_t inlength) { size_t bpstart = bp; //get the tree of a deflated block with dynamic tree, the tree itself is also Huffman compressed with a known tree std::vector bitlen(288, 0), bitlenD(32, 0); @@ -649,42 +550,33 @@ struct ExtractZlib // Zlib decompression and information extraction for(size_t i = 0; i < codelengthcode.size(); i++) zlibinfo->back().clcl.push_back(codelengthcode[i]); error = codelengthcodetree.makeFromLengths(codelengthcode, 7); if(error) return; size_t i = 0, replength; - while(i < HLIT + HDIST) - { + while(i < HLIT + HDIST) { unsigned long code = huffmanDecodeSymbol(in, bp, codelengthcodetree, inlength); if(error) return; zlibinfo->back().treecodes.push_back(code); //tree symbol code if(code <= 15) { if(i < HLIT) bitlen[i++] = code; else bitlenD[i++ - HLIT] = code; } //a length code - else if(code == 16) //repeat previous - { + else if(code == 16) { //repeat previous if(bp >> 3 >= inlength) { error = 50; return; } //error, bit pointer jumps past memory replength = 3 + readBitsFromStream(bp, in, 2); unsigned long value; //set value to the previous code if((i - 1) < HLIT) value = bitlen[i - 1]; else value = bitlenD[i - HLIT - 1]; - for(size_t n = 0; n < replength; n++) //repeat this value in the next lengths - { + for(size_t n = 0; n < replength; n++) { //repeat this value in the next lengths if(i >= HLIT + HDIST) { error = 13; return; } //error: i is larger than the amount of codes if(i < HLIT) bitlen[i++] = value; else bitlenD[i++ - HLIT] = value; } - } - else if(code == 17) //repeat "0" 3-10 times - { + } else if(code == 17) { //repeat "0" 3-10 times if(bp >> 3 >= inlength) { error = 50; return; } //error, bit pointer jumps past memory replength = 3 + readBitsFromStream(bp, in, 3); zlibinfo->back().treecodes.push_back(replength); //tree symbol code repetitions - for(size_t n = 0; n < replength; n++) //repeat this value in the next lengths - { + for(size_t n = 0; n < replength; n++) { //repeat this value in the next lengths if(i >= HLIT + HDIST) { error = 14; return; } //error: i is larger than the amount of codes if(i < HLIT) bitlen[i++] = 0; else bitlenD[i++ - HLIT] = 0; } - } - else if(code == 18) //repeat "0" 11-138 times - { + } else if(code == 18) { //repeat "0" 11-138 times if(bp >> 3 >= inlength) { error = 50; return; } //error, bit pointer jumps past memory replength = 11 + readBitsFromStream(bp, in, 7); zlibinfo->back().treecodes.push_back(replength); //tree symbol code repetitions - for(size_t n = 0; n < replength; n++) //repeat this value in the next lengths - { + for(size_t n = 0; n < replength; n++) { //repeat this value in the next lengths if(i >= HLIT + HDIST) { error = 15; return; } //error: i is larger than the amount of codes if(i < HLIT) bitlen[i++] = 0; else bitlenD[i++ - HLIT] = 0; } @@ -704,13 +596,11 @@ struct ExtractZlib // Zlib decompression and information extraction } void inflateHuffmanBlock(std::vector& out, - const unsigned char* in, size_t& bp, size_t& pos, size_t inlength, unsigned long btype) - { + const unsigned char* in, size_t& bp, size_t& pos, size_t inlength, unsigned long btype) { size_t numcodes = 0, numlit = 0, numlen = 0; //for logging if(btype == 1) { generateFixedTrees(codetree, codetreeD); } else if(btype == 2) { getTreeInflateDynamic(codetree, codetreeD, in, bp, inlength); if(error) return; } - for(;;) - { + for(;;) { unsigned long code = huffmanDecodeSymbol(in, bp, codetree, inlength); if(error) return; numcodes++; zlibinfo->back().lz77_lcode.push_back(code); //output code @@ -720,15 +610,13 @@ struct ExtractZlib // Zlib decompression and information extraction zlibinfo->back().lz77_lvalue.push_back(0); zlibinfo->back().lz77_dvalue.push_back(0); - if(code == 256) break; //end code - else if(code <= 255) //literal symbol - { + if(code == 256) { + break; //end code + } else if(code <= 255) { //literal symbol out.push_back((unsigned char)(code)); pos++; numlit++; - } - else if(code >= 257 && code <= 285) //length code - { + } else if(code >= 257 && code <= 285) { //length code size_t length = LENBASE[code - 257], numextrabits = LENEXTRA[code - 257]; if((bp >> 3) >= inlength) { error = 51; return; } //error, bit pointer will jump past memory length += readBitsFromStream(bp, in, numextrabits); @@ -738,8 +626,7 @@ struct ExtractZlib // Zlib decompression and information extraction if((bp >> 3) >= inlength) { error = 51; return; } //error, bit pointer will jump past memory dist += readBitsFromStream(bp, in, numextrabitsD); size_t start = pos, back = start - dist; //backwards - for(size_t i = 0; i < length; i++) - { + for(size_t i = 0; i < length; i++) { out.push_back(out[back++]); pos++; if(back >= start) back = start - dist; @@ -757,24 +644,21 @@ struct ExtractZlib // Zlib decompression and information extraction } void inflateNoCompression(std::vector& out, - const unsigned char* in, size_t& bp, size_t& pos, size_t inlength) - { + const unsigned char* in, size_t& bp, size_t& pos, size_t inlength) { while((bp & 0x7) != 0) bp++; //go to first boundary of byte size_t p = bp / 8; if(p >= inlength - 4) { error = 52; return; } //error, bit pointer will jump past memory unsigned long LEN = in[p] + 256u * in[p + 1], NLEN = in[p + 2] + 256u * in[p + 3]; p += 4; if(LEN + NLEN != 65535) { error = 21; return; } //error: NLEN is not one's complement of LEN if(p + LEN > inlength) { error = 23; return; } //error: reading outside of in buffer - for(unsigned long n = 0; n < LEN; n++) - { + for(unsigned long n = 0; n < LEN; n++) { out.push_back(in[p++]); //read LEN bytes of literal data pos++; } bp = p * 8; } - int decompress(std::vector& out, const std::vector& in) //returns error value - { + int decompress(std::vector& out, const std::vector& in) { //returns error value if(in.size() < 2) { return 53; } //error, size of zlib data too small //error: 256 * in[0] + in[1] must be a multiple of 31, the FCHECK value is supposed to be made that way if((in[0] * 256 + in[1]) % 31 != 0) { return 24; } @@ -788,13 +672,11 @@ struct ExtractZlib // Zlib decompression and information extraction } }; -struct ExtractPNG //PNG decoding and information extraction -{ +struct ExtractPNG { //PNG decoding and information extraction std::vector* zlibinfo; ExtractPNG(std::vector* info) : zlibinfo(info) {}; int error; - void decode(const unsigned char* in, size_t size) - { + void decode(const unsigned char* in, size_t size) { error = 0; if(size == 0 || in == 0) { error = 48; return; } //the given data is empty readPngHeader(&in[0], size); if(error) return; @@ -803,8 +685,7 @@ struct ExtractPNG //PNG decoding and information extraction bool IEND = false; //loop through the chunks, ignoring unknown chunks and stopping at IEND chunk. //IDAT data is put at the start of the in buffer - while(!IEND) - { + while(!IEND) { //error: size of the in buffer too small to contain next chunk if(pos + 8 >= size) { error = 30; return; } size_t chunkLength = read32bitInt(&in[pos]); pos += 4; @@ -812,18 +693,13 @@ struct ExtractPNG //PNG decoding and information extraction //error: size of the in buffer too small to contain next chunk if(pos + chunkLength >= size) { error = 35; return; } //IDAT chunk, containing compressed image data - if(in[pos + 0] == 'I' && in[pos + 1] == 'D' && in[pos + 2] == 'A' && in[pos + 3] == 'T') - { + if(in[pos + 0] == 'I' && in[pos + 1] == 'D' && in[pos + 2] == 'A' && in[pos + 3] == 'T') { idat.insert(idat.end(), &in[pos + 4], &in[pos + 4 + chunkLength]); pos += (4 + chunkLength); - } - else if(in[pos + 0] == 'I' && in[pos + 1] == 'E' && in[pos + 2] == 'N' && in[pos + 3] == 'D') - { + } else if(in[pos + 0] == 'I' && in[pos + 1] == 'E' && in[pos + 2] == 'N' && in[pos + 3] == 'D') { pos += 4; IEND = true; - } - else //it's not an implemented chunk type, so ignore it: skip over the data - { + } else { //it's not an implemented chunk type, so ignore it: skip over the data pos += (chunkLength + 4); //skip 4 letters and uninterpreted data of unimplemented chunk } pos += 4; //step over CRC (which is ignored) @@ -835,8 +711,7 @@ struct ExtractPNG //PNG decoding and information extraction } //read the information from the header and store it in the Info - void readPngHeader(const unsigned char* in, size_t inlength) - { + void readPngHeader(const unsigned char* in, size_t inlength) { if(inlength < 29) { error = 27; return; } //error: the data length is smaller than the length of the header if(in[0] != 137 || in[1] != 80 || in[2] != 78 || in[3] != 71 || in[4] != 13 || in[5] != 10 || in[6] != 26 || in[7] != 10) { error = 28; return; } //no PNG signature @@ -844,33 +719,28 @@ struct ExtractPNG //PNG decoding and information extraction if(in[12] != 'I' || in[13] != 'H' || in[14] != 'D' || in[15] != 'R') { error = 29; return; } } - unsigned long readBitFromReversedStream(size_t& bitp, const unsigned char* bits) - { + unsigned long readBitFromReversedStream(size_t& bitp, const unsigned char* bits) { unsigned long result = (bits[bitp >> 3] >> (7 - (bitp & 0x7))) & 1; bitp++; return result; } - unsigned long readBitsFromReversedStream(size_t& bitp, const unsigned char* bits, unsigned long nbits) - { + unsigned long readBitsFromReversedStream(size_t& bitp, const unsigned char* bits, unsigned long nbits) { unsigned long result = 0; for(size_t i = nbits - 1; i < nbits; i--) result += ((readBitFromReversedStream(bitp, bits)) << i); return result; } - void setBitOfReversedStream(size_t& bitp, unsigned char* bits, unsigned long bit) - { + void setBitOfReversedStream(size_t& bitp, unsigned char* bits, unsigned long bit) { bits[bitp >> 3] |= (bit << (7 - (bitp & 0x7))); bitp++; } - unsigned long read32bitInt(const unsigned char* buffer) - { + unsigned long read32bitInt(const unsigned char* buffer) { return (unsigned int)((buffer[0] << 24u) | (buffer[1] << 16u) | (buffer[2] << 8u) | buffer[3]); } }; -void extractZlibInfo(std::vector& zlibinfo, const std::vector& in) -{ +void extractZlibInfo(std::vector& zlibinfo, const std::vector& in) { ExtractPNG decoder(&zlibinfo); decoder.decode(&in[0], in.size()); diff --git a/lodepng_util.h b/lodepng_util.h index e67b8180..305951fc 100644 --- a/lodepng_util.h +++ b/lodepng_util.h @@ -35,8 +35,7 @@ Not part of the stable API of lodepng, more loose separate utils. #include #include "lodepng.h" -namespace lodepng -{ +namespace lodepng { /* Returns info from the header of the PNG by value, purely for convenience. @@ -172,8 +171,7 @@ unsigned convertFromXYZ(unsigned char* out, const float* in, /* The information for extractZlibInfo. */ -struct ZlibBlockInfo -{ +struct ZlibBlockInfo { int btype; //block type (0-2) size_t compressedbits; //size of compressed block in bits size_t uncompressedbytes; //size of uncompressed block in bytes diff --git a/pngdetail.cpp b/pngdetail.cpp index 98fa5fa1..c0aa1699 100644 --- a/pngdetail.cpp +++ b/pngdetail.cpp @@ -55,8 +55,7 @@ everything except huge output: #include #include -void showHelp() -{ +void showHelp() { std::cout << "pngdetail by Lode Vandevenne" << std::endl; std::cout << "version: " << LODEPNG_VERSION_STRING << std::endl; std::cout << "Shows detailed information about a PNG image, its compression and possible corruptions.\n" @@ -105,8 +104,7 @@ enum HexFormat { HF_MIX // hex and ascii }; -struct Options -{ +struct Options { bool verbose; bool show_one_line_summary; //show filesize, pixels and color type on single line bool show_header; @@ -136,21 +134,18 @@ struct Options show_palette(false), show_palette_pixels(false), hexformat(HF_MIX), show_render(false), rendermode(RM_ASCII), rendersize(80), show_chunks(false), show_chunks2(false), show_filters(false), - zlib_info(false), zlib_blocks(false), zlib_counts(false), zlib_full(false), use_hex(false) - { + zlib_info(false), zlib_blocks(false), zlib_counts(false), zlib_full(false), use_hex(false) { } }; unsigned inspect_chunk_by_name(const unsigned char* data, const unsigned char* end, - lodepng::State& state, const char type[5]) -{ + lodepng::State& state, const char type[5]) { const unsigned char* p = lodepng_chunk_find_const(data, end, type); return lodepng_inspect_chunk(&state, p - data, data, end - data); } // Lazy loads the raw file, inspected header or entire image as needed -struct Data -{ +struct Data { std::string filename; std::vector buffer; std::vector pixels; // 16-bit @@ -164,21 +159,16 @@ struct Data // Load the file if not already loaded - void loadFile() - { - if(buffer.empty()) - { + void loadFile() { + if(buffer.empty()) { error = lodepng::load_file(buffer, filename); //load the image file with given filename - } - else - { + } else { error = 0; // for reloadpixels, reset error if file was already successfully loaded } } // Load header info (plus a few more nearby light chunks) if not already loaded, and the file if needed - void loadInspect() - { + void loadInspect() { if(inspected) return; inspected = true; loadFile(); @@ -208,13 +198,11 @@ struct Data } // Load the pixels if not already loaded, and the file if needed - void loadPixels() - { + void loadPixels() { if(pixels.empty()) reloadPixels(); } - void reloadPixels() - { + void reloadPixels() { loadFile(); if(error) return; inspected = true; @@ -225,11 +213,9 @@ struct Data } }; -std::string colorTypeString(LodePNGColorType type) -{ +std::string colorTypeString(LodePNGColorType type) { std::string name; - switch(type) - { + switch(type) { case LCT_GREY: name = "grey"; break; case LCT_RGB: name = "RGB"; break; case LCT_PALETTE: name = "palette"; break; @@ -243,8 +229,7 @@ std::string colorTypeString(LodePNGColorType type) } template -T strtoval(const std::string& s) -{ +T strtoval(const std::string& s) { std::istringstream sstream(s); T val; sstream >> val; @@ -255,8 +240,7 @@ T strtoval(const std::string& s) /* Display the names and sizes of all chunks in the PNG file. */ -void displayChunkNames(Data& data, const Options& options) -{ +void displayChunkNames(Data& data, const Options& options) { data.loadFile(); if(data.error) return; std::cout << (options.use_hex ? std::hex: std::dec); @@ -272,23 +256,18 @@ void displayChunkNames(Data& data, const Options& options) } } - if(options.show_chunks2) - { + if(options.show_chunks2) { std::cout << "Chunk types: "; for(size_t i = 0; i < names.size(); i++) std::cout << names[i] << " "; std::cout << std::endl; std::cout << "Chunk sizes: "; for(size_t i = 0; i < sizes.size(); i++) std::cout << sizes[i] << " "; std::cout << std::endl; - } - else - { + } else { std::cout << "Chunks (type: lengths):"; std::string last_type; - for(size_t i = 0; i < names.size(); i++) - { - if(last_type != names[i]) - { + for(size_t i = 0; i < names.size(); i++) { + if(last_type != names[i]) { std::cout << std::endl; std::cout << " " << names[i] << ": "; } @@ -428,18 +407,14 @@ char RGBtoLetter(unsigned char r, unsigned char g, unsigned char b, unsigned cha } std::vector rescale(const std::vector& in, - int w0, int h0, int w1, int h1, bool smooth) -{ + int w0, int h0, int w1, int h1, bool smooth) { int numchannels = in.size() / (w0 * h0); std::vector out(w1 * h1 * numchannels); - if(smooth) - { + if(smooth) { // box filter. std::vector temp(w1 * h0 * numchannels); - for (int c = 0; c < numchannels; c++) - { - for (int x = 0; x < w1; x++) - { + for (int c = 0; c < numchannels; c++) { + for (int x = 0; x < w1; x++) { float xaf = x * 1.0 * w0 / w1; float xbf = (x + 1.0) * w0 / w1; int xa = (int)xaf; @@ -447,12 +422,10 @@ std::vector rescale(const std::vector& in, double norm = 1.0 / (xbf - xaf); xaf -= std::floor(xaf); xbf -= std::floor(xbf); - for (int y = 0; y < h0; y++) - { + for (int y = 0; y < h0; y++) { int index1 = x * numchannels + y * w1 * numchannels; double val = 0; - for(int x0 = xa; x0 <= xb; x0++) - { + for(int x0 = xa; x0 <= xb; x0++) { int index0 = x0 * numchannels + y * w0 * numchannels; double v = 1; if(x0 == xa) v -= xaf; @@ -462,8 +435,7 @@ std::vector rescale(const std::vector& in, temp[index1 + c] = val * norm; } } - for (int y = 0; y < h1; y++) - { + for (int y = 0; y < h1; y++) { float yaf = y * 1.0 * h0 / h1; float ybf = (y + 1.0) * h0 / h1; int ya = (int)yaf; @@ -471,12 +443,10 @@ std::vector rescale(const std::vector& in, double norm = 1.0 / (ybf - yaf); yaf -= std::floor(yaf); ybf -= std::floor(ybf); - for (int x = 0; x < w1; x++) - { + for (int x = 0; x < w1; x++) { int index1 = x * numchannels + y * w1 * numchannels; double val = 0; - for(int y0 = ya; y0 <= yb; y0++) - { + for(int y0 = ya; y0 <= yb; y0++) { int index0 = x * numchannels + y0 * w1 * numchannels; double v = 1; if(y0 == ya) v -= yaf; @@ -488,16 +458,13 @@ std::vector rescale(const std::vector& in, } } } else { - for(int y = 0; y < h1; y++) - { + for(int y = 0; y < h1; y++) { int y0 = (int)((y + 0.5) * h0 / h1 - 0.5); - for (int x = 0; x < w1; x++) - { + for (int x = 0; x < w1; x++) { int x0 = (int)((x + 0.5) * w0 / w1 - 0.5); int index0 = x0 * numchannels + y0 * w0 * numchannels; int index1 = x * numchannels + y * w1 * numchannels; - for (int c = 0; c < numchannels; c++) - { + for (int c = 0; c < numchannels; c++) { out[index1 + c] = in[index0 + c]; } } @@ -510,12 +477,10 @@ std::vector rescale(const std::vector& in, Show ASCII art preview of the image image is given in 16-bit big endian */ -void displayAsciiArt(const std::vector& image, unsigned w, unsigned h, unsigned asciiw) -{ +void displayAsciiArt(const std::vector& image, unsigned w, unsigned h, unsigned asciiw) { const std::vector* imagep = ℑ std::vector image2; - if(asciiw < w) - { + if(asciiw < w) { unsigned w2 = asciiw; unsigned h2 = h * w2 / w; image2 = rescale(image, w, h, w2, h2, true); @@ -523,19 +488,16 @@ void displayAsciiArt(const std::vector& image, unsigned w, unsign w = w2; h = h2; } - if(w > 0 && h > 0) - { + if(w > 0 && h > 0) { std::cout << "ASCII Art Preview: " << std::endl; unsigned h2 = 1 + ((h - 1) * 4) / 7; //compensate for non-square characters in terminal std::cout << '+'; for(unsigned x = 0; x < w; x++) std::cout << '-'; std::cout << '+' << std::endl; - for(unsigned y = 0; y < h2; y++) - { + for(unsigned y = 0; y < h2; y++) { std::cout << "|"; unsigned y2 = y * h / h2; - for(unsigned x = 0; x < w; x++) - { + for(unsigned x = 0; x < w; x++) { int r = (*imagep)[y2 * w * 8 + x * 8 + 0]; int g = (*imagep)[y2 * w * 8 + x * 8 + 2]; int b = (*imagep)[y2 * w * 8 + x * 8 + 4]; @@ -555,31 +517,24 @@ void displayAsciiArt(const std::vector& image, unsigned w, unsign //sixteen: print 16 bits per pixel //alpha: print alpha channel //input image ALWAYS given in 16-bit per channel RGBA -void displayColorsHex(const std::vector& image, unsigned w, unsigned h, bool sixteen) -{ +void displayColorsHex(const std::vector& image, unsigned w, unsigned h, bool sixteen) { std::ios_base::fmtflags flags = std::cout.flags(); - if(w > 0 && h > 0) - { + if(w > 0 && h > 0) { std::cout << "Colors (CSS RGBA hex format):" << std::endl; - for(unsigned y = 0; y < h; y++) - { + for(unsigned y = 0; y < h; y++) { std::cout.flags(flags); //print line numbers in hex or dec whatever it originally was std::cout << y << ":"; - for(unsigned x = 0; x < w; x++) - { + for(unsigned x = 0; x < w; x++) { size_t index = y * w * 8 + x * 8; - if (sixteen) - { + if (sixteen) { int r = image[index + 0] * 256 + image[index + 1]; int g = image[index + 2] * 256 + image[index + 3]; int b = image[index + 4] * 256 + image[index + 5]; int a = image[index + 6] * 256 + image[index + 7]; std::cout << std::hex << std::setfill('0') << " #" << std::setw(4) << r << std::setw(4) << g << std::setw(4) << b << std::setw(4) << a; - } - else - { + } else { int r = image[index + 0]; int g = image[index + 2]; int b = image[index + 4]; @@ -598,38 +553,30 @@ void displayColorsHex(const std::vector& image, unsigned w, unsig /* Show the filtertypes of each scanline in this PNG image. */ -void displayFilterTypes(Data& data, const Options& options) -{ +void displayFilterTypes(Data& data, const Options& options) { std::cout << (options.use_hex ? std::hex: std::dec); data.loadFile(); if(data.error) return; const std::vector& buffer = data.buffer; std::vector > types; unsigned error = lodepng::getFilterTypesInterlaced(types, buffer); - if(error) - { + if(error) { std::cout << "Error getting filter types" << std::endl; return; } - if(types.size() == 7) - { + if(types.size() == 7) { std::cout << "Filter types (Adam7 interlaced):" << std::endl; - for(int j = 0; j < 7; j++) - { + for(int j = 0; j < 7; j++) { std::cout << " Pass " << (j + 1) << ": "; - for(size_t i = 0; i < types[j].size(); i++) - { + for(size_t i = 0; i < types[j].size(); i++) { std::cout << (int)(types[j][i]); } std::cout << std::endl; } - } - else - { + } else { std::cout << "Filter types: "; - for(size_t i = 0; i < types[0].size(); i++) - { + for(size_t i = 0; i < types[0].size(); i++) { std::cout << (int)(types[0][i]); } std::cout << std::endl; @@ -637,8 +584,7 @@ void displayFilterTypes(Data& data, const Options& options) } //image type MUST be palette -void displayPalette(Data& data, const Options& options) -{ +void displayPalette(Data& data, const Options& options) { data.loadInspect(); if(data.error) return; std::cout << (options.use_hex ? std::hex: std::dec); @@ -650,8 +596,7 @@ void displayPalette(Data& data, const Options& options) std::cout << "Palette colors: "; std::ios_base::fmtflags flags = std::cout.flags(); std::cout << std::hex << std::setfill('0'); - for(size_t i = 0; i < color.palettesize; i++) - { + for(size_t i = 0; i < color.palettesize; i++) { unsigned char* p = &color.palette[i * 4]; std::cout << "#" << std::setw(2) << (int)p[0] << std::setw(2) << (int)p[1] << std::setw(2) << (int)p[2] << std::setw(2) << (int)p[3] << " "; } @@ -660,8 +605,7 @@ void displayPalette(Data& data, const Options& options) } //image type MUST be palette -void displayPalettePixels(const std::vector& buffer, const Options& options) -{ +void displayPalettePixels(const std::vector& buffer, const Options& options) { unsigned w, h; lodepng::State state; std::vector out; @@ -671,23 +615,19 @@ void displayPalettePixels(const std::vector& buffer, const Option lodepng::decode(out, w, h, state, buffer); - if(state.info_png.color.colortype == LCT_PALETTE) - { - if (options.show_color_stats) - { + if(state.info_png.color.colortype == LCT_PALETTE) { + if (options.show_color_stats) { std::vector count(256, 0); size_t outofbounds = 0; - for(size_t i = 0; i < w * h; i++) - { + for(size_t i = 0; i < w * h; i++) { int value = lodepng::getPaletteValue(&out[0], i, state.info_raw.bitdepth); count[value]++; if(value >= (int)state.info_raw.palettesize) outofbounds++; } std::cout << "Palette count: "; - for(size_t i = 0; i < state.info_raw.palettesize; i++) - { + for(size_t i = 0; i < state.info_raw.palettesize; i++) { std::cout << count[i] << " "; } std::cout << std::endl; @@ -696,21 +636,17 @@ void displayPalettePixels(const std::vector& buffer, const Option } std::cout << "Pixel palette indices:" << std::endl; - for(size_t i = 0; i < w * h; i++) - { + for(size_t i = 0; i < w * h; i++) { int value = lodepng::getPaletteValue(&out[0], i, state.info_raw.bitdepth); std::cout << value << ", "; if(i % w == w - 1) std::cout << std::endl; } - } - else - { + } else { std::cout << "Pixel palette indices: not shown, not a palette image\n" << std::endl; } } -void printZlibInfo(Data& data, const Options& options) -{ +void printZlibInfo(Data& data, const Options& options) { data.loadFile(); if(data.error) return; const std::vector& in = data.buffer; @@ -719,15 +655,13 @@ void printZlibInfo(Data& data, const Options& options) std::vector zlibinfo; lodepng::extractZlibInfo(zlibinfo, in); - if(options.zlib_info) - { + if(options.zlib_info) { //std::cout << "Zlib info: " << std::endl; size_t compressed = 0; size_t uncompressed = 0; std::vector boundaries_compressed; std::vector boundaries_uncompressed; - for(size_t i = 0; i < zlibinfo.size(); i++) - { + for(size_t i = 0; i < zlibinfo.size(); i++) { compressed += zlibinfo[i].compressedbits / 8; uncompressed += zlibinfo[i].uncompressedbytes; boundaries_compressed.push_back(compressed); @@ -738,8 +672,7 @@ void printZlibInfo(Data& data, const Options& options) std::cout << "Compressed size: " << compressed << std::endl; std::cout << "Uncompressed size: " << uncompressed << std::endl; std::cout << "Amount of zlib blocks: " << zlibinfo.size() << std::endl; - if(zlibinfo.size() > 1) - { + if(zlibinfo.size() > 1) { std::cout << "Block sizes (uncompressed): "; for(size_t i = 0; i < zlibinfo.size(); i++) std::cout << zlibinfo[i].uncompressedbytes << " "; @@ -759,10 +692,8 @@ void printZlibInfo(Data& data, const Options& options) } } - if(options.zlib_blocks) - { - for(size_t i = 0; i < zlibinfo.size(); i++) - { + if(options.zlib_blocks) { + for(size_t i = 0; i < zlibinfo.size(); i++) { const lodepng::ZlibBlockInfo& info = zlibinfo[i]; std::cout << "Zlib block " << i << ":" << std::endl; @@ -773,14 +704,12 @@ void printZlibInfo(Data& data, const Options& options) std::cout << " block compressed: " << compressedsize << " (" << compressedsize / 1024 << "K) (" << info.compressedbits << " bits)" << std::endl; std::cout << " block uncompressed: " << uncompressedsize << " (" << uncompressedsize / 1024 << "K)" << std::endl; - if(info.btype > 2) - { + if(info.btype > 2) { std::cout << "Error: Invalid Block Type" << std::endl; return; } - if(info.btype == 2) - { + if(info.btype == 2) { std::cout << " encoded trees size: " << info.treebits / 8 << " (" << info.treebits << " bits)" << std::endl; std::cout << " HLIT: " << info.hlit << std::endl; std::cout << " HDIST: " << info.hdist << std::endl; @@ -788,17 +717,12 @@ void printZlibInfo(Data& data, const Options& options) std::cout << std::hex; std::cout << " code length code lengths: "; for(size_t j = 0; j < 19; j++) std::cout << info.clcl[j]; std::cout << std::endl; if(!options.use_hex) std::cout << std::dec; - if(options.zlib_full) - { - for(size_t j = 0; j < info.treecodes.size(); j++) - { + if(options.zlib_full) { + for(size_t j = 0; j < info.treecodes.size(); j++) { int code = info.treecodes[j]; - if(code < 17) - { + if(code < 17) { std::cout << " tree: " << code << std::endl; - } - else - { + } else { j++; std::cout << " tree: " << code << " rep: " << info.treecodes[j] << std::endl; } @@ -816,43 +740,30 @@ void printZlibInfo(Data& data, const Options& options) } - if(info.btype != 0) - { + if(info.btype != 0) { std::cout << " code counts: lit: " << info.numlit << ", len/dist: " << info.numlen << ", total: " << (info.numlit + info.numlen + 1) << ", with dists: " << (info.numlit + 2 * info.numlen + 1) << std::endl; - if(options.zlib_full) - { - for(size_t j = 0; j < info.lz77_lcode.size(); j++) - { + if(options.zlib_full) { + for(size_t j = 0; j < info.lz77_lcode.size(); j++) { int symbol = info.lz77_lcode[j]; - if(symbol == 256) - { + if(symbol == 256) { std::cout << " end" << std::endl; - } - else if(symbol < 256) - { + } else if(symbol < 256) { std::cout << " lit: " << symbol << std::endl; - } - else - { + } else { std::cout << " len: " << info.lz77_lvalue[j] << ", dist: " << info.lz77_dvalue[j] << std::endl; } } } - if(options.zlib_counts) - { + if(options.zlib_counts) { std::vector ll_count(288, 0); std::vector d_count(32, 0); - for(size_t j = 0; j < info.lz77_lcode.size(); j++) - { + for(size_t j = 0; j < info.lz77_lcode.size(); j++) { int symbol = info.lz77_lcode[j]; - if(symbol <= 256) - { + if(symbol <= 256) { ll_count[symbol]++; - } - else - { + } else { ll_count[symbol]++; d_count[info.lz77_dcode[j]]++; } @@ -898,8 +809,7 @@ size_t countColors(std::vector image, unsigned w, unsigned h, } } *ro = *go = *bo = *ao = 0; - for(size_t i = 0; i < rm.size(); i++) - { + for(size_t i = 0; i < rm.size(); i++) { *ro += rm[i]; *go += gm[i]; *bo += bm[i]; @@ -910,19 +820,16 @@ size_t countColors(std::vector image, unsigned w, unsigned h, } -void showError(Data& data, const Options& options) -{ +void showError(Data& data, const Options& options) { std::cout << (options.use_hex ? std::hex: std::dec); std::string prefix = (options.use_hex ? "0x": ""); - if(!data.error) - { + if(!data.error) { std::cout << "No error" << std::endl; } std::cout << "Decoding error " << prefix << data.error << ": " << lodepng_error_text(data.error) << std::endl; } -void loadWithErrorRecovery(Data& data, const Options& options) -{ +void loadWithErrorRecovery(Data& data, const Options& options) { (void)options; unsigned& error = data.error; lodepng::State& state = data.state; @@ -930,46 +837,35 @@ void loadWithErrorRecovery(Data& data, const Options& options) data.loadPixels(); // In case of checksum errors and some other ignorable errors, report it but ignore it and retry - while(error) - { + while(error) { // Not showing regular error here, is shown at end of program. unsigned error2 = error; - if(error == 57) - { + if(error == 57) { showError(data, options); std::cerr << "Ignoring the error: enabling ignore_crc" << std::endl; state.decoder.ignore_crc = 1; data.reloadPixels(); - } - else if(error == 58) - { + } else if(error == 58) { showError(data, options); std::cerr << "Ignoring the error: enabling ignore_adler32" << std::endl; state.decoder.zlibsettings.ignore_adler32 = 1; data.reloadPixels(); - } - else if(error == 69) - { + } else if(error == 69) { showError(data, options); std::cerr << "Ignoring the error: enabling ignore_critical" << std::endl; state.decoder.ignore_critical = 1; data.reloadPixels(); - } - else if(error == 30 || error == 63) - { + } else if(error == 30 || error == 63) { showError(data, options); std::cerr << "Ignoring the error: enabling ignore_end" << std::endl; state.decoder.ignore_end = 1; data.reloadPixels(); - } - else - { + } else { if(error == 0) std::cerr << "This error is unrecoverable" << std::endl; break; // other error that we cannot ignore } if(error == 0) std::cerr << "Successfully ignored the error" << std::endl; - if(error == error2) - { + if(error == error2) { std::cerr << "Failed to ignore the error" << std::endl; break; // avoid infinite loop if ignoring did not fix the error code } @@ -979,8 +875,7 @@ void loadWithErrorRecovery(Data& data, const Options& options) -void showSingleLineSummary(Data& data, const Options& options) -{ +void showSingleLineSummary(Data& data, const Options& options) { data.loadInspect(); if(data.error) return; std::cout << (options.use_hex ? std::hex: std::dec); @@ -990,83 +885,68 @@ void showSingleLineSummary(Data& data, const Options& options) std::cout << "Color: " << colorTypeString(data.state.info_png.color.colortype) << ", " << data.state.info_png.color.bitdepth << " bit" << std::endl; } -void showHeaderInfo(Data& data, const Options& options) -{ +void showHeaderInfo(Data& data, const Options& options) { data.loadInspect(); if(data.error) return; std::cout << (options.use_hex ? std::hex: std::dec); const LodePNGInfo& info = data.state.info_png; const LodePNGColorMode& color = info.color; - if(options.show_header) - { + if(options.show_header) { std::cout << "Filesize: " << data.buffer.size() << " (" << data.buffer.size() / 1024 << "K)" << std::endl; std::cout << "Width: " << data.w << std::endl; std::cout << "Height: " << data.h << std::endl; std::cout << "Interlace method: " << info.interlace_method << std::endl; - if(options.verbose) - { + if(options.verbose) { std::cout << "Compression method: " << info.compression_method << std::endl; std::cout << "Filter method: " << info.filter_method << std::endl; } std::cout << "Color type: " << colorTypeString(color.colortype) << std::endl; std::cout << "Bit depth: " << color.bitdepth << std::endl; - if(options.verbose) - { + if(options.verbose) { std::cout << "Bits per pixel: " << lodepng_get_bpp(&color) << std::endl; std::cout << "Channels per pixel: " << lodepng_get_channels(&color) << std::endl; std::cout << "Is greyscale type: " << lodepng_is_greyscale_type(&color) << std::endl; std::cout << "Can have alpha: " << lodepng_can_have_alpha(&color) << std::endl; std::cout << "Has color key: " << color.key_defined << std::endl; } - if (color.colortype == LCT_PALETTE) - { + if (color.colortype == LCT_PALETTE) { std::cout << "Palette size: " << color.palettesize << std::endl; } - if(color.key_defined) - { + if(color.key_defined) { std::cout << "Color key rgb: " << color.key_r << ", " << color.key_g << ", " << color.key_b << std::endl; } - if(info.background_defined) - { - if(color.colortype == LCT_PALETTE) - { + if(info.background_defined) { + if(color.colortype == LCT_PALETTE) { std::cout << "Background index: " << info.background_r << std::endl; - } - else - { + } else { std::cout << "Background rgb: " << info.background_r << ", " << info.background_g << ", " << info.background_b << std::endl; } } - if(info.gama_defined) - { + if(info.gama_defined) { std::cout << "gAMA defined: " << info.gama_gamma << " (" << (info.gama_gamma / 100000.0) << ", " << (100000.0 / info.gama_gamma) << ")" << std::endl; } - if(info.chrm_defined) - { + if(info.chrm_defined) { std::cout << "cHRM defined: w: " << (info.chrm_white_x / 100000.0) << " " << (info.chrm_white_y / 100000.0) << ", r: " << (info.chrm_red_x / 100000.0) << " " << (info.chrm_red_y / 100000.0) << ", g: " << (info.chrm_green_x / 100000.0) << " " << (info.chrm_green_y / 100000.0) << ", b: " << (info.chrm_blue_x / 100000.0) << " " << (info.chrm_blue_y / 100000.0) << std::endl; } - if(info.srgb_defined) - { + if(info.srgb_defined) { std::cout << "sRGB defined: rendering intent: " << info.srgb_intent << std::endl; } - if(info.iccp_defined) - { + if(info.iccp_defined) { std::cout << "iCCP defined: (" << info.iccp_profile_size << " bytes), name: " << info.iccp_name << std::endl; if(options.verbose && !options.show_icc) std::cout << "Use -i to show full ICC profile" << std::endl; } } - if(info.iccp_defined && options.show_icc) - { + if(info.iccp_defined && options.show_icc) { for(size_t i = 0; i < info.iccp_profile_size; i++) { unsigned char c = info.iccp_profile[i]; if(c > 32 && c < 127 && options.hexformat == HF_MIX) printf(" %c ", c); @@ -1076,19 +956,16 @@ void showHeaderInfo(Data& data, const Options& options) std::cout << std::endl; } - if(options.show_header) - { + if(options.show_header) { if(options.verbose) std::cout << "Physics defined: " << info.phys_defined << std::endl; - if(info.phys_defined) - { + if(info.phys_defined) { std::cout << "Physics: X: " << info.phys_x << ", Y: " << info.phys_y << ", unit: " << info.phys_unit << std::endl; } } } // A bit more PNG info, which is from chunks that can come after IDAT. showHeaderInfo shows most other stuff. -void showPNGInfo(Data& data, const Options& options) -{ +void showPNGInfo(Data& data, const Options& options) { loadWithErrorRecovery(data, options); if(data.error) return; std::cout << (options.use_hex ? std::hex: std::dec); @@ -1096,13 +973,11 @@ void showPNGInfo(Data& data, const Options& options) const LodePNGInfo& info = data.state.info_png; if(options.verbose) std::cout << "Texts: " << info.text_num << std::endl; - for(size_t i = 0; i < info.text_num; i++) - { + for(size_t i = 0; i < info.text_num; i++) { std::cout << "Text: " << info.text_keys[i] << ": " << info.text_strings[i] << std::endl; } if(options.verbose) std::cout << "International texts: " << info.itext_num << std::endl; - for(size_t i = 0; i < info.itext_num; i++) - { + for(size_t i = 0; i < info.itext_num; i++) { std::cout << "Text: " << info.itext_keys[i] << ", " << info.itext_langtags[i] << ", " @@ -1110,8 +985,7 @@ void showPNGInfo(Data& data, const Options& options) << info.itext_strings[i] << std::endl; } if(options.verbose) std::cout << "Time defined: " << info.time_defined << std::endl; - if(info.time_defined) - { + if(info.time_defined) { const LodePNGTime& time = info.time; std::cout << "year: " << time.year << std::endl; std::cout << "month: " << time.month << std::endl; @@ -1122,8 +996,7 @@ void showPNGInfo(Data& data, const Options& options) } } -void showColorStats(Data& data, const Options& options) -{ +void showColorStats(Data& data, const Options& options) { std::cout << (options.use_hex ? std::hex: std::dec); std::vector& image = data.pixels; unsigned& w = data.w; @@ -1137,8 +1010,7 @@ void showColorStats(Data& data, const Options& options) std::cout << "Num unique colors: " << countColors(image, w, h, &rc, &gc, &bc, &ac); std::cout << " (r: " << rc << ", g: " << gc << ", b: " << bc << ", a: " << ac << ")"; std::cout << std::endl; - if(w > 0 && h > 0) - { + if(w > 0 && h > 0) { double avg[4] = {0, 0, 0, 0}; double min[4] = {999999, 999999, 999999, 999999}; double max[4] = {0, 0, 0, 0}; @@ -1163,34 +1035,28 @@ void showColorStats(Data& data, const Options& options) } } -void showRender(Data& data, const Options& options) -{ +void showRender(Data& data, const Options& options) { data.loadPixels(); if(data.error) return; - if(options.rendermode == RM_ASCII) - { + if(options.rendermode == RM_ASCII) { displayAsciiArt(data.pixels, data.w, data.h, options.rendersize); } - if(options.rendermode == RM_HEX) - { + if(options.rendermode == RM_HEX) { displayColorsHex(data.pixels, data.w, data.h, false); } - if(options.rendermode == RM_HEX16) - { + if(options.rendermode == RM_HEX16) { displayColorsHex(data.pixels, data.w, data.h, true); } - if(options.rendermode == RM_PAL) - { + if(options.rendermode == RM_PAL) { displayPalettePixels(data.buffer, options); } } -void showInfos(Data& data, const Options& options) -{ +void showInfos(Data& data, const Options& options) { if(options.show_one_line_summary) showSingleLineSummary(data, options); if(options.show_header || options.show_icc) showHeaderInfo(data, options); if(options.show_color_stats) showColorStats(data, options); @@ -1199,32 +1065,26 @@ void showInfos(Data& data, const Options& options) if(options.show_chunks || options.show_chunks2) displayChunkNames(data, options); if(options.show_filters) displayFilterTypes(data, options); if(options.show_render) showRender(data, options); - if(options.zlib_info || options.zlib_blocks || options.zlib_counts || options.zlib_full) - { + if(options.zlib_info || options.zlib_blocks || options.zlib_counts || options.zlib_full) { printZlibInfo(data, options); } if(data.error) showError(data, options); } -int main(int argc, char *argv[]) -{ +int main(int argc, char *argv[]) { Options options; bool options_chosen = false; std::vector filenames; - for (int i = 1; i < argc; i++) - { + for (int i = 1; i < argc; i++) { std::string s = argv[i]; - if(s.size() > 1 && s[0] == '-' && s[1] != '-') - { + if(s.size() > 1 && s[0] == '-' && s[1] != '-') { // anything that chooses actual set disables the defaults if(s != "-x" && s != "-v") options_chosen = true; - for(size_t j = 1; j < s.size(); j++) - { + for(size_t j = 1; j < s.size(); j++) { char c = s[j]; - if(c == '?') - { + if(c == '?') { showHelp(); return 0; } @@ -1242,61 +1102,50 @@ int main(int argc, char *argv[]) else if(c == 'f') options.show_filters = true; else if(c == 'z') options.zlib_info = true; else if(c == 'b') options.zlib_blocks = true; - else if(c == 'B') - { + else if(c == 'B') { options.zlib_blocks = true; options.zlib_counts = true; } - else if(c == '7') - { + else if(c == '7') { options.zlib_blocks = true; options.zlib_full = true; } - else if(c == 'x') - { + else if(c == 'x') { options.use_hex = true; std::cout << std::hex; } - else if(c == '-') - { + else if(c == '-') { if(s != "--help") std::cout << "Unknown flag: " << s << ". Use -h for help" << std::endl; showHelp(); return 0; } - else - { + else { std::cout << "Unknown flag: " << c << ". Use -h for help" << std::endl; showHelp(); return 0; } } - } - else if(s.size() > 1 && s[0] == '-' && s[1] == '-') - { + } else if(s.size() > 1 && s[0] == '-' && s[1] == '-') { size_t eqpos = 2; while(eqpos < s.size() && s[eqpos] != '=') eqpos++; std::string key = s.substr(2, eqpos - 2); std::string value = (eqpos + 1) < s.size() ? s.substr(eqpos + 1) : ""; - if(key == "help") - { + if(key == "help") { showHelp(); return 0; } - if(key == "mode") - { + if(key == "mode") { if(value == "ascii") options.rendermode = RM_ASCII; else if(value == "hex") options.rendermode = RM_HEX; else if(value == "hex16") options.rendermode = RM_HEX16; else if(value == "palette") options.rendermode = RM_PAL; } - if(key == "size") - { + if(key == "size") { int size = strtoval(value); if(options.rendersize >= 1 && options.rendersize <= 4096) options.rendersize = size; } - if(key == "format") - { + if(key == "format") { if(value == "mix") options.hexformat = HF_MIX; else if(value == "hex") options.hexformat = HF_HEX; } @@ -1304,21 +1153,18 @@ int main(int argc, char *argv[]) else filenames.push_back(s); } - if(filenames.empty()) - { + if(filenames.empty()) { std::cout << "Please provide a filename to preview" << std::endl; showHelp(); return 0; } - if(!options_chosen) - { + if(!options_chosen) { //fill in defaults options.show_header = true; } - for(size_t i = 0; i < filenames.size(); i++) - { + for(size_t i = 0; i < filenames.size(); i++) { if(filenames.size() > 1) { if(i > 0 && !options.show_one_line_summary) std::cout << std::endl; std::cout << filenames[i] << ":";